coder.const
R2026bFold expressions into constants in generated code
Description
instructs the code generator to replace the variable out = coder.const(expr)out with the
constant value of expr in the generated code. If the value of
expr is not a constant during code generation, the code generator
produces an error.
If the code generator is able to evaluate the expression expr
during code generation, the generated code does not contain
any expressions derived from expr.
Otherwise, the generated code contains expressions derived from expr
that are evaluated at run time.
Note
Replacing a constant expression with its value in the generated code is a code optimization that is referred to as constant folding. Because the generated code does not have to evaluate the expression, this optimization reduces the execution time and memory use of the generated code.
[out1,...,outM] = coder.const(
allows you to create a @fun,arg1,...,argN)coder.const call that evaluates the multi-output
function . Other than the ability to return
multiple outputs, this [out1,...,outM] =
fun(arg1,...,argN)coder.const call behaves the same as
coder.const(fun(arg1,...,argN)).
To learn about the behavior of coder.const when
fun accepts zero inputs and returns zero or one outputs, see Tips (MATLAB Coder).
Examples
Input Arguments
Limitations
The code generator does not support using
coder.conston dictionaries, dictionary keys, or dictionary values.
Tips
If
coder.constis unable to constant-fold a function call, try to force constant-folding by making the function call extrinsic. Extrinsic calls are not evaluated by the code generator, these calls are dispatched to MATLAB. For example:function yi = fcn(xi) y = coder.const(feval('rand',1,100)); yi = interp1(y,xi); end
See Reduce Code Generation Time (MATLAB Coder).
Suppose that you call
coder.conston a function handle with zero inputs and zero or one outputs. For example:In such situations, the code generator does not evaluateout = coder.const(@fcn);
fcn, and setsoutto the function handle@fcnitself. To force the evaluation offcnin this special case, call the function explicitly inside thecoder.constcommand. For example:out = coder.const(fcn());
Extended Capabilities
Version History
Introduced in R2013b