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'; open_system(model); set_param(model, 'SimulationCommand', 'update')
Generate Code
Build the model.
slbuild(model)
### Starting build procedure for: rtwdemo_VectorOptimization ### Successful completion of build procedure for: rtwdemo_VectorOptimization Build Summary Top model targets: Model Build Reason Status Build Duration ============================================================================================================================= rtwdemo_VectorOptimization Information cache folder or artifacts were missing. Code generated and compiled. 0h 0m 9.0957s 1 of 1 models built (0 models already up to date) Build duration: 0h 0m 9.7358s
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',... 'rtwdemo_VectorOptimization.c'); 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) - rtb_tmp1_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.
bdclose(model)