This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

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

In the model, there are no data dependencies across the for loop iterations. Therefore, the code generator combines all for loops into one loop. Build the model and view the generated code.

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

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 += (1.0 + (real_T)k) +

Close the model.

Was this topic helpful?