If-Else - MATLAB & Simulink (original) (raw)

Main Content

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: '/Switch' incorporates:

/* End of Switch: '/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: '/Chart' incorporates:

/* End of Chart: '/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: '/MATLAB Function' incorporates:

/* End of MATLAB Function: '/MATLAB Function' */ }

See Also

Topics