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 statement
y = (1:10).^2+Shift;
with
y = coder.const((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 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 i0; static const signed char iv0[10] = { 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 }; for (i0 = 0; i0 < 10; i0++) { y[i0] = (double)iv0[i0] + Shift; } }