Prevent Code Generation for Unused Execution Paths - MATLAB & Simulink (original) (raw)
If a variable controls the flow of an: if, elseif, else statement, or a switch, case, otherwise statement, declare it as constant so that code generation takes place for one branch of the statement only.
Depending on the nature of the control-flow variable, you can declare it as constant in two ways:
- If the variable is local to the MATLABĀ® function, assign it to a constant value in the MATLAB code. For an example, see Prevent Code Generation When Local Variable Controls Flow.
- If the variable is an input to the MATLAB function, you can declare it as constant using coder.Constant. For an example, see Prevent Code Generation When Input Variable Controls Flow.
Prevent Code Generation When Local Variable Controls Flow
- Define a function
SquareOrCube
which takes an input variable,in
, and squares or cubes its elements based on whether the choice variable,ch
, is set tos
orc
:
function out = SquareOrCube(ch,in) %#codegen
if ch=='s'
out = in.^2;
elseif ch=='c'
out = in.^3;
else
out = 0;
end - Generate code for
SquareOrCube
using the codegen command:
codegen -config:lib SquareOrCube -args {'s',zeros(2,2)}
The generated C code squares or cubes the elements of a 2-by-2 matrix based on the input forch
. - Add the following line to the definition of
SquareOrCube
:
The generated C code squares the elements of a 2-by-2 matrix. The choice variable,ch
, and the other branches of theif/elseif/if
statement do not appear in the generated code.
Prevent Code Generation When Input Variable Controls Flow
- Define a function
MathFunc
, which performs different mathematical operations on an input,in
, depending on the value of the input,flag
:
function out = MathFunc(flag,in) %#codegen
%# codegen
switch flag
case 1
out=sin(in);
case 2
out=cos(in);
otherwise
out=sqrt(in);
end - Generate code for
MathFunc
using the codegen command:
codegen -config:lib MathFunc -args {1,zeros(2,2)}
The generated C code performs different math operations on the elements of a 2-by-2 matrix based on the input forflag
. - Generate code for
MathFunc
, declaring the argument,flag
, as a constant using coder.Constant:
codegen -config:lib MathFunc -args {coder.Constant(1),zeros(2,2)}
The generated C code finds the sine of the elements of a 2-by-2 matrix. The variable,flag
, and theswitch/case/otherwise
statement do not appear in the generated code.