Main Content

Optimize Generated Code by Combining Multiple for Constructs

This example shows how the code generator combines for loops. The generated code uses for constructs to represent a variety of modeling patterns, such as a matrix signal or Iterator blocks. Using data dependency analysis, the code generator combines for constructs to reduce static code size and runtime branching.

The benefits of optimizing for loops are:

  • Reducing ROM and RAM consumption.

  • Increasing execution speed.

for Loop Modeling Patterns

In the model, rtwdemo_forloop, the Switch block and MATLAB Function block represent for constructs. In the In1 Block Parameters dialog box, the Port dimensions parameter is set to 10 .

Generate Code

The model does not contain data dependencies across the for loop iterations. Therefore, the code generator combines for loops into one loop. Open the Simulink Coder or Embedded Coder app. Then, generate and view the code.

### Starting build procedure for: rtwdemo_forloop
### Successful completion of build procedure for: rtwdemo_forloop

Build Summary

Top model targets built:

Model            Action                       Rebuild Reason                                    
rtwdemo_forloop  Code generated and compiled  Code generation information file does not exist.  

1 of 1 models built (0 models already up to date)
Build duration: 0h 0m 23.716s

The generated file, rtwdemo_forloop.c, contains the code for the single for loop.

/* Model step function */
void rtwdemo_forloop_step(void)
  int32_T k;

  /* MATLAB Function: '<Root>/Accum' */
  /* MATLAB Function 'Accum': '<S1>:1' */
  /* '<S1>:1:3' */
  /* '<S1>:1:4' */
  rtwdemo_forloop_Y.Out1 = 0.0;

  /* '<S1>:1:5' */
  for (k = 0; k < 10; k++) {
    /* Switch: '<Root>/Switch' incorporates:
     *  Gain: '<Root>/G1'
     *  Gain: '<Root>/G3'
     *  Inport: '<Root>/In1'
     *  Sum: '<Root>/Sum1'
     *  Sum: '<Root>/Sum2'
     *  UnitDelay: '<Root>/Delay'
    if (3.0 * rtwdemo_forloop_U.In1[k] >= 0.0) {
      rtwdemo_forloop_DW.Delay_DSTATE[k] = rtwdemo_forloop_U.In1[k] -
    } else {
      rtwdemo_forloop_DW.Delay_DSTATE[k] = (rtwdemo_forloop_DW.Delay_DSTATE[k] -
        rtwdemo_forloop_U.In1[k]) * 5.0;

    /* End of Switch: '<Root>/Switch' */

    /* MATLAB Function: '<Root>/Accum' */
    /* '<S1>:1:5' */
    /* '<S1>:1:6' */
    rtwdemo_forloop_Y.Out1 += ((real_T)k + 1.0) +

Close the model.

Related Topics