Main Content

Use coder.const with Extrinsic Function Calls

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, use coder.extrinsic.

Reduce Code Generation Time by Using coder.const with feval

Consider this function that folds a computationally intensive expression besselj(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, evaluate besselj(3, zTable) in MATLAB by using feval.

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
??? The input to coder.const cannot be reduced to a constant.

To successfully constant-fold rand(1,100), evaluate it in MATLAB by using feval.

function yi = fcn(xi)
y = coder.const(feval('rand',1,100));
yi = interp1(y,xi);
end

See Also

|

Related Topics