Real-Time Workshop | ![]() ![]() |
Expression Folding Example
As a simple example of how expression folding affects the code generated from a model, consider the model shown in Figure 9-1.
Figure 9-1: Expression Folding Example Model
With expression folding on, this model generates a single-line output computation, as shown in this MdlOutputs function.
void MdlOutputs(int_T tid) { /* tid is required for a uniform function interface. This system * is single rate, and in this case, tid is not accessed. */ UNUSED_PARAMETER(tid); /* Outport: '<Root>/Out1' incorporates: * Product: '<Root>/Product' * Gain: '<Root>/k1' * Inport: '<Root>/In1' * Gain: '<Root>/k2' * Inport: '<Root>/In2' * * Regarding '<Root>/k1': * Gain value: rtP.k1_Gain * * Regarding '<Root>/k2': * Gain value: rtP.k2_Gain */ rtY.Out1 = ((rtP.k1_Gain * rtU.i1) * (rtP.k2_Gain * rtU.i2)); }
The generated comments indicate the block computations that were combined into a single expression. The comments also document the block parameters that appear in the expression.
With expression folding off, the same model computes temporary results for both Gain blocks and the Product block before the final output, as shown in this MdlOutputs function.
void MdlOutputs(int_T tid) { /* local block i/o variables */ real_T rtb_s2; real_T rtb_temp1; /* tid is required for a uniform function interface. This system * is single rate, and in this case, tid is not accessed. */ UNUSED_PARAMETER(tid); /* Gain Block: '<Root>/k1' * Gain value: rtP.k1_Gain */ rtb_temp1 = rtU.i1 * rtP.k1_Gain; /* Gain Block: '<Root>/k2' * Gain value: rtP.k2_Gain */ rtb_s2 = rtU.i2 * rtP.k2_Gain; /* Product Block: '<Root>/Product' */ rtb_temp1 = rtb_temp1 * rtb_s2; /* Outport Block: '<Root>/Out1' */ rtY.Out1 = rtb_temp1; }
For a example of expression folding in the context of a more complex model, link to the exprfolding demo, or type the following command at the MATLAB prompt.
![]() | Expression Folding | Using and Configuring Expression Folding | ![]() |