If-Else
This example shows how to implement an if-else construct by using Simulink® blocks, Stateflow® Charts, and MATLAB® Function block.
C Construct
if (u1 > u2)
{
y1 = u1;
}
else
{
y1 = u2;
}
Modeling Pattern for If-Else: Switch block
One method to create an if-else statement is to use a Switch block from the Simulink > Signal Routing library.
1. Open example model ex_if_else_SL.

The model contains the Switch block with the block parameter Criteria for passing first input of u2~=0. The software selects u1 if u2 is TRUE, otherwise u2 passes.
2. To build the model and generate code, press Ctrl+B.
The code implementing the if-else construct is in the ex_if_else_SL_step function in ex_if_else_SL.c:
/* External inputs (root inport signals with default storage) */
ExternalInputs U;
/* External outputs (root outports fed by signals with default storage) */
ExternalOutputs Y;
/* Model step function */
void ex_if_else_SL_step(void)
{
/* Switch: '<Root>/Switch' incorporates:
* Inport: '<Root>/u1'
* Inport: '<Root>/u2'
* RelationalOperator: '<Root>/Relational Operator'
*/
if (U.u1 > U.u2) {
/* Outport: '<Root>/y1' */
Y.y1 = U.u1;
} else {
/* Outport: '<Root>/y1' */
Y.y1 = U.u2;
}
/* End of Switch: '<Root>/Switch' */
}
Modeling Pattern for If-Else: Stateflow Chart
1. Open example model ex_if_else_SF.

The model contains an If-Else decision pattern that you add by right clicking inside the chart > Add Pattern in Chart > Decision > If-Else.
2. To build the model and generate code, press Ctrl+B.
The code implementing the if-else construct is in the ex_if_else_SF_step function in ex_if_else_SF.c:
/* External inputs (root inport signals with default storage) */
ExternalInputs U;
/* External outputs (root outports fed by signals with default storage) */
ExternalOutputs Y;
/* Model step function */
void ex_if_else_SF_step(void)
{
/* Chart: '<Root>/Chart' incorporates:
* Inport: '<Root>/u1'
* Inport: '<Root>/u2'
*/
/* If-Else */
if (U.u1 >= U.u2) {
/* Outport: '<Root>/y1' */
Y.y1 = U.u1;
} else {
/* Outport: '<Root>/y1' */
Y.y1 = U.u2;
}
/* End of Chart: '<Root>/Chart' */
}
Modeling Pattern for If-Else: MATLAB Function Block
1. Open example model ex_if_else_ML.

2. The MATLAB Function Block contains this function:
function y1 = fcn(u1, u2) if u1 > u2; y1 = u1; else y1 = u2; end
2. To build the model and generate code, press Ctrl+B.
The code implementing the if-else construct is in the ex_if_else_ML_step function in ex_if_else_ML.c:
/* External inputs (root inport signals with default storage) */
ExternalInputs U;
/* External outputs (root outports fed by signals with default storage) */
ExternalOutputs Y;
/* Model step function */
void ex_if_else_ML_step(void)
{
/* MATLAB Function: '<Root>/MATLAB Function' incorporates:
* Inport: '<Root>/u1'
* Inport: '<Root>/u2'
*/
if (U.u1 >= U.u2) {
/* Outport: '<Root>/y1' */
Y.y1 = U.u1;
} else {
/* Outport: '<Root>/y1' */
Y.y1 = U.u2;
}
/* End of MATLAB Function: '<Root>/MATLAB Function' */
}