Main Content

Vector Operation Optimization

This example shows how Simulink® Coder™ optimizes generated code by setting block output that generates vectors to scalars, for blocks such as the Mux, Sum, Gain, and Bus. This optimization reduces stack memory by replacing temporary local arrays with local variables.

Example Model

In the model, rtwdemo_VectorOptimization, the output of Gain blocks G1 and G2 are the vector signals tmp1 and tmp2. These vectors have a width of 10.

model = 'rtwdemo_VectorOptimization';
set_param(model, 'SimulationCommand', 'update')

Generate Code

Build the model.

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

Build Summary

Top model targets built:

Model                       Action                        Rebuild Reason                                    
rtwdemo_VectorOptimization  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 19.506s

The optimized code is in rtwdemo_VectorOptimization.c. The signals tmp1 and tmp2 are the local variables rtb_tmp1 and rtb_tmp2.

cfile = fullfile('rtwdemo_VectorOptimization_grt_rtw',...
coder.example.extractLines(cfile,'/* Model step', '/* Model initialize', 1, 0);
/* Model step function */
void rtwdemo_VectorOptimization_step(void)
  real_T rtb_Sum3_0;
  real_T rtb_tmp1_0;
  real_T rtb_tmp2_0;
  int32_T i;
  for (i = 0; i < 10; i++) {
    /* Gain: '<Root>/G2' incorporates:
     *  UnitDelay: '<Root>/X2'
    rtb_tmp2_0 = 0.3 * rtwdemo_VectorOptimization_DW.X2_DSTATE[i];

    /* Gain: '<Root>/G1' incorporates:
     *  UnitDelay: '<Root>/X1'
    rtb_tmp1_0 = 0.2 * rtwdemo_VectorOptimization_DW.X1_DSTATE[i];

    /* Sum: '<Root>/Sum3' incorporates:
     *  Gain: '<Root>/G3'
     *  Inport: '<Root>/In2'
     *  Sum: '<Root>/Sum1'
     *  Sum: '<Root>/Sum2'
     *  UnitDelay: '<Root>/X3'
    rtb_Sum3_0 = ((rtwdemo_VectorOptimization_U.In2[i] - 0.4 *
                   rtwdemo_VectorOptimization_DW.X3_DSTATE[i]) - rtb_tmp2_0) -

    /* Outport: '<Root>/Out2' */
    rtwdemo_VectorOptimization_Y.Out2[i] = rtb_Sum3_0;

    /* Update for UnitDelay: '<Root>/X3' */
    rtwdemo_VectorOptimization_DW.X3_DSTATE[i] = rtb_tmp2_0;

    /* Update for UnitDelay: '<Root>/X2' */
    rtwdemo_VectorOptimization_DW.X2_DSTATE[i] = rtb_tmp1_0;

    /* Update for UnitDelay: '<Root>/X1' */
    rtwdemo_VectorOptimization_DW.X1_DSTATE[i] = rtb_Sum3_0;

Close the model and code generation report.


Related Topics