Main Content

Fold Function Calls into Constants

This example shows how to specify constants in generated code using coder.const. The code generator folds an expression or a function call in a coder.const statement into a constant in generated code. Because the generated code does not have to evaluate the expression or call the function every time, this optimization reduces the execution time of the generated code.

Write a function AddShift that takes an input Shift and adds it to the elements of a vector. The vector consists of the square of the first 10 natural numbers. AddShift generates this vector.

function y = AddShift(Shift) %#codegen
y = (1:10).^2+Shift;

Generate code for AddShift using the codegen command. Open the Code Generation Report.

codegen -config:lib -launchreport AddShift -args 0

The code generator produces code for creating the vector. It adds Shift to each element of the vector during vector creation. The definition of AddShift in generated code looks as follows:

void AddShift(double Shift, double y[10])
{
  int k;
  for (k = 0; k < 10; k++) {
    y[k] = (double)((1 + k) * (1 + k)) + Shift;
  }
}

Replace the expression (1:10).^2 with coder.const((1:10).^2), and then generate code for AddShift again using the codegen command. Open the Code Generation Report.

codegen -config:lib -launchreport AddShift -args 0

The code generator creates the vector containing the squares of the first 10 natural numbers. In the generated code, it adds Shift to each element of this vector. The definition of AddShift in generated code looks as follows:

void AddShift(double Shift, double y[10])
{
  int i;
  static const signed char iv[10] = { 1, 4, 9, 16, 25, 36, 
                                 49, 64, 81, 100 };

  for (i = 0; i < 10; i++) {
    y[i] = (double)iv[i] + Shift;
  }
}

See Also

Related Topics