Use coder.const with Extrinsic Function Calls - MATLAB & Simulink (original) (raw)
Main Content
You can use coder.const to fold a function call into a constant in the generated code. The code generator evaluates the function call and replaces it with the result of the evaluation. If you make the function call extrinsic, the function call is evaluated by MATLABĀ® instead of by the code generator. Use coder.const
with an extrinsic function call to:
- Reduce code generation time, especially for constant-folding of computationally intensive expressions.
- Force constant-folding when
coder.const
is unable to constant-fold.
To make an individual function call extrinsic, use feval
. To make all calls to a particular function extrinsic, usecoder.extrinsic
.
Reduce Code Generation Time by Using coder.const
with feval
Consider this function that folds a computationally intensive expressionbesselj(3, zTable)
into a constant:
function j = fcn(z) zTable = coder.const(0:0.01:100); jTable = coder.const(besselj(3,zTable)); j = interp1(zTable,jTable,z); end
To make code generation of fcn
faster, evaluatebesselj(3, zTable)
in MATLAB by usingfeval
.
function j = fcn(z) zTable = coder.const(0:0.01:100); jTable = coder.const(feval('besselj',3,zTable)); j = interp1(zTable,jTable,z); end
Force Constant-Folding by Using coder.const
with feval
Consider this function that folds the function call rand(1,100)
into a constant.
function yi = fcn(xi) y = coder.const(rand(1,100)); yi = interp1(y,xi); end
Code generation ends with an error.
codegen fcn -args {0} -config:lib -report
Expression could not be reduced to a constant.
To successfully constant-foldrand(1,100)
, evaluate it in MATLAB by usingfeval
.
function yi = fcn(xi) y = coder.const(feval('rand',1,100)); yi = interp1(y,xi); end