Search code examples
cpointersif-statementsimulinks-function

Why an IF statement is being infringed while output results clearly says it should be executed?


Context: I'm using Matlab/Simulink to simulate a circuit where I need to follow a reference. To simplify it: below reference current then apply more current, above reference current then apply less current. To achieve this, I have to control two devices (Sa and Sb) which basically closes applying a 1 in my code and opens with a 0 (both at the same time).

Now, I'm having these results where the important graphs are S1 Current, S-Function/2 and S-Function/1 and the final question: why, considering the following code, would the S-Function/2, this is THY[], stay at 1 while clearly there are lapses of time where S-Function/1, this is IGBT[], is 0?

  • The next code is inside an S-Function that I use inside Simulink. This is the entire code

    for (i=0; i<width; i++){
    if (*Is[i] <  *Iref[i]){
        //IGBT[] is S-Function/1 and THY[] is S-Function/2
        //Is[] is S1 Current and Iref[] is Reference Current 1
        IGBT[i] = 1.0;
    
        if ( IGBT[i] == 0.0){
        THY[i] = 0.0;   
        }
        else {
        THY[i] = 1.0; 
        }
        }
        else {
        IGBT[i] = 0.0;   
        }
    }
    

Solution

  • I am not sure but I think there is a problem in code:

    for (i=0; i<width; i++){
    if (*Is[i] <  *Iref[i]){
        //IGBT[] is S-Function/1 and THY[] is S-Function/2
        //Is[] is S1 Current and Iref[] is Reference Current 1
        IGBT[i] = 1.0;
    
        if ( IGBT[i] == 0.0){ // condition 1
        // if condition 1 is true then execute this
        THY[i] = 0.0;   
        }
        else {
        // if condition 1 is false then execute this
        THY[i] = 1.0; 
        }
        }
        else {
       // this condition will never be executed
        IGBT[i] = 0.0;   
        }
    }
    

    Now if condition 1 is true then THY[I] = 0.0; will be executed, if condition is false then, THY[i] = 1.0;. In your code

     else {
        IGBT[i] = 0.0;   
        }
    

    is a kind of dead code and it will never be excuted. You need to replace the else followed by if condition with else if(condition) so that second else can be executed.

    Also 1 more thing

    IGBT[i] = 1.0; // IGBT[i] is updated
    
            if ( IGBT[i] == 0.0){ // IGBT[i]  is compared ... wow
    

    I would recommend you to read about comparison between float and double.