Main Content

Minimize Computations and Storage for Intermediate Results at Block Outputs

Expression Folding

Expression folding optimizes code to minimize the computation of intermediate results at block outputs and the storage of such results in temporary buffers or variables. When expression folding is on, the code generator collapses (folds) block computations into a single expression, instead of generating separate code statements and storage declarations for each block in the model. Most Simulink® blocks support expression folding.

Expression folding improves the efficiency of generated code, frequently achieving results that compare favorably to hand-optimized code. In many cases, entire groups of model computations fold into a single, highly optimized line of code.

You can use expression folding in your own inlined S-function blocks. For more information, see S-Functions That Support Expression Folding.

Example Model

Generate Code

With expression folding off, in the explfld.c file, the code generator generates this code.

/* Model step function */
void exprfld_step(void)
{
  /* Gain: '<Root>/Gain' incorporates:
   *  Inport: '<Root>/In1'
   */
  exprfld_B.S1 = exprfld_P.Gain_Gain * exprfld_U.i1;
 
  /* Gain: '<Root>/Gain1' incorporates:
   *  Inport: '<Root>/In2'
   */
  exprfld_B.S2 = exprfld_P.Gain1_Gain * exprfld_U.i2;
 
  /* Outport: '<Root>/Out1' incorporates:
   *  Product: '<Root>/Product'
   */
  exprfld_Y.Out1 = exprfld_B.S1 * exprfld_B.S2;
}

There are separate code statements for both Gain blocks. Before final output, these code statements compute temporary results for the Gain blocks.

Enable Optimization

Expression folding is on by default. To see if expression folding is on for an existing model:

  1. Expression folding is available only when the Configuration Parameters > Signal storage reuse parameter is selected because expression folding operates only on expressions involving local variables. Enable the Signal storage reuse parameter.

  2. When you select Signal storage reuse, the Enable local block outputs, Reuse local block outputs, and Eliminate superfluous local variables (expression folding) parameters are all on by default.

Generate Code with Optimization

With expression folding, the code generator generates a single-line output computation, as shown in the expfld.c file. The generated comments document the block parameters that appear in the expression.

/* Model step function */
void exprfld_step(void)
{
  /* Outport: '<Root>/Out1' incorporates:
   *  Gain: '<Root>/Gain'
   *  Gain: '<Root>/Gain1'
   *  Inport: '<Root>/In1'
   *  Inport: '<Root>/In2'
   *  Product: '<Root>/Product'
   */
  exprfld_Y.Out1 = 
     exprfld_P.Gain_Gain * 
     exprfld_U.i1 * 
     (exprfld_P.Gain1_Gain * exprfld_U.i2);
}

See Also

| | |

Related Topics