Documentation

Optimize Generated Code by Combining Multiple for Constructs

This example shows how code is optimized by combining for loops in the generated code. Code generation uses for constructs to represent a variety of modeling patterns, such as a matrix signal or Iterator blocks. Using data dependency analysis, this optimization combines for constructs to reduce static code size and runtime branching.

The benefits of optimizing for loops are:

  • Reducing the ROM and RAM consumption.

  • Improving the execution speed.

for Loop Modeling Patterns

In the model, rtwdemo_forloop, the Switch block and MATLAB Function block represent for constructs.

Generate Code

In the model, there are no data dependencies across the for loop iterations. Therefore, all loops are combined 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] -
        rtwdemo_forloop_DW.Delay_DSTATE[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) +
      rtwdemo_forloop_DW.Delay_DSTATE[k];

    /* '<S1>:1:5' */
  }
}

/* Model initialize function */
void rtwdemo_forloop_initialize(void)
{
  /* Registration code */

  /* initialize error status */
  rtmSetErrorStatus(rtwdemo_forloop_M, (NULL));

  /* states (dwork) */
  (void) memset((void *)&rtwdemo_forloop_DW, 0,
                sizeof(DW_rtwdemo_forloop_T));

  /* external inputs */
  (void) memset(rtwdemo_forloop_U.In1, 0,
                10U*sizeof(real_T));

  /* external outputs */
  rtwdemo_forloop_Y.Out1 = 0.0;

  /* InitializeConditions for UnitDelay: '<Root>/Delay' */
  memset(&rtwdemo_forloop_DW.Delay_DSTATE[0], 0, 10U * sizeof(real_T));
}

/* Model terminate function */
void rtwdemo_forloop_terminate(void)
{
  /* (no terminate code required) */
}

Close the model.

Was this topic helpful?