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

Open the example model ForLoopConstruct. 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.

model = 'ForLoopConstruct';
open_system(model);

Generate Code

The model does not contain data dependencies across the for loop iterations. Therefore, the code generator combines for loops into one loop.

Build the model.

slbuild(model)
### Starting build procedure for: ForLoopConstruct
### Successful completion of build procedure for: ForLoopConstruct

Build Summary

Top model targets:

Model             Build Reason                                         Status                        Build Duration
===================================================================================================================
ForLoopConstruct  Information cache folder or artifacts were missing.  Code generated and compiled.  0h 0m 16.719s 

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

View the optimized code in ForLoopConstruct.c.

cfile = fullfile('ForLoopConstruct_grt_rtw','ForLoopConstruct.c');
coder.example.extractLines(cfile,'/* Model step', '/* Model initialize', 1, 0);
/* Model step function */
void ForLoopConstruct_step(void)
{
  real_T In1;
  real_T rtb_y;
  int32_T k;

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

  /* '<S1>:1:5' */
  for (k = 0; k < 10; k++) {
    /* Gain: '<Root>/G1' incorporates:
     *  Inport: '<Root>/In1'
     */
    In1 = ForLoopConstruct_U.In1[k];

    /* Switch: '<Root>/Switch' incorporates:
     *  Gain: '<Root>/G1'
     *  Gain: '<Root>/G3'
     *  Sum: '<Root>/Sum1'
     *  Sum: '<Root>/Sum2'
     *  UnitDelay: '<Root>/Delay'
     */
    if (3.0 * In1 >= 0.0) {
      In1 -= ForLoopConstruct_DW.Delay_DSTATE[k];
    } else {
      In1 = (ForLoopConstruct_DW.Delay_DSTATE[k] - In1) * 5.0;
    }

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

    /* MATLAB Function: '<Root>/Accum' */
    /* '<S1>:1:6' */
    rtb_y += ((real_T)k + 1.0) + In1;

    /* Update for UnitDelay: '<Root>/Delay' */
    ForLoopConstruct_DW.Delay_DSTATE[k] = In1;
  }

  /* Outport: '<Root>/Out1' */
  ForLoopConstruct_Y.Out1 = rtb_y;
}

The generated code contains code for the single for loop.

Close the model

bdclose(model)

Related Topics