Do While Loop - MATLAB & Simulink (original) (raw)

Main Content

This example shows how to implement a do while loop construct by using Simulink® blocks and Stateflow® Charts.

C Construct

num_iter = 1; do { flag = func(); num_iter++; } while (flag && num_iter <= 100)

Modeling Pattern for Do While Loop: While Iterator Subsystem block

One method for creating a do while loop is to use a While Iterator Subsystem block from the Simulink > Ports & Subsystems library.

1. Open example model ex_do_while_loop_SL.

The model contains a While Iterator Subsystem block that repeats execution of the contents of the subsystem during a simulation time step.

Observe the following settings in the While Iterator Subsystem:

2. To build the model and generate code, press Ctrl+B.

The code implementing the do while loop is in the ex_do_while_loop_SL_step function in ex_do_while_loop_SL.c:

/* Model step function */ void ex_do_while_loop_SL_step(void) { int32_T s1_iter;

/* Outputs for Iterator SubSystem: '/While Iterator Subsystem' incorporates:

/* SystemReset for Atomic SubSystem: '/func' */ func_Reset();

/* End of SystemReset for SubSystem: '/func' / / End of Outputs for SubSystem: '/While Iterator Subsystem' */ do { func(); s1_iter++; } while (flag && (s1_iter <= 100)); }

Modeling Pattern for Do While Loop: Stateflow Chart

1. Open example model ex_do_while_loop_SF.

In the model, the ex_do_while_loop_SF/Chart executes the do while loop.

The chart contains a While loop decision pattern that you add by selecting Chart > Add Pattern in Chart > Loop > While.

2. To build the model and generate code, press Ctrl+B.

The code implementing the do while loop is in the ex_do_while_loop_SF_step function in ex_do_while_loop_SF.c:

/* Model step function */ void ex_do_while_loop_SF_step(void) { int32_T num_iter;

/* Chart: '/Chart' */ num_iter = 1; do { func(); num_iter++; } while (flag && (num_iter <= 100)); }

See Also

While Iterator Subsystem

Topics