Why is there no "if" condition for a "switch" block in generated code?

I am using MATLAB R2024a with Embedded Coder. In my Simulink model, I have a "Switch" that chooses between two signals. I found the code for the "Switch" block in the generated code. However, it does not contain an "if" statement, and it always sets the output signal to the same value:

/* Switch: '<Root>/Switch' incorporates:
* Inport: '<Root>/In1'
*/
outSignal = myInput1;
I want the code to switch between the two signals I send into the "Switch" block like so:

/* Switch: '<Root>/Switch' incorporates:
* Inport: '<Root>/In1'
* RelationalOperator: '<S1>/Compare'
*/

if (controlSignal) < 0)

{

/* Switch: '<Root>/Switch' incorporates:
* Inport: '<Root>/In1'
*/
outSignal = myInput1;
}

else
{
/* Switch: '<Root>/Switch' incorporates:
* Inport: '<Root>/In2'
*/
outSignal = myInput2;
}
Why is the code missing the "if" condition? Is this a bug?

 Accepted Answer

The "if" condition may not appear in the generated code because Embedded Coder optimizes out one of the code paths. To check this, turn on the "Eliminated / virtual blocks" parameter. With this setting on, the code generation report will show blocks that were eliminated in the generated code. Check if the blocks around the switch block are removed from the code. For more information about this parameter, see its documentation page:
https://www.mathworks.com/help/releases/R2024a/ecoder/ref/eliminatedvirtualblocks.html
To work around this issue, ensure that the control signal going into the "Switch" block can cause the switch block to send either of the data input signals during simulation. If the switch block always sends the same data signal, the code generator might not include an "if" condition in the generated code. For example, if you send an unsigned integer signal into a "Switch" block that checks if the control signal is greater than or equal to zero, the code generator will not generate code for the situation when the control signal is less than zero.

More Answers (0)

Products

Release

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!