Fold Function Calls into Constants
This example shows how to specify constants in generated code usingcoder.const
. The code generator folds an expression or a function call in acoder.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 functionAddShift
that takes an inputShift
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.
functiony = AddShift(Shift)%#codegeny = (1:10).^2+Shift;
Generate code forAddShift
using thecodegen
command. Open the Code Generation Report.
codegen-config:lib-launchreportAddShift-args0
The code generator produces code for creating the vector. It addsShift
to each element of the vector during vector creation. The definition ofAddShift
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
withcoder.const((1:10).^2)
, and then generate code forAddShift
again using thecodegen
command. Open the Code Generation Report.
codegen-config:lib-launchreportAddShift-args0
The code generator creates the vector containing the squares of the first 10 natural numbers. In the generated code, it addsShift
to each element of this vector. The definition ofAddShift
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; } }