Main Content

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.conststatement 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 functionAddShiftthat takes an inputShiftand adds it to the elements of a vector. The vector consists of the square of the first 10 natural numbers.AddShiftgenerates this vector.

functiony = AddShift(Shift)%#codegeny = (1:10).^2+Shift;

Generate code forAddShiftusing thecodegencommand. Open the Code Generation Report.

codegen-config:lib-launchreportAddShift-args0

The code generator produces code for creating the vector. It addsShiftto each element of the vector during vector creation. The definition ofAddShiftin 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).^2withcoder.const((1:10).^2), and then generate code forAddShiftagain using thecodegencommand. 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 addsShiftto each element of this vector. The definition ofAddShiftin 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