User's Guide: Code Generation From MATLAB
User's Guide: Code Generation From MATLAB
User’s Guide
R2011b
How to Contact MathWorks
www.mathworks.com Web
comp.soft-sys.matlab Newsgroup
www.mathworks.com/contact_TS.html Technical Support
508-647-7000 (Phone)
508-647-7001 (Fax)
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
March 2007 Online only New for Release 2007a
September 2007 Online only Revised for Release 2007b
March 2008 Online only Revised for Release 2008a
October 2008 Online only Revised for Release 2008b
March 2009 Online only Revised for Release 2009a
September 2009 Online only Revised for Release 2009b
March 2010 Online only Revised for Release 2010a
September 2010 Online only Revised for Release 2010b
April 2011 Online only Revised for Release 2011a
September 2011 Online only Revised for Release 2011b
Contents
v
Functions Supported for Code Generation
2
About Code Generation for Supported Functions . . . . . 2-2
vi Contents
String Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-90
Structure Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-91
Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-91
vii
When Redundant Copies Occur . . . . . . . . . . . . . . . . . . . . . . 4-8
How to Eliminate Redundant Copies by Defining
Uninitialized Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8
Defining Uninitialized Variables . . . . . . . . . . . . . . . . . . . . . 4-9
viii Contents
Structure Operations Allowed for Code Generation . . . 6-3
ix
Workflows for Using Enumerated Data for Code
Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7
Workflow for Generating Code for Enumerated Data from
MATLAB Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7
Workflow for Generating Code for Enumerated Data from
MATLAB Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . 7-8
x Contents
Toolbox Functions That Support Enumerated Types for
Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-25
xi
When to Define Variable-Size Data Explicitly . . . . . . . . . . 8-20
Using a Matrix Constructor with Nonconstant
Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-21
Inferring Variable Size from Multiple Assignments . . . . . . 8-21
Defining Variable-Size Data Explicitly Using
coder.varsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-23
xii Contents
Toolbox Functions with Variable Sizing Restrictions . . . . . 8-43
xiii
Rules for Using Variable Length Argument Lists for
Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-10
xiv Contents
Unrolling for-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-2
Inlining Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-2
Eliminating Redundant Copies of Function Inputs . . . . . . 12-2
Examples
A
Data Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2
Index
xv
xvi Contents
1
To verify the generated code in the MATLAB environment, you can generate
MEX functions to compare with your original algorithm to determine whether
they are functionally equivalent.
1-2
Prerequisites for Code Generation from MATLAB®
1-3
1 About Code Generation from MATLAB® Algorithms
1-4
Expected Differences in Behavior After Compiling Your MATLAB® Code
Character Size
MATLAB supports 16-bit characters, but the generated code represents
characters in 8 bits, the standard size for most embedded languages like C.
See “Code Generation for Characters” on page 5-6.
1-5
1 About Code Generation from MATLAB® Algorithms
In addition, the generated code does not enforce order of evaluation of logical
operators that do not short circuit.
A = f1() + f2();
as
A = f1();
A = A + f2();
Termination Behavior
Generated code does not match the termination behavior of MATLAB source
code. For example, optimizations remove infinite loops from generated code if
they have no side effects. As a result, the generated code may terminate even
though the corresponding MATLAB code does not.
1-6
Expected Differences in Behavior After Compiling Your MATLAB® Code
1-7
1 About Code Generation from MATLAB® Algorithms
1-8
MATLAB® Language Features Supported for Code Generation
• N-dimensional arrays
• Matrix operations, including deletion of rows and columns
• Variable-sized data (see “How Working with Variable-Size Data Is Different
for Code Generation” on page 8-3)
• Subscripting (see “Limitations on Matrix Indexing Operations for Code
Generation” on page 8-40)
• Complex numbers (see “Code Generation for Complex Data” on page 5-4)
• Numeric classes (see “Supported Variable Types” on page 4-16)
• Double-precision, single-precision, and integer math
• Fixed-point arithmetic (see “Code Acceleration and Code Generation
from MATLAB for Fixed-Point Algorithms” in the Fixed-Point Toolbox™
documentation)
• Program control statements if, switch, for, and while
• All arithmetic, relational, and logical operators
• Subfunctions (see Chapter 11, “Calling Functions for Code Generation”)
• Persistent variables (see “Defining and Initializing Persistent Variables”
on page 4-10)
• Global variables (see “Specifying Global Variable Type and Initial Value in
a Project” in the MATLAB Coder documentation.
• Structures (see Chapter 6, “Code Generation for MATLAB Structures”)
• Characters (see “Code Generation for Characters” on page 5-6)
• Function handles (see Chapter 9, “Code Generation for Function Handles”)
• Frames (see “Working with Frame-Based Signals” in the Simulink®
documentation.
• Variable length input and output argument lists (see Chapter 8, “Code
Generation for Variable-Size Data”)
1-9
1 About Code Generation from MATLAB® Algorithms
1-10
MATLAB® Language Features Not Supported for Code Generation
• Anonymous functions
• Cell arrays
• Java™
• Nested functions
• Objects
• Recursion
• Sparse matrices
• try/catch statements
1-11
1 About Code Generation from MATLAB® Algorithms
1-12
Related Products That Support Code Generation from MATLAB®
1-13
1 About Code Generation from MATLAB® Algorithms
1-14
2
2-2
Functions Supported for Code Generation — Alphabetical List
2-3
2 Functions Supported for Code Generation
2-4
Functions Supported for Code Generation — Alphabetical List
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox™ license to
generate code.
bartlett Signal Processing • Window length must be a constant.
Toolbox Expressions or variables are allowed if their
values do not change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
besselap Signal Processing • Filter order must be a constant. Expressions
Toolbox or variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
2-5
2 Functions Supported for Code Generation
bitconcat Fixed-Point —
Toolbox
bitget MATLAB —
bitget Fixed-Point —
Toolbox
bitmax MATLAB —
bitor MATLAB • Does not support floating-point inputs. The
arguments must belong to an integer class.
bitor Fixed-Point • Not supported for slope-bias scaled fi objects.
Toolbox
bitorreduce Fixed-Point —
Toolbox
2-6
Functions Supported for Code Generation — Alphabetical List
2-7
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
blackmanharris Signal Processing • Window length must be a constant.
Toolbox Expressions or variables are allowed if their
values do not change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
blanks MATLAB —
2-8
Functions Supported for Code Generation — Alphabetical List
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
bsxfun MATLAB —
buttap Signal Processing • Filter order must be a constant. Expressions
Toolbox or variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
butter Signal Processing • Filter coefficients must be constants.
Toolbox Expressions or variables are allowed if their
values do not change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
2-9
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
cart2pol MATLAB —
cart2sph MATLAB —
cast MATLAB —
cat MATLAB —
ceil MATLAB —
ceil Fixed-Point —
Toolbox
cfirpm Signal Processing • All inputs must be constants. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
2-10
Functions Supported for Code Generation — Alphabetical List
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
cheb1ord Signal Processing • All inputs must be constants. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
cheb2ap Signal Processing • All inputs must be constants. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
2-11
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
chebwin Signal Processing • All inputs must be constants. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
2-12
Functions Supported for Code Generation — Alphabetical List
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
cheby2 Signal Processing • All inputs must be constants. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
chol MATLAB —
circshift MATLAB —
class MATLAB —
compan MATLAB —
complex MATLAB —
complex Fixed-Point —
Toolbox
cond MATLAB —
conj MATLAB —
2-13
2 Functions Supported for Code Generation
2-14
Functions Supported for Code Generation — Alphabetical List
2-15
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
de2bi Communications • Requires a Communications System Toolbox
System Toolbox license to generate code.
deal —
deconv MATLAB —
del2 MATLAB —
det MATLAB —
2-16
Functions Supported for Code Generation — Alphabetical List
2-17
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
eig MATLAB • QZ algorithm used in all cases, whereas
MATLAB might use different algorithms
for different inputs. Consequently, V might
represent a different basis of eigenvectors,
and the eigenvalues in D might not be in the
same order as in MATLAB.
• With one input, [V,D] = eig(A), the results
will be similar to those obtained using [V,D]
= eig(A,eye(size(A)),'qz') in MATLAB,
except that for code generation, the columns
of V are normalized.
• Options 'balance', 'nobalance' are not
supported for the standard eigenvalue
problem, and 'chol' is not supported for the
symmetric generalized eigenvalue problem.
• Outputs are always of complex type.
2-18
Functions Supported for Code Generation — Alphabetical List
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
ellipap Signal Processing • All inputs must be constants. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
ellipke MATLAB —
ellipord Signal Processing • All inputs must be constants. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
2-19
2 Functions Supported for Code Generation
2-20
Functions Supported for Code Generation — Alphabetical List
2-21
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
fimath Fixed-Point • Fixed-point signals coming in to a MATLAB
Toolbox Function block from Simulink are assigned
the fimath object defined in the MATLAB
Function dialog in the Model Explorer.
• Use to create fimath objects in generated
code.
2-22
Functions Supported for Code Generation — Alphabetical List
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
2-23
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
fircls Signal Processing • All inputs must be constants. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
fircls1 Signal Processing • All inputs must be constants. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
2-24
Functions Supported for Code Generation — Alphabetical List
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
firpm Signal Processing • All inputs must be constants. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
firpmord Signal Processing • All inputs must be constants. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
2-25
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
fix MATLAB —
fix Fixed-Point —
Toolbox
flattopwin Signal Processing • All inputs must be constants. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
flipdim MATLAB —
fliplr MATLAB —
flipud MATLAB —
floor MATLAB —
floor Fixed-Point —
Toolbox
freqspace MATLAB —
2-26
Functions Supported for Code Generation — Alphabetical List
opt.TolX = tol;
opt.FunValCheck = 'on';
2-27
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
gausswin Signal Processing • All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
gcd MATLAB —
ge MATLAB —
ge Fixed-Point • Not supported for fixed-point signals with
Toolbox different biases.
get Fixed-Point • The syntax structure = get(o) is not
Toolbox supported.
getlsb Fixed-Point —
Toolbox
2-28
Functions Supported for Code Generation — Alphabetical List
gradient MATLAB —
gt MATLAB —
gt Fixed-Point • Not supported for fixed-point signals with
Toolbox different biases.
hadamard MATLAB —
hamming Signal Processing • All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
hankel MATLAB —
hann Signal Processing • All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
2-29
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
idivide MATLAB • opt string must be in lowercase.
• For efficient generated code, MATLAB rules
for divide by zero are supported only for the
'round' option.
2-30
Functions Supported for Code Generation — Alphabetical List
2-31
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
intmax MATLAB —
2-32
Functions Supported for Code Generation — Alphabetical List
2-33
2 Functions Supported for Code Generation
2-34
Functions Supported for Code Generation — Alphabetical List
isreal MATLAB —
isreal Fixed-Point —
Toolbox
isrow MATLAB —
isrow Fixed-Point —
Toolbox
isscalar MATLAB —
isscalar Fixed-Point —
Toolbox
issigned Fixed-Point —
Toolbox
issorted MATLAB —
issparse MATLAB —
isstruct MATLAB —
istrellis Communications • Requires a Communications System Toolbox
System Toolbox license to generate code.
isvector MATLAB —
2-35
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
kaiserord Signal Processing • Computation performed at run time.
Toolbox
• Requires DSP System Toolbox license to
generate code.
kron MATLAB —
label2rgb Image Processing Referring to the standard syntax:
Toolbox
RGB = label2rgb(L, map, zerocolor, order)
2-36
Functions Supported for Code Generation — Alphabetical List
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
linsolve MATLAB • The option structure must be a constant.
• Supports only a scalar option structure input.
It does not support arrays of option structures.
• Only optimizes these cases:
- UT
- LT
- UHESS = true (the TRANSA can be either
true or false)
- SYM = true and POSDEF = true
All other options are equivalent to using
mldivide.
2-37
2 Functions Supported for Code Generation
2-38
Functions Supported for Code Generation — Alphabetical List
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
mean MATLAB —
mean Fixed-Point —
Toolbox
median MATLAB —
median Fixed-Point —
Toolbox
meshgrid MATLAB —
min MATLAB —
min Fixed-Point —
Toolbox
minus MATLAB —
minus Fixed-Point • Any non-fi input must be constant; that is,
Toolbox its value must be known at compile time so
that it can be cast to a fi object.
mldivide MATLAB —
mod MATLAB • Performs all arithmetic in the output class.
Hence, results might not match MATLAB due
to different rounding errors.
2-39
2 Functions Supported for Code Generation
2-40
Functions Supported for Code Generation — Alphabetical List
2-41
2 Functions Supported for Code Generation
not MATLAB —
nthroot MATLAB —
2-42
Functions Supported for Code Generation — Alphabetical List
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
ones MATLAB • Dimensions must be real, nonnegative,
integer constants
or MATLAB —
orth MATLAB • Might return a different basis than MATLAB
2-43
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
pascal MATLAB —
permute MATLAB —
permute Fixed-Point —
Toolbox
pi MATLAB —
pinv MATLAB —
planerot MATLAB —
plus MATLAB —
plus Fixed-Point • Any non-fi input must be constant; that is,
Toolbox its value must be known at compile time so
that it can be cast to a fi object.
pol2cart MATLAB —
poly MATLAB • Does not discard nonfinite input values
• Complex input always produces complex
output
poly2trellis Communications • Requires a Communications System Toolbox
System Toolbox license to generate code.
polyfit MATLAB —
polyval MATLAB —
2-44
Functions Supported for Code Generation — Alphabetical List
2-45
2 Functions Supported for Code Generation
2-46
Functions Supported for Code Generation — Alphabetical List
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
reinterpretcast Fixed-Point —
Toolbox
rem MATLAB • Performs all arithmetic in the output class.
Hence, results might not match MATLAB due
to different rounding errors.
2-47
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
rescale Fixed-Point —
Toolbox
reshape MATLAB —
reshape Fixed-Point —
Toolbox
roots MATLAB • Output is always variable size
• Output is always complex
• Roots may not be in the same order as
MATLAB
• Roots of poorly conditioned polynomials may
not match MATLAB
rosser MATLAB —
rot90 MATLAB —
round MATLAB —
round Fixed-Point —
Toolbox
2-48
Functions Supported for Code Generation — Alphabetical List
secd MATLAB —
sech MATLAB —
setdiff MATLAB • When rows is not specified:
- Inputs must be row vectors.
- If a vector is variable-sized, its first
dimension must have a fixed length of 1.
- The input [] is not supported. Use a 1-by-0
input, for example, zeros(1,0) to represent
the empty set.
- Empty outputs are always row vectors,
1-by-0, never 0-by-0.
• When rows is specified, output i is always
a column vector. If i is empty, it is 0-by-1,
never 0-by-0, even if the output c is 0-by-0.
• Inputs must already be sorted in ascending
order. The first output is always sorted in
ascending order.
• Complex inputs must be single or double.
2-49
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
shiftdim MATLAB Second argument must be a constant.
2-50
Functions Supported for Code Generation — Alphabetical List
2-51
2 Functions Supported for Code Generation
2-52
Functions Supported for Code Generation — Alphabetical List
2-53
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
tril MATLAB • If supplied, the argument representing the
order of the diagonal matrix must be a real
and scalar integer value.
tril Fixed-Point • If supplied, the index, k, must be a real and
Toolbox scalar integer value that is not a fi object.
triu MATLAB • If supplied, the argument representing the
order of the diagonal matrix must be a real
and scalar integer value.
triu Fixed-Point • If supplied, the index, k, must be a real and
Toolbox scalar integer value that is not a fi object.
true MATLAB • Dimensions must be real, nonnegative,
integer constants
2-54
Functions Supported for Code Generation — Alphabetical List
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
typecast MATLAB • Value of string input argument type must be
lower case
• You might receive a size error when you use
typecast with inheritance of input port data
types in MATLAB Function blocks. To avoid
this error, specify the block’s input port data
types explicitly.
ufi Fixed-Point —
Toolbox
uint8, uint16, uint32 MATLAB —
uint8, uint16, uint32 Fixed-Point —
Toolbox
uminus MATLAB —
uminus Fixed-Point —
Toolbox
2-55
2 Functions Supported for Code Generation
2-56
Functions Supported for Code Generation — Alphabetical List
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Variable-size inputs are not supported.
• Requires DSP System Toolbox license to
generate code
uplus MATLAB —
uplus Fixed-Point —
Toolbox
upperbound Fixed-Point —
Toolbox
upsample Signal Processing Either declare input n as constant, or use the
Toolbox assert function in the calling function to set
upper bounds for n. For example,
assert(n<10)
vander MATLAB —
var MATLAB —
vertcat Fixed-Point —
Toolbox
2-57
2 Functions Supported for Code Generation
Specifying constants
To specify a constant input for codegen, use
coder.Constant. For more information, see
“Specifying Constant Inputs at the Command
Line”.
• Requires DSP System Toolbox license to
generate code.
zeros MATLAB • Dimensions must be real, nonnegative,
integer constants
zp2tf MATLAB —
2-58
Functions Supported for Code Generation — Categorical List
2-59
2 Functions Supported for Code Generation
In this section...
“Relational Operator Functions” on page 2-82
“Rounding and Remainder Functions” on page 2-83
“Set Functions” on page 2-83
“Signal Processing Functions in MATLAB” on page 2-84
“Signal Processing Toolbox Functions” on page 2-84
“Special Values” on page 2-89
“Specialized Math” on page 2-89
“Statistical Functions” on page 2-90
“String Functions” on page 2-90
“Structure Functions” on page 2-91
“Trigonometric Functions” on page 2-91
2-60
Functions Supported for Code Generation — Categorical List
Function Description
ctranspose Complex conjugate transpose (')
idivide Integer division with rounding option
isa Determine if input is object of given class
ldivide Left array divide
minus Minus (-)
mldivide Left matrix divide (\)
mpower Equivalent of array power operator (.^)
mrdivide Right matrix divide
mtimes Matrix multiply (*)
plus Plus (+)
power Array power
rdivide Right array divide
times Array multiply
transpose Matrix transpose (')
uminus Unary minus (-)
uplus Unary plus (+)
Casting Functions
Data Type Description
cast Cast variable to different data type
char Create character array (string)
2-61
2 Functions Supported for Code Generation
2-62
Functions Supported for Code Generation — Categorical List
Function Description
real Return the real part of a complex number
unwrap Correct phase angles to produce smoother phase plots
2-63
2 Functions Supported for Code Generation
2-64
Functions Supported for Code Generation — Categorical List
Exponential Functions
Function Description
exp Exponential
expm Matrix exponential
expm1 Compute exp(x)-1 accurately for small values of x
factorial Factorial function
log Natural logarithm
log2 Base 2 logarithm and dissect floating-point numbers into exponent and
mantissa
log10 Common (base 10) logarithm
log1p Compute log(1+x) accurately for small values of x
nextpow2 Next higher power of 2
nthroot Real nth root of real numbers
reallog Natural logarithm for nonnegative real arrays
realpow Array power for real-only output
realsqrt Square root for nonnegative real arrays
sqrt Square root
2-65
2 Functions Supported for Code Generation
2-66
Functions Supported for Code Generation — Categorical List
• All general limitations of C/C++ code generated from MATLAB apply. See
“MATLAB Language Features Not Supported for Code Generation” on page
1-11 for more information.
Function Remarks/Limitations
abs N/A
add N/A
all N/A
any N/A
bitand Not supported for slope-bias scaled fi objects.
bitandreduce N/A
bitcmp N/A
bitconcat N/A
bitget N/A
bitor Not supported for slope-bias scaled fi objects.
bitorreduce N/A
bitreplicate N/A
bitrol N/A
bitror N/A
bitset N/A
bitshift N/A
bitsliceget N/A
bitsll N/A
bitsra N/A
bitsrl N/A
bitxor Not supported for slope-bias scaled fi objects.
bitxorreduce N/A
ceil N/A
complex N/A
2-67
2 Functions Supported for Code Generation
Function Remarks/Limitations
conj N/A
conv • Variable-sized inputs are only supported when the
SumMode property of the governing fimath is set to
Specify precision or Keep LSB.
• For variable-sized signals, you may see different
results between generated code and MATLAB.
- In the generated code, the output for
variable-sized signals is always computed using
the SumMode property of the governing fimath.
- In MATLAB, the output for variable-sized
signals is computed using the SumMode property
of the governing fimath when both inputs
are nonscalar. However, if either input is a
scalar, MATLAB computes the output using the
ProductMode of the governing fimath.
convergent N/A
cordicabs Variable-size signals are not supported.
cordicangle Variable-size signals are not supported.
cordicatan2 Variable-size signals are not supported.
cordiccart2pol Variable-size signals are not supported.
cordiccexp Variable-size signals are not supported.
cordiccos Variable-size signals are not supported.
cordicpol2cart Variable-size signals are not supported.
cordicrotate Variable-size signals are not supported.
cordicsin Variable-size signals are not supported.
cordicsincos Variable-size signals are not supported.
ctranspose N/A
diag If supplied, the index, k, must be a real and scalar
integer value that is not a fi object.
disp —
2-68
Functions Supported for Code Generation — Categorical List
Function Remarks/Limitations
divide • Any non-fi input must be constant; that is, its
value must be known at compile time so that it can
be cast to a fi object.
• Complex and imaginary divisors are not supported.
• Code generation in MATLAB does not support the
syntax T.divide(a,b).
double N/A
end N/A
eps • Supported for scalar fixed-point signals only.
• Supported for scalar, vector, and matrix, fi single
and fi double signals.
eq Not supported for fixed-point signals with different
biases.
fi • Use to create a fixed-point constant or variable in
the generated code.
• The default constructor syntax without any input
arguments is not supported.
• The syntax
fi('PropertyName',PropertyValue...)
is not supported. To use property
name/property value pairs, you must first
specify the value v of the fi object as in
fi(v,'PropertyName',PropertyValue...).
• Works for all input values when complete
numerictype information of the fi object is
provided.
• Works only for constant input values (value of
input must be known at compile time) when
complete numerictype information of the fi object
is not specified.
2-69
2 Functions Supported for Code Generation
Function Remarks/Limitations
2-70
Functions Supported for Code Generation — Categorical List
Function Remarks/Limitations
isfinite N/A
isinf N/A
isnan N/A
isnumeric N/A
isnumerictype N/A
isreal N/A
isrow N/A
isscalar N/A
issigned N/A
isvector N/A
le Not supported for fixed-point signals with different
biases.
length N/A
logical N/A
lowerbound N/A
lsb • Supported for scalar fixed-point signals only.
• Supported for scalar, vector, and matrix, fi single
and double signals.
lt Not supported for fixed-point signals with different
biases.
max N/A
mean N/A
median N/A
min N/A
minus Any non-fi input must be constant; that is, its value
must be known at compile time so that it can be cast
to a fi object.
2-71
2 Functions Supported for Code Generation
Function Remarks/Limitations
mpower • The exponent input, k, must be constant; that is,
its value must be known at compile time.
• Variable-sized inputs are only supported when the
SumMode property of the governing fimath is set to
Specify precision or Keep LSB.
• For variable-sized signals, you may see different
results between the generated code and MATLAB.
- In the generated code, the output for
variable-sized signals is always computed using
the SumMode property of the governing fimath.
- In MATLAB, the output for variable-sized
signals is computed using the SumMode property
of the governing fimath when the first input,
a, is nonscalar. However, when a is a scalar,
MATLAB computes the output using the
ProductMode of the governing fimath.
mpy When you provide complex inputs to the mpy function
inside of a MATLAB Function block, you must declare
the input as complex before running the simulation.
To do so, go to the Ports and data manager and set
the Complexity parameter for all known complex
inputs to On.
mrdivide N/A
mtimes • Any non-fi input must be constant; that is, its
value must be known at compile time so that it can
be cast to a fi object.
• Variable-sized inputs are only supported when the
SumMode property of the governing fimath is set to
Specify precision or Keep LSB.
• For variable-sized signals, you may see different
results between the generated code and MATLAB.
2-72
Functions Supported for Code Generation — Categorical List
Function Remarks/Limitations
2-73
2 Functions Supported for Code Generation
Function Remarks/Limitations
rdivide N/A
real N/A
realmax N/A
realmin N/A
reinterpretcast N/A
repmat N/A
rescale N/A
reshape N/A
round N/A
sfi N/A
sign N/A
single N/A
size N/A
sort N/A
sqrt • Complex and [Slope Bias] inputs error out.
• Negative inputs yield a 0 result.
sub N/A
subsasgn N/A
subsref N/A
sum Variable-sized inputs are only supported when the
SumMode property of the governing fimath is set to
Specify precision or Keep LSB.
2-74
Functions Supported for Code Generation — Categorical List
Function Remarks/Limitations
times • Any non-fi input must be constant; that is, its
value must be known at compile time so that it can
be cast to a fi object.
• When you provide complex inputs to the times
function inside of a MATLAB Function block, you
must declare the input as complex before running
the simulation. To do so, go to the Ports and data
manager and set the Complexity parameter for
all known complex inputs to On.
transpose N/A
tril If supplied, the index, k, must be a real and scalar
integer value that is not a fi object.
triu If supplied, the index, k, must be a real and scalar
integer value that is not a fi object.
ufi N/A
uint8, uint16, uint32N/A
uminus N/A
uplus N/A
upperbound N/A
vertcat N/A
Histogram Functions
Function Description
hist Non-graphical histogram
histc Histogram count
2-75
2 Functions Supported for Code Generation
Function Remarks/Limitations
fspecial All inputs must be constants at compilation time. Expressions or
variables are allowed if their values do not change.
label2rgb Referring to the standard syntax:
• Submit at least two input arguments: the label matrix, L, and the
colormap matrix, map.
• map must be an n-by-3, double, colormap matrix. You cannot use
a string containing the name of a MATLAB colormap function or a
function handle of a colormap function.
• If you set the boundary color zerocolor to the same color as one of
the regions, label2rgb will not issue a warning.
• If you supply a value for order, it must be 'noshuffle'.
2-76
Functions Supported for Code Generation — Categorical List
Function Description
pol2cart Transform polar or cylindrical coordinates to Cartesian
sph2cart Transform spherical coordinates to Cartesian
Linear Algebra
Function Description
linsolve Solve linear system of equations
2-77
2 Functions Supported for Code Generation
Function Description
or Logical OR (||)
xor Logical exclusive-OR
2-78
Functions Supported for Code Generation — Categorical List
Function Description
diag Return a matrix formed around the specified diagonal vector and the
specified diagonal (0, 1, 2,...) it occupies
diff Differences and approximate derivatives
dot Vector dot product
eig Eigenvalues and eigenvectors
eye Identity matrix
false Return an array of 0s for the specified dimensions
find Find indices and values of nonzero elements
flipdim Flip array along specified dimension
fliplr Flip matrix left to right
flipud Flip matrix up to down
full Convert sparse matrix to full matrix
hadamard Hadamard matrix
hankel Hankel matrix
hilb Hilbert matrix
ind2sub Subscripts from linear index
inv Inverse of a square matrix
invhilb Inverse of Hilbert matrix
ipermute Inverse permute dimensions of array
iscolumn True if input is a column vector
isempty Determine whether array is empty
isequal Test arrays for equality
isequalwithequalnans Test arrays for equality, treating NaNs as equal
isfinite Detect finite elements of an array
isfloat Determine if input is floating-point array
isinf Detect infinite elements of an array
isinteger Determine if input is integer array
2-79
2 Functions Supported for Code Generation
Function Description
islogical Determine if input is logical array
ismatrix True if input is a matrix
isnan Detect NaN elements of an array
isrow True if input is a row vector
issparse Determine whether input is sparse
isvector Determine whether input is vector
kron Kronecker tensor product
length Return the length of a matrix
linspace Generate linearly spaced vectors
logspace Generate logarithmically spaced vectors
lu Matrix factorization
magic Magic square
2-80
Functions Supported for Code Generation — Categorical List
Function Description
prod Product of array element
qr Orthogonal-triangular decomposition
randperm Random permutation
rank Rank of matrix
rcond Matrix reciprocal condition number estimate
repmat Replicate and tile an array
reshape Reshape one array into the dimensions of another
rosser Classic symmetric eigenvalue test problem
rot90 Rotate matrix 90 degrees
shiftdim Shift dimensions
sign Signum function
size Return the size of a matrix
sort Sort elements in ascending or descending order
sortrows Sort rows in ascending order
squeeze Remove singleton dimensions
sub2ind Single index from subscripts
subspace Angle between two subspaces
sum Sum of matrix elements
toeplitz Toeplitz matrix
trace Sum of diagonal elements
tril Extract lower triangular part
triu Extract upper triangular part
true Return an array of logical (Boolean) 1s for the specified dimensions
vander Vandermonde matrix
wilkinson Wilkinson’s eigenvalue test matrix
zeros Create a matrix of all zeros
2-81
2 Functions Supported for Code Generation
Polynomial Functions
Function Description
poly Polynomial with specified roots
polyfit Polynomial curve fitting
polyval Polynomial evaluation
roots Polynomial roots
2-82
Functions Supported for Code Generation — Categorical List
Set Functions
Function Description
intersect Find set intersection of two vectors
ismember Array elements that are members of set
issorted Determine whether set elements are in sorted order
setdiff Find set difference of two vectors
setxor Find set exclusive OR of two vectors
union Find set union of two vectors
unique Find unique elements of vector
2-83
2 Functions Supported for Code Generation
Note All of these functions require a DSP System Toolbox license to generate
code.
2-84
Functions Supported for Code Generation — Categorical List
Function Remarks/Limitations
barthannwin Window length must be a constant. Expressions or variables are
allowed if their values do not change.
bartlett Window length must be a constant. Expressions or variables are
allowed if their values do not change.
besselap Filter order must be a constant. Expressions or variables are allowed if
their values do not change.
bitrevorder —
blackman Window length must be a constant. Expressions or variables are
allowed if their values do not change.
blackmanharris Window length must be a constant. Expressions or variables are
allowed if their values do not change.
bohmanwin Window length must be a constant. Expressions or variables are
allowed if their values do not change.
buttap Filter order must be a constant. Expressions or variables are allowed if
their values do not change.
butter Filter coefficients must be constants. Expressions or variables are
allowed if their values do not change.
buttord All inputs must be constants. Expressions or variables are allowed if
their values do not change.
cfirpm All inputs must be constants. Expressions or variables are allowed if
their values do not change.
cheb1ap All inputs must be constants. Expressions or variables are allowed if
their values do not change.
cheb2ap All inputs must be constants. Expressions or variables are allowed if
their values do not change.
cheb1ord All inputs must be constants. Expressions or variables are allowed if
their values do not change.
2-85
2 Functions Supported for Code Generation
Function Remarks/Limitations
cheb2ord All inputs must be constants. Expressions or variables are allowed if
their values do not change.
chebwin All inputs must be constants. Expressions or variables are allowed if
their values do not change.
cheby1 All Inputs must be constants. Expressions or variables are allowed if
their values do not change.
cheby2 All inputs must be constants. Expressions or variables are allowed if
their values do not change.
dct Length of transform dimension must be a power of two. If specified, the
pad or truncation value must be constant. Expressions or variables are
allowed if their values do not change.
downsample —
dpss All inputs must be constants. Expressions or variables are allowed if
their values do not change.
ellip Inputs must be constant. Expressions or variables are allowed if their
values do not change.
ellipap All inputs must be constants. Expressions or variables are allowed if
their values do not change.
ellipord All inputs must be constants. Expressions or variables are allowed if
their values do not change.
filtfilt Filter coefficients must be constants. Expressions or variables are
allowed if their values do not change.
fir1 All inputs must be constants. Expressions or variables are allowed if
their values do not change.
fir2 All inputs must be constants. Expressions or variables are allowed if
their values do not change.
fircls All inputs must be constants. Expressions or variables are allowed if
their values do not change.
fircls1 All inputs must be constants. Expressions or variables are allowed if
their values do not change.
2-86
Functions Supported for Code Generation — Categorical List
Function Remarks/Limitations
firls All inputs must be constants. Expressions or variables are allowed if
their values do not change.
firpm All inputs must be constants. Expressions or variables are allowed if
their values do not change.
firpmord All inputs must be constants. Expressions or variables are allowed if
their values do not change.
firrcos All inputs must be constants. Expressions or variables are allowed if
their values do not change.
flattopwin All inputs must be constants. Expressions or variables are allowed if
their values do not change.
freqz freqz with no output arguments produces a plot only when the function
call terminates in a semicolon. See “freqz With No Output Arguments”.
gaussfir All inputs must be constant. Expressions or variables are allowed if
their values do not change.
gausswin All inputs must be constant. Expressions or variables are allowed if
their values do not change.
hamming All inputs must be constant. Expressions or variables are allowed if
their values do not change.
hann All inputs must be constant. Expressions or variables are allowed if
their values do not change.
idct Length of transform dimension must be a power of two. If specified, the
pad or truncation value must be constant. Expressions or variables are
allowed if their values do not change.
intfilt All inputs must be constant. Expressions or variables are allowed if
their values do not change.
kaiser All inputs must be constant. Expressions or variables are allowed if
their values do not change.
kaiserord —
levinson If specified, the order of recursion must be a constant. Expressions or
variables are allowed if their values do not change.
2-87
2 Functions Supported for Code Generation
Function Remarks/Limitations
maxflat All inputs must be constant. Expressions or variables are allowed if
their values do not change.
nuttallwin All inputs must be constant. Expressions or variables are allowed if
their values do not change.
parzenwin All inputs must be constant. Expressions or variables are allowed if
their values do not change.
rectwin All inputs must be constant. Expressions or variables are allowed if
their values do not change.
resample The upsampling and downsampling factors must be specified as
constants. Expressions or variables are allowed if their values do not
change.
sgolay All inputs must be constant. Expressions or variables are allowed if
their values do not change.
sosfilt —
taylorwin All inputs must be constant. Expressions or variables are allowed if
their values do not change.
triang All inputs must be constant. Expressions or variables are allowed if
their values do not change.
tukeywin All inputs must be constant. Expressions or variables are allowed if
their values do not change.
upfirdn • Filter coefficients, upsampling factor, and downsampling factor must
be constants. Expressions or variables are allowed if their values
do not change.
• Variable-size inputs are not supported.
upsample Either declare input n as constant, or use the assert function in the
calling function to set upper bounds for n. For example,
assert(n<10)
xcorr —
yulewalk If specified, the order of recursion must be a constant. Expressions or
variables are allowed if their values do not change.
2-88
Functions Supported for Code Generation — Categorical List
Special Values
Symbol Description
eps Floating-point relative accuracy
inf IEEE® arithmetic representation for positive infinity
intmax Largest possible value of specified integer type
intmin Smallest possible value of specified integer type
NaN or nan Not a number
pi Ratio of the circumference to the diameter for a circle
rand Uniformly distributed pseudorandom numbers
randn Normally distributed random numbers
realmax Largest positive floating-point number
realmin Smallest positive floating-point number
Specialized Math
Symbol Description
beta Beta function
betainc Incomplete beta function
betaln Logarithm of beta function
ellipke Complete elliptic integrals of first and second kind
erf Error function
erfc Complementary error function
erfcinv Inverse of complementary error function
erfcx Scaled complementary error function
erfinv Inverse error function
expint Exponential integral
gamma Gamma function
2-89
2 Functions Supported for Code Generation
Symbol Description
gammainc Incomplete gamma function
gammaln Logarithm of the gamma function
Statistical Functions
Function Description
corrcoef Correlation coefficients
mean Average or mean value of array
median Median value of array
mode Most frequent values in array
std Standard deviation
var Variance
String Functions
Function Description
bin2dec Convert binary number string to decimal number
bitmax Maximum double-precision floating-point integer
blanks Create string of blank characters
char Create character array (string)
hex2dec Convert hexadecimal number string to decimal number
ischar True for character array (string)
strcmp Return a logical result for the comparison of two strings; limited to
strings known at compile time
2-90
Functions Supported for Code Generation — Categorical List
Structure Functions
Function Description
isfield Determine whether input is structure array field
struct Create structure
isstruct Determine whether input is a structure
Trigonometric Functions
Function Description
acos Inverse cosine
acosd Inverse cosine; result in degrees
acosh Inverse hyperbolic cosine
acot Inverse cotangent; result in radians
acotd Inverse cotangent; result in degrees
acoth Inverse hyperbolic cotangent
acsc Inverse cosecant; result in radians
acscd Inverse cosecant; result in degrees
acsch Inverse cosecant and inverse hyperbolic cosecant
asec Inverse secant; result in radians
asecd Inverse secant; result in degrees
asech Inverse hyperbolic secant
asin Inverse sine
asinh Inverse hyperbolic sine
atan Inverse tangent
atan2 Four quadrant inverse tangent
atand Inverse tangent; result in degrees
atanh Inverse hyperbolic tangent
2-91
2 Functions Supported for Code Generation
Function Description
cos Cosine
cosd Cosine; result in degrees
cosh Hyperbolic cosine
cot Cotangent; result in radians
cotd Cotangent; result in degrees
coth Hyperbolic cotangent
csc Cosecant; result in radians
cscd Cosecant; result in degrees
csch Hyperbolic cosecant
hypot Square root of sum of squares
sec Secant; result in radians
secd Secant; result in degrees
sech Hyperbolic secant
sin Sine
sind Sine; result in degrees
sinh Hyperbolic sine
tan Tangent
tand Tangent; result in degrees
tanh Hyperbolic tangent
2-92
3
3-2
Computer Vision System Toolbox™ System Objects
Object Description
Analysis & Enhancement
vision.BoundaryTracer Trace object boundaries in binary images
vision.ContrastAdjuster Adjust image contrast by linear scaling
vision.Deinterlacer Remove motion artifacts by deinterlacing input
video signal
vision.EdgeDetector Find edges of objects in images
vision.ForegroundDetector Detect foreground using Gaussian Mixture
Models
vision.HistogramEqualizer Enhance contrast of images using histogram
equalization
vision.TemplateMatcher Perform template matching by shifting
template over image
Conversions
vision.Autothresholder Convert intensity image to binary image
vision.ChromaResampler Downsample or upsample chrominance
components of images
vision.ColorSpaceConverter Convert color information between color spaces
vision.DemosaicInterpolator Demosaic Bayer’s format images
vision.GammaCorrector Apply or remove gamma correction from
images or video streams
3-3
3 System Objects Supported for Code Generation
Object Description
vision.ImageComplementer Compute complement of pixel values in binary,
intensity, or RGB images
vision.ImageDataTypeConverter Convert and scale input image to specified
output data type
Filtering
vision.Convolver Compute 2-D discrete convolution of two input
matrices
vision.ImageFilter Perform 2-D FIR filtering of input matrix
vision.MedianFilter 2D median filtering
Geometric Transformations
vision.GeometricRotator Rotate image by specified angle
vision.GeometricRotator Enlarge or shrink image size
3-4
Computer Vision System Toolbox™ System Objects
Object Description
vision.MorphologicalErode Perform morphological erosion on an image
vision.MorphologicalOpen Perform morphological opening on an image
Sinks
Statistics
vision.Autocorrelator Compute 2-D autocorrelation of input matrix
vision.BlobAnalysis Compute statistics for connected regions in a
binary image
vision.Crosscorrelator Compute 2-D cross-correlation of two input
matrices
vision.Histogram Generate histogram of each input matrix
vision.LocalMaximaFinder Find local maxima in matrices
vision.Maximum Find maximum values in input or sequence of
inputs
vision.Mean Find mean value of input or sequence of inputs
vision.Median Find median values in an input
vision.Minimum Find minimum values in input or sequence of
inputs
3-5
3 System Objects Supported for Code Generation
Object Description
vision.PSNR Compute peak signal-to-noise ratio (PSNR)
between images
vision.StandardDeviation Find standard deviation of input or sequence
of inputs
vision.Variance Find variance values in an input or sequence
of inputs
Text & Graphics
vision.AlphaBlender Combine images, overlay images, or highlight
selected pixels
vision.MarkerInserter Draw markers on output image
vision.ShapeInserter Draw rectangles, lines, polygons, or circles on
images
vision.TextInserter Draw text on image or video stream
Transforms
vision.DCT Compute 2-D discrete cosine transform
vision.FFT Two-dimensional discrete Fourier transform
vision.HoughLines Find Cartesian coordinates of lines that are
described by rho and theta pairs
vision.HoughTransform Find lines in images via Hough transform
vision.IDCT Compute 2-D inverse discrete cosine transform
vision.IFFT Two–dimensional inverse discrete Fourier
transform
vision.Pyramid Perform Gaussian pyramid decomposition
Utilities
vision.ImagePadder Pad or crop input image along its rows,
columns, or both
3-6
Communications System Toolbox™ System Objects
Object Description
Source Coding
comm.DifferentialDecoder Decode binary signal using differential decoding
comm.DifferentialEncoder Encode binary signal using differential coding
Channels
comm.AWGNChannel Add white Gaussian noise to input signal
comm.BinarySymmetricChannel Introduce binary errors
Equalizers
comm.MLSEEqualizer Equalize using maximum likelihood sequence
estimation
Filters
comm.IntegrateAndDumpFilter Integrate discrete-time signal with periodic resets
Measurements
comm.EVM Measure error vector magnitude
comm.MER Measure modulation error ratio
Sources
comm.BarkerCode Generate Barker code
comm.HadamardCode Generate Hadamard code
comm.KasamiSequence Generate a Kasami sequence
comm.OVSFCode Generate OVSF code
3-7
3 System Objects Supported for Code Generation
Object Description
comm.PNSequence Generate a pseudo-noise (PN) sequence
comm.WalshCode Generate Walsh code from orthogonal set of codes
Error Detection and Correction – Convolutional Coding
comm.ConvolutionalEncoder Convolutionally encode binary data
comm.ViterbiDecoder Decode convolutionally encoded data using Viterbi
algorithm
Error Detection and Correction – Cyclic Redundancy Check Coding
comm.CRCDetector Detect errors in input data using cyclic redundancy
code
comm.CRCGenerator Generate cyclic redundancy code bits and append to
input data
comm.TurboDecoder Decode input signal using parallel concatenated
decoding scheme
comm.TurboEncoder Encode input signal using parallel concatenated
encoding scheme
Interleavers – Block
comm.AlgebraicDeinterleaver Deinterleave input symbols using algebraically
derived permutation vector
comm.AlgebraicInterleaver Permute input symbols using an algebraically
derived permutation vector
comm.BlockDeinterleaver Deinterleave input symbols using permutation
vector
comm.BlockInterleaver Permute input symbols using a permutation vector
comm.MatrixDeinterleaver Deinterleave input symbols using permutation
matrix
comm.MatrixInterleaver Permute input symbols using permutation matrix
comm.MatrixHelicalScanDeinterleaver Deinterleave input symbols by filling a matrix along
diagonals
3-8
Communications System Toolbox™ System Objects
Object Description
comm.MatrixHelicalScanInterleaver Permute input symbols by selecting matrix elements
along diagonals
Interleavers – Convolutional
comm.ConvolutionalDeinterleaver Restore ordering of symbols using shift registers
comm.ConvolutionalInterleaver Permute input symbols using shift registers
comm.HelicalDeinterleaver Restore ordering of symbols using a helical array
comm.HelicalInterleaver Permute input symbols using a helical array
comm.MultiplexedDeinterleaver Restore ordering of symbols using a set of shift
registers with specified delays
comm.MultiplexedInterleaver Permute input symbols using a set of shift registers
with specified delays
MIMO
comm.OSTBCCombiner Combine inputs using orthogonal space-time block
code
comm.OSTBCEncoder Encode input message using orthogonal space-time
block code
Digital Baseband Modulation – Phase
comm.BPSKDemodulator Demodulate using binary PSK method
comm.BPSKModulator Modulate using binary PSK method
comm.DBPSKModulator Modulate using differential binary PSK method
comm.DPSKDemodulator Demodulate using M-ary DPSK method
comm.DPSKModulator Modulate using M-ary DPSK method
comm.DQPSKDemodulator Demodulate using differential quadrature PSK
method
comm.DQPSKModulator Modulate using differential quadrature PSK method
comm.DBPSKDemodulator Demodulate using M-ary DPSK method
comm.QPSKDemodulator Demodulate using quadrature PSK method
3-9
3 System Objects Supported for Code Generation
Object Description
comm.QPSKModulator Modulate using quadrature PSK method
comm.PSKDemodulator Demodulate using M-ary PSK method
comm.PSKModulator Modulate using M-ary PSK method
comm.OQPSKDemodulator Demodulate offset quadrature PSK modulated data
comm.OQPSKModulator Modulate using offset quadrature PSK method
Digital Baseband Modulation – Amplitude
comm.GeneralQAMDemodulator Demodulate using arbitrary QAM constellation
comm.GeneralQAMModulator Modulate using arbitrary QAM constellation
comm.PAMDemodulator Demodulate using M-ary PAM method
comm.PAMModulator Modulate using M-ary PAM method
comm.RectangularQAMDemodulator Demodulate using rectangular QAM method
comm.RectangularQAMModulator Modulate using rectangular QAM method
Digital Baseband Modulation – Frequency
comm.FSKDemodulator Demodulate using M-ary FSK method
comm.FSKModulator Modulate using M-ary FSK method
Digital Baseband Modulation – Trelllis Coded
comm.GeneralQAMTCMDemodulator Demodulate convolutionally encoded data mapped
to arbitrary QAM constellation
comm.GeneralQAMTCMModulator Convolutionally encode binary data and map using
arbitrary QAM constellation
comm.PSKTCMDemodulator Demodulate convolutionally encoded data mapped
to M-ary PSK constellation
comm.PSKTCMModulator Convolutionally encode binary data and map using
M-ary PSK constellation
comm.RectangularQAMTCMDemodulator Demodulate convolutionally encoded data mapped
to rectangular QAM constellation
3-10
Communications System Toolbox™ System Objects
Object Description
comm.RectangularQAMTCMModulator Convolutionally encode binary data and map using
rectangular QAM constellation
Digital Baseband Modulation – Continuous Phase
comm.CPFSKDemodulator Demodulate using CPFSK method and Viterbi
algorithm
comm.CPFSKModulator Modulate using CPFSK method
comm.CPMDemodulator Demodulate using CPM method and Viterbi
algorithm
comm.CPMModulator Modulate using CPM method
comm.GMSKDemodulator Demodulate using GMSK method and the Viterbi
algorithm
comm.GMSKModulator Modulate using GMSK method
comm.MSKDemodulator Demodulate using MSK method and the Viterbi
algorithm
comm.MSKModulator Modulate using MSK method
RF Impairments
comm.PhaseFrequencyOffset Apply phase and frequency offsets to input signal
Synchronization – Timing Phase
comm.EarlyLateGateTimingSynchronizer Recover symbol timing phase using early-late gate
method
comm.GardnerTimingSynchronizer Recover symbol timing phase using Gardner’s
method
comm.GMSKTimingSynchronizer Recover symbol timing phase using fourth-order
nonlinearity method
comm.MSKTimingSynchronizer Recover symbol timing phase using fourth-order
nonlinearity method
comm.MuellerMullerTimingSynchronizer Recover symbol timing phase using Mueller-Muller
method
3-11
3 System Objects Supported for Code Generation
Object Description
Synchronization Utilities
comm.DiscreteTimeVCO Generate variable frequency sinusoid
Converters
comm.BitToInteger Convert vector of bits to vector of integers
comm.IntegerToBit Convert vector of integers to vector of bits
Sequence Operators
comm.Descrambler Descramble input signal
3-12
DSP System Toolbox™ System Objects
Object Description
Estimation
dsp.BurgAREstimator Compute estimate of autoregressive model parameters
using Burg method
dsp.BurgSpectrumEstimator Compute parametric spectral estimate using Burg
method
3-13
3 System Objects Supported for Code Generation
Object Description
dsp.LSFToLPC Convert line spectral frequencies to linear prediction
coefficients
dsp.LSPToLPC Convert line spectral pairs to linear prediction
coefficients
3-14
DSP System Toolbox™ System Objects
Object Description
dsp.LevinsonSolver Solve linear system of equations using
Levinson-Durbin recursion
dsp.LowerTriangularSolver Solve LX = B for X when L is lower triangular matrix
dsp.LUFactor Factor square matrix into lower and upper triangular
matrices
dsp.Normalizer Normalize input
dsp.UpperTriangularSolver Solve UX = B for X when U is upper triangular matrix
Quantizers
3-15
3 System Objects Supported for Code Generation
Object Description
dsp.VariableIntegerDelay Delay input by time-varying integer number of sample
periods
dsp.Window Generate or apply window function
dsp.ZeroCrossingDetector Calculate number of zero crossings of a signal
Signal Processing Sinks
dsp.AudioPlayer Write audio data to computer’s audio device
dsp.AudioFileWriter Write audio file
dsp.UDPSender Send UDP packets to the network
Signal Processing Sources
dsp.AudioFileReader Read audio samples from an audio file
3-16
DSP System Toolbox™ System Objects
Object Description
dsp.Variance Compute variance of input or sequence of inputs
Transforms
dsp.AnalyticSignal Compute analytic signals of discrete-time inputs
3-17
3 System Objects Supported for Code Generation
3-18
4
Defining MATLAB
Variables for C/C++ Code
Generation
For more information, see “Best Practices for Defining Variables for C/C++
Code Generation” on page 4-3.
4-2
Best Practices for Defining Variables for C/C++ Code Generation
Assignment: Defines:
a = 14.7; a as a real double scalar.
b = a; b with properties of a (real double
scalar).
c = zeros(5,2); c as a real 5-by-2 array of doubles.
d = [1 2 3 4 5; 6 7 8 9 0]; d as a real 5-by-2 array of doubles.
y = int16(3); y as a real 16-bit integer scalar.
Define properties this way so that the variable is defined on all execution
paths during C/C++ code generation (see Example: Defining a Variable for
Multiple Execution Paths on page 4-4).
The data that you assign to a variable can be a scalar, matrix, or structure. If
your variable is a structure, define the properties of each field explicitly (see
Example: Defining All Fields in a Structure on page 4-5).
4-3
4 Defining MATLAB® Variables for C/C++ Code Generation
Initializing the new variable to the value of the assigned data sometimes
results in redundant copies in the generated code. To avoid redundant
copies, you can define variables without initializing their values by using the
coder.nullcopy construct as described in “Eliminating Redundant Copies of
Variables in Generated Code” on page 4-8.
When you define variables, they are local by default; they do not persist
between function calls. To make variables persistent, see “Defining and
Initializing Persistent Variables” on page 4-10.
...
if c > 0
x = 11;
end
% Later in your code ...
if c > 0
use(x);
end
...
Here, x is assigned only if c > 0 and used only when c > 0. This code
works in MATLAB, but generates a compilation error during code generation
because it detects that x is undefined on some execution paths (when c <= 0),.
To make this code suitable for code generation, define x before using it:
x = 0;
...
if c > 0
x = 11;
end
% Later in your code ...
if c > 0
use(x);
end
...
4-4
Best Practices for Defining Variables for C/C++ Code Generation
...
if c > 0
s.a = 11;
disp(s);
else
s.a = 12;
s.b = 12;
end
% Try to use s
use(s);
...
Here, the first part of the if statement uses only the field a, and the else
clause uses fields a and b. This code works in MATLAB, but generates a
compilation error during C/C++ code generation because it detects a structure
type mismatch. To prevent this error, do not add fields to a structure after
you perform certain operations on the structure. For more information, see
Chapter 6, “Code Generation for MATLAB Structures”.
To make this code suitable for C/C++ code generation, define all fields of
s before using it.
...
% Define all fields in structure s
s = struct( a ,0, b , 0);
if c > 0
s.a = 11;
disp(s);
else
s.a = 12;
s.b = 12;
end
% Use s
use(s);
...
4-5
4 Defining MATLAB® Variables for C/C++ Code Generation
...
x = 15; % x is of type double by default.
y = uint8(x); % z has the value of x, but cast to uint8.
...
For example, the following initial assignment is not allowed for code
generation:
4-6
When You Can Reassign Variable Properties for C/C++ Code Generation
A variable can hold values that have the same class and complexity but
different sizes. If the size of the initial assignment is not constant, the
variable is dynamically sized in generated code. For more information, see
“How Working with Variable-Size Data Is Different for Code Generation”
on page 8-3.
You can reassign the type (class, size, and complexity) of a variable after
the initial assignment if each occurrence of the variable can have only one
type. In this case, the variable is renamed in the generated code to create
multiple independent variables. For more information, see “Reusing the Same
Variable with Different Properties” on page 4-11.
4-7
4 Defining MATLAB® Variables for C/C++ Code Generation
Note, however, that variable assignments not only copy the properties of the
assigned data to the new variable, but also initialize the new variable to the
assigned value. This forced initialization sometimes results in redundant
copies in C/C++ code. To eliminate redundant copies, define uninitialized
variables by using the coder.nullcopy function, as described in “How to
Eliminate Redundant Copies by Defining Uninitialized Variables” on page
4-8..
When the uninitialized variable is an array, you must initialize all of its
elements before passing the array as an input to a function or operator
— even if the function or operator does not read from the uninitialized
portion of the array.
4-8
Eliminating Redundant Copies of Variables in Generated Code
N = 5;
X = zeros(1,N);
for i = 1:N
if mod(i,2) == 0
X(i) = i;
else
X(i) = 0;
end
end
N = 5;
X = coder.nullcopy(zeros(1,N));
for i = 1:N
if mod(i,2) == 0
X(i) = i;
else
X(i) = 0;
end
end
4-9
4 Defining MATLAB® Variables for C/C++ Code Generation
persistent PROD_X;
The definition should appear at the top of the function body, after the
header and comments, but before the first use of the variable. During code
generation, the value of the persistent variable is initialized to an empty
matrix by default. You can assign your own value after the definition by using
the isempty statement, as in this example:
if isempty(PROD_X)
PROD_X = 1;
end
PROD_X = PROD_X * inputvalue;
end
4-10
Reusing the Same Variable with Different Properties
To compile this example and see how MATLAB renames the reused variable t,
see Variable Reuse in an if Statement on page 4-12.
4-11
4 Defining MATLAB® Variables for C/C++ Code Generation
4-12
Reusing the Same Variable with Different Properties
y = sum(u(t(2:end-1)));
end
2 Compile example1.
4 In the MATLAB code pane of the code generation report, place your pointer
over the variable t inside the if statement.
5 In the MATLAB code pane of the report, place your pointer over the
variable t outside the for-loop.
4-13
4 Defining MATLAB® Variables for C/C++ Code Generation
6 Click the Variables tab to view the list of variables used in example1.
The report displays a list of all the variables in example1. There are two
uniquely named local variables t>1 and t>2.
• Persistent variables.
• Global variables.
• Variables passed to C code using coder.ref, coder.rref, coder.wref.
• Variables whose size is set using coder.varsize.
• Variables whose names are controlled using coder.cstructname.
• The index variable of a for-loop when it is used inside the loop body.
4-14
Reusing the Same Variable with Different Properties
4-15
4 Defining MATLAB® Variables for C/C++ Code Generation
Type Description
char Character array (string)
complex Complex data. Cast function takes real and imaginary
components
double Double-precision floating point
int8, int16, int32 Signed integer
logical Boolean true or false
single Single-precision floating point
struct Structure (see Chapter 6, “Code Generation for
MATLAB Structures”)
uint8, uint16, Unsigned integer
uint32
Fixed-point See “Code Acceleration and Code Generation
from MATLAB for Fixed-Point Algorithms” in the
Fixed-Point Toolbox User’s Guide documentation.
4-16
5
• “How Working with Data is Different for Code Generation” on page 5-2
• “Code Generation for Complex Data” on page 5-4
• “Code Generation for Characters” on page 5-6
5 Defining Data for Code Generation
5-2
How Working with Data is Different for Code Generation
5-3
5 Defining Data for Code Generation
Once you set the type and size of a variable, you cannot cast it to another
type or size. In the following example, the variable x is defined as complex
and stays complex:
Mismatches can also occur when you assign a real operand the complex result
of an operation:
5-4
Code Generation for Complex Data
x = 2 + 3i;
y = 2 - 3i;
z = x + y; % z is 4 + 0i.
5-5
5 Defining Data for Code Generation
5-6
6
6-2
Structure Operations Allowed for Code Generation
6-3
6 Code Generation for MATLAB® Structures
...
S = struct('a', 0, 'b', 1, 'c', 2);
p = S;
...
6-4
Defining Scalar Structures for Code Generation
In this example, the assignment to x.a comes before x.b in the first if
statement clause, but the assignments appear in reverse order in the else
clause. Here is the corrected code:
...
x.c = 10; % Defines structure and creates field c
y = x; % Reads from structure
x.d = 20; % Generates an error
...
6-5
6 Code Generation for MATLAB® Structures
In this example, the attempt to add a new field d after reading from structure
x generates an error.
This restriction extends across the structure hierarchy. For example, you
cannot add a field to a structure after operating on one of its fields or nested
structures, as in this example:
x.c = 10;
y = x.c;
x.d = 20; % Generates an error
In this example, the attempt to add a new field d to structure x after reading
from the structure’s field c generates an error.
6-6
Defining Arrays of Structures for Code Generation
2 Call repmat, passing the scalar structure and the dimensions of the array.
For example, the following code creates X, a 1-by-3 array of scalar structures.
Each element of the array is defined by the structure s, which has two fields,
a and b:
...
s.a = 0;
s.b = 0;
X = repmat(s,1,3);
X(1).a = 1;
6-7
6 Code Generation for MATLAB® Structures
X(2).a = 2;
X(3).a = 3;
X(1).b = 4;
X(2).b = 5;
X(3).b = 6;
...
...
W = [ sab(1,2) sab(2,3) sab(4,5) ];
function s = sab(a,b)
s.a = a;
s.b = b;
...
6-8
Making Structures Persistent
if isempty(X)
X.a = 1;
X.b = 2;
end
6-9
6 Code Generation for MATLAB® Structures
For example, the following MATLAB code uses dot notation to index fields
and substructures:
...
substruct1.a1 = 15.2;
substruct1.a2 = int8([1 2;3 4]);
mystruct = struct('ele1',20.5,'ele2',single(100),
'ele3',substruct1);
substruct2 = mystruct;
substruct2.ele3.a2 = 2*(substruct1.a2);
...
To reference the value of a field in a structure array, you must index into the
array to the structure of interest and then reference that structure’s field
individually using dot notation, as in this example:
...
6-10
Indexing Substructures and Fields
To reference all the values of a particular field for each structure in an array,
use this notation in a for loop, as in this example:
...
s.a = 0;
s.b = 0;
X = repmat(s,1,5);
for i = 1:5
X(i).a = i;
X(i).b = i+1;
end
This example uses the repmat function to define an array of structures, each
with two fields a and b as defined by s. See “Defining Arrays of Structures for
Code Generation” on page 6-7 for more information.
6-11
6 Code Generation for MATLAB® Structures
If: Then:
Assigning one structure to another Define each structure with the same
structure. number, type, and size of fields.
Assigning one structure to a Define the structure with the same
substructure of a different structure number, type, and size of fields as
and vice versa. the substructure.
Assigning an element of one The elements must have the same
structure to an element of another type and size.
structure.
The values stored in the fields of a structure are not treated as constant values
in generated code. Therefore, you cannot use field values to set the size or
class of other data. For example, the following code generates a compiler error:
...
Y.a = 3;
X = zeros(Y.a); % Generates an error
In this example, even though you set field a of structure Y to the value 3, Y.a
is not a constant in generated code and, therefore, it is not a valid argument
to pass to the function zeros.
6-12
Passing Large Structures as Input Parameters
y = foo(a, S)
[y, S] = foo(a, S)
6-13
6 Code Generation for MATLAB® Structures
6-14
7
See Also
• “How to Define Enumerated Data for Code Generation” on page 7-9
• “Defining and Organizing Classes” in the MATLAB Object-Oriented
Programming documentation for more information about defining
MATLAB classes
• “Enumerations and Modeling” for more information about enumerated
types based on Simulink.IntEnumType
7-2
Enumerated Types Supported for Code Generation
Syntax
Example
7-3
7 Code Generation for Enumerated Data
How to Use
Define enumerated data in MATLAB code and compile the source file. For
example, to generate C/C++ code from your MATLAB source, you can use
codegen, as described in “Workflow for Generating Code for Enumerated
Data from MATLAB Algorithms” on page 7-7.
Syntax
Example
classdef(Enumeration) myMode < Simulink.IntEnumType
enumeration
OFF(0)
ON(1)
end
end
How to Use
Here are the basic guidelines for using enumerated data based on
Simulink.IntEnumType:
7-4
Enumerated Types Supported for Code Generation
Application What to Do
When exchanging Define enumerated data in MATLAB
enumerated data with Function blocks in Simulink models.
Simulink blocks Requires Simulink software.
When exchanging Define enumerated data in MATLAB
enumerated data with functions in Stateflow charts. Requires
Stateflow charts Simulink and Stateflow software.
7-5
7 Code Generation for Enumerated Data
7-6
Workflows for Using Enumerated Data for Code Generation
7-7
7 Code Generation for Enumerated Data
7-8
How to Define Enumerated Data for Code Generation
In the MATLAB Command Window, select File > New > Class.
For example, the following code defines an enumerated type called sysMode:
For example, the following code defines a set of two values for enumerated
type sysMode:
end
7-9
7 Code Generation for Enumerated Data
The name of the file must match the name of the enumerated data type.
The match is case sensitive.
For example, you cannot name an enumerated data type mode because
MATLAB for code generation provides a toolbox function of the same name.
For a list of toolbox functions supported for code generation, see Chapter 2,
“Functions Supported for Code Generation”.
7-10
How to Instantiate Enumerated Types for Code Generation
if state == sysMode.ON
led = LEDcolor.GREEN;
else
led = LEDcolor.RED;
end
7-11
7 Code Generation for Enumerated Data
If your function has inputs, you must specify the properties of these inputs
to codegen. For an enumerated data input, use the -args option to pass
one of its allowable values as a sample value. For example, the following
codegen command specifies that the function displayState takes one input
of enumerated data type sysMode.
displayState(sysMode.OFF)
ans =
RED
See Also
• MATLAB Coder documentation to learn more about codegen
• “Defining and Using Enumerated Types for Code Generation” on page 7-13
for a description of the example function displayState and its enumerated
type definitions
7-12
Defining and Using Enumerated Types for Code Generation
Before using enumerated data, you must define your enumerated data types
as MATLAB classes that inherit from the built-in type int32. Each class
definition must reside in a separate file on the MATLAB path. This example
uses two enumerated types: sysMode to represent the set of allowable modes
and LEDcolor to represent the set of allowable colors.
See Also
• “Workflows for Using Enumerated Data for Code Generation” on page 7-7
• “How to Define Enumerated Data for Code Generation” on page 7-9
• “How to Instantiate Enumerated Types for Code Generation” on page 7-11
• “How to Generate Code for Enumerated Data” on page 7-12
7-13
7 Code Generation for Enumerated Data
end
end
This definition must reside on the MATLAB path in a file with the same
name as the class, sysMode.m.
This definition must reside on the MATLAB path in a file called LEDcolor.m.
Function: displayState
The following function displayState uses enumerated data to activate an
LED display, based on the state of a device. It lights a green LED display to
indicate the ON state and lights a red LED display to indicate the OFF state.
if state == sysMode.ON
led = LEDcolor.GREEN;
else
led = LEDcolor.RED;
end
7-14
Operations on Enumerated Data Allowed for Code Generation
Assignment Operator, =
Example Result
RED
7-15
7 Code Generation for Enumerated Data
Cast Operation
Example Result
double(LEDcolor.RED) ans =
z = 2 z =
y = LEDcolor(z)
2
y =
RED
Indexing Operation
Example Result
m = [1 2] m =
n = LEDcolor(m)
p = n(LEDcolor.GREEN) 1 2
n =
GREEN RED
p =
GREEN
7-16
Operations on Enumerated Data Allowed for Code Generation
7-17
7 Code Generation for Enumerated Data
This definition must reside on the MATLAB path in a file with the same
name as the class, sysMode.m.
This definition must reside on the MATLAB path in a file called LEDcolor.m.
7-18
Using Enumerated Data in Control Flow Statements
if state == sysMode.ON
led = LEDcolor.GREEN;
else
led = LEDcolor.RED;
end
1 Generate a MEX function for displayState. Use the -args option to pass
one of the allowable values for the enumerated data input as a sample
value.
displayState(sysMode.OFF)
ans =
RED
7-19
7 Code Generation for Enumerated Data
Play(2),
Forward(3),
Rewind(4)
end
end
This definition must reside on the MATLAB path in a file with the same
name as the class, VCRState.m.
This definition must reside on the MATLAB path in a file with the same name
as the class, VCRButton.m.
function s = VCR(button)
%#codegen
persistent state
if isempty(state)
state = VCRState.Stop;
end
switch state
case {VCRState.Stop, VCRState.Forward, VCRState.Rewind}
state = handleDefault(button);
7-20
Using Enumerated Data in Control Flow Statements
case VCRState.Play
switch button
case VCRButton.PlayOrPause, state = VCRState.Pause;
otherwise, state = handleDefault(button);
end
case VCRState.Pause
switch button
case VCRButton.PlayOrPause, state = VCRState.Play;
otherwise, state = handleDefault(button);
end
end
s = state;
1 Generate a MEX function for VCR. Use the -args option to pass one of the
allowable values for the enumerated data input as a sample value.
s = VCR(VCRButton.Stop)
s =
Stop
7-21
7 Code Generation for Enumerated Data
This definition must reside on the MATLAB path in a file with the same
name as the class, State.m.
function s = Setup(initState)
%#codegen
state = initState;
if isempty(state)
state = State.Standby;
end
7-22
Using Enumerated Data in Control Flow Statements
s = state;
function initialize()
% Perform initialization.
function boot()
% Boot the device.
1 Generate a MEX executable for Setup. Use the -args option to pass one of
the allowable values for the enumerated data input as a sample value.
s = Setup(State.Standby)
s =
Ready
7-23
7 Code Generation for Enumerated Data
To iterate over a range of enumerated data with consecutive values, you can
cast the enumerated data to int32 in the loop counter.
Because the enumerated values are consecutive, you can use ColorCodes
data in a for-loop like this:
...
for i = int32(ColorCodes.Red):int32(ColorCodes.Purple)
c = ColorCodes(i);
...
end
7-24
Toolbox Functions That Support Enumerated Types for Code Generation
• cast
• cat
• circshift
• flipdim
• fliplr
• flipud
• histc
• ipermute
• isequal
• isequalwithequalnans
• isfinite
• isinf
• isnan
• issorted
• length
• permute
• repmat
• reshape
• rot90
• shiftdim
• sort
• sortrows
7-25
7 Code Generation for Enumerated Data
• squeeze
7-26
8
function B = nway(A,n)
% Compute average of every N elements of A and put them in B.
if ((mod(numel(A),n) == 0) && (n>=1 && n<=numel(A)))
B = ones(1,numel(A)/n);
k = 1;
for i = 1 : numel(A)/n
B(i) = mean(A(k + (0:n-1)));
k = k + n;
end
else
error('n <= 0 or does not divide number of elements evenly');
end
8-2
How Working with Variable-Size Data Is Different for Code Generation
By default, the compiler detects code logic that attempts to change these fixed
attributes after initial assignments, and flags these occurrences as errors
during code generation. However, you can override this behavior by defining
variables or structure fields as variable-size data. You can then generate
standalone code for bounded and unbounded variable-size data.
See Also
• “Bounded Versus Unbounded Variable-Size Data” on page 8-4
• “Related Products That Support Code Generation from MATLAB” on page
1-12
8-3
8 Code Generation for Variable-Size Data
By default during code generation, the compiler allocates memory on the stack
for variable-size data and performs a sophisticated analysis to determine or
calculate upper bounds. If you use unbounded data, you must enable dynamic
memory allocation so the compiler:
8-4
When to Use Dynamic Allocation for Variable-Size Data
See Also
• “Specifying Upper Bounds for Variable-Size Data” on page 8-27.
8-5
8 Code Generation for Variable-Size Data
To work through these steps with a simple example, see “Tutorial: Generating
MEX Code for a MATLAB Function That Expands a Vector in a Loop” on
page 8-9
This directive:
• Indicates that you intend to generate code for the MATLAB algorithm
• Turns on checking in the MATLAB Code Analyzer to detect potential
errors during code generation
In some cases, the MATLAB Code Analyzer warns you when your code
assigns data a fixed size but later grows the data, such as by assignment
or concatenation in a loop. If that data is supposed to vary in size at run
time, you can ignore these warnings.
For example:
8-6
How to Generate Code for MATLAB® Functions with Variable-Size Data
8-7
8 Code Generation for Variable-Size Data
8-8
Tutorial: Generating MEX Code for a MATLAB® Function That Expands a Vector in a Loop
8-9
8 Code Generation for Variable-Size Data
cd ([matlabroot, '/toolbox/stateflow/sfdemos'])
2 Open emldemo_uniquetol.m.
In this function, vector B should expand in size as it adds values from vector A.
Therefore, you can ignore this warning.
8-10
Tutorial: Generating MEX Code for a MATLAB® Function That Expands a Vector in a Loop
The -args option specifies the class, complexity, and size of each input to
function emldemo_uniquetol:
• The first argument, coder.typeof, defines a variable-size input. The
expression coder.typeof(0,[1 100],1) defines input A as a real double
vector with a fixed upper bound. Its first dimension is fixed at 1 and its
second dimension can vary in size up to 100 elements.
For more information, see “Specifying Variable-Size Inputs at the
Command Line” in the MATLAB Coder documentation.
• The second argument, 0, defines input tol as a real double scalar.
For more information, see the codegen reference page in the MATLAB
Coder documentation.
8-11
8 Code Generation for Variable-Size Data
The error indicates a size mismatch between the left-hand side and right-hand
side of the assignment statement B = [B A(i)];. The assignment B =
A(1) establishes the size of B as a fixed-size scalar (1 x 1). Therefore, the
concatenation of [B A(i)] creates a 1 x 2 vector.
coder.varsize('B');
8-12
Tutorial: Generating MEX Code for a MATLAB® Function That Expands a Vector in a Loop
coder.varsize('B');
B = A(1);
k = 1;
for i = 2:length(A)
if abs(A(k) - A(i)) > tol
B = [B A(i)];
k = i;
end
end
8-13
8 Code Generation for Variable-Size Data
This error occurs because codegen cannot determine an upper bound for B .
coder.varsize('B', [1 100]);
The argument [1 100] specifies that B is a vector with its first dimension
fixed at size 1 and the second dimension variable to an upper bound of
8-14
Tutorial: Generating MEX Code for a MATLAB® Function That Expands a Vector in a Loop
100. The value of 100 matches the upper bound of variable-size vector A.
Based on the algorithm, output B is at most as large as input A. By default,
dimensions of 1 are fixed size.
coder.varsize('B', [1 100]);
B = A(1);
k = 1;
for i = 2:length(A)
if abs(A(k) - A(i)) > tol
B = [B A(i)];
k = i;
end
end
This exercise presents one way to specify an upper bound. To learn about other
methods, see “Specifying Upper Bounds for Variable-Size Data” on page 8-27
8-15
8 Code Generation for Variable-Size Data
cfg = coder.config;
cfg.DynamicMemoryAllocation = 'AllVariableSizeArrays';
If you do not know the upper bounds of an input, it is good coding practice
to specify the input as unbounded instead of giving it an arbitrary upper
bound. In this codegen command, the size of the second dimension of
input A is Inf. When you specify the size of a dimension as Inf in a
coder.typeof statement, codegen treats the dimension as unbounded.
You can use Inf only with dynamic allocation.
See Also
• codegen in the MATLAB Coder documentation.
• “Primary Function Input Specification” in the MATLAB Coder
documentation.
8-16
Tutorial: Generating MEX Code for a MATLAB® Function That Expands a Vector in a Loop
cfg=coder.config('lib');
cfg.DynamicMemoryAllocation = 'AllVariableSizeArrays';
In the generated code, MATLAB represents data with unknown upper bounds
as a data type called emxArray. MATLAB provides utility functions for
creating and interacting with emxArrays in your generated code.
See Also
• “C Code Interface for Unbounded Arrays and Structure Fields” on page 8-30
• codegen in the MATLAB Coder documentation.
8-17
8 Code Generation for Variable-Size Data
8-18
Variable-Size Data in Code Generation Reports
8-19
8 Code Generation for Variable-Size Data
Method See
Assign the data from a variable-size “Using a Matrix Constructor with
matrix constructor such as Nonconstant Dimensions” on page
• ones 8-21
• zeros
• repmat
Assign multiple, constant sizes “Inferring Variable Size from
to the same variable before using Multiple Assignments” on page 8-21
(reading) the variable.
Define all instances of a variable to “Defining Variable-Size Data
be variable sized Explicitly Using coder.varsize” on
page 8-23
8-20
Defining Variable-Size Data for Code Generation
If you are not using dynamic memory allocation, you must also add an assert
statement to provide upper bounds for the dimensions. For example:
When you enable dynamic memory allocation on the heap, MATLAB does not
check for upper bounds; it assumes all variable-size data is unbounded.
8-21
8 Code Generation for Variable-Size Data
if (u > 0)
y = ones(3,4,5);
else
y = zeros(3,1);
end
When static allocation is used, this function infers that y is a matrix with
three dimensions, where:
The code generation report represents the size of matrix y like this:
In this case, the code generation report represents the size of matrix y like
this:
8-22
Defining Variable-Size Data for Code Generation
coder.varsize('B');
When you supply only the first argument, coder.varsize assumes all
dimensions of B can vary and that the upper bound is size(B).
The third argument specifies which dimensions vary. This argument must be
a logical vector or a double vector containing only zeros and ones. Dimensions
that correspond to zeros or false have fixed size; dimensions that correspond
to ones or true vary in size. coder.varsize usually treats dimensions of size
1 as fixed (see “Defining Variable-Size Matrices with Singleton Dimensions”
on page 8-24).
For more information about the syntax, see the coder.varsize reference
page.
8-23
8 Code Generation for Variable-Size Data
8-24
Defining Variable-Size Data for Code Generation
8-25
8 Code Generation for Variable-Size Data
for i = 1:numel(data)
data(i).color = rand-0.5;
data(i).values = 1:i;
end
y = 0;
for i = 1:numel(data)
if data(i).color > 0
y = y + sum(data(i).values);
end;
end
• coder.varsize('data.A(:).B')
In this example, data is a scalar variable that contains matrix A. Each
element of matrix A contains a variable-size field B.
• coder.varsize('data(:).A(:).B')
This expression defines field B inside each element of matrix A inside each
element of matrix data to be variable sized.
8-26
Specifying Upper Bounds for Variable-Size Data
This command specifies that the input to function foo is a matrix of real
doubles with two variable dimensions. The upper bound for the first
dimension is 3; the upper bound for the second dimension is 100. For a
detailed explanation of this syntax, see coder.typeof in the MATLAB Coder
documentation.
8-27
8 Code Generation for Variable-Size Data
In this example, the input to function foo is a vector of real doubles without
an upper bound.
You do not need to specify upper bounds when using dynamic allocation on
the heap. In this case, MATLAB assumes all variable-size data is unbounded
and does not attempt to determine upper bounds.
8-28
Specifying Upper Bounds for Variable-Size Data
The second argument of coder.varsize specifies the upper bound for each
instance of the variable specified in the first argument. In this example, the
argument [1 10] indicates that for every instance of Y:
8-29
8 Code Generation for Variable-Size Data
For example, here’s the definition for an emxArray of base type real_T with
unknown upper bounds:
8-30
C Code Interface for Unbounded Arrays and Structure Fields
To define two variables, in1 and in2, of this type, use this statement:
Field Description
*data Pointer to data of type <baseTypeName>
*size Pointer to first element of size vector. Length
of the vector equals the number of dimensions.
allocatedSize Number of elements currently allocated for the
array. If the size changes, MATLAB reallocates
memory based on the new size.
numDimensions Number of dimensions of the size vector, that
is, the number of dimensions you can access
without crossing into unallocated or unused
memory
canFreeData Boolean flag indicating how to deallocate
memory:
• true – MATLAB deallocates memory
automatically
• false – Calling program determines when
to deallocate memory
8-31
8 Code Generation for Variable-Size Data
8-32
Troubleshooting Issues with Variable-Size Data
8-33
8 Code Generation for Variable-Size Data
A(1) = mean(A(:));
if (n == 3)
A = B;
end
Y = A;
8-34
Troubleshooting Issues with Variable-Size Data
If u < 0
Y = [Y u];
end
When you compile this function, you get an error because y has fixed
dimensions (3 x 3), but x has variable dimensions. Fix this problem by using
explicit indexing to make x the same size as y:
8-35
8 Code Generation for Variable-Size Data
However, compiling this function generates an error because you did not
specify an upper bound for u. There are several ways to fix the problem:
8-36
Limitations with Variable-Size Support for Code Generation
For example, the following code applies the standard MATLAB scalar
expansion rules:
function y = scalar_exp_test()%#codegen
A = zeros(2,2);
coder.varsize('A');
B = 1;
y = A + B;
ans =
8-37
8 Code Generation for Variable-Size Data
1 1
1 1
function y = scalar_exp_test_err1()%#codegen
A = zeros(2,2);
coder.varsize('A','B');
B = 1;
y = A + B;
In this case, the coder.varsize statement obscures the fact that B is scalar.
The function compiles successfully, but generates a run-time error:
Workaround
To fix the problem, use indexing to force B to be a scalar value:
function y = scalar_exp_test_fix()%#codegen
A = zeros(2,2);
coder.varsize('A','B');
B = 1;
y = A + B(1);
8-38
Limitations with Variable-Size Support for Code Generation
Workarounds
If your application requires generated code to return the same size of
variable-size N-D arrays as MATLAB code, consider one of these workarounds:
B = size(A);
X = B(1:ndims(A));
In this situation, if MATLAB detects that both A and B are vectors at compile
time, it applies the special rule and gives the same result as MATLAB.
However, if either A or B is a variable-size matrix (has shape ?x?) at compile
time, MATLAB applies only the general indexing rule. Then, if both A and B
become vectors at run time, MATLAB reports a run-time error in simulation.
Workaround
Force your data to be a vector by using the colon operator for indexing:
A(B(:)). For example, suppose your code intentionally toggles between
vectors and regular matrices at run time. You can do an explicit check to
provide deterministic behavior:
...
8-39
8 Code Generation for Variable-Size Data
The indexing in the first branch specifies that C and B(:) are compile-time
vectors. As a result, MATLAB applies the standard vector-vector indexing
rule during code generation.
...
M = ones(10,10);
for i=1:10
for j = i:10
M(i,j) = 2 * M(i,j);
end
end
...
Note The matrix M must be defined before entering the loop, as shown in
the highlighted code.
8-40
Limitations with Variable-Size Support for Code Generation
In this case, since i — and therefore i+k — are not known, memory cannot
be allocated for the numerical result. However, memory can be allocated
for the following workaround:
M(i + (0:k))
for i = 1:10
M(i) = 5;
end
8-41
8 Code Generation for Variable-Size Data
Common Restrictions
The following common restrictions apply to multiple toolbox functions
supported for code generation. To determine which of these restrictions apply
to specific library functions, see the table in “Toolbox Functions with Variable
Sizing Restrictions” on page 8-43.
8-42
Restrictions on Variable Sizing in Toolbox Functions Supported for Code Generation
Array-to-vector restriction
The function issues an error when a variable-size array that is not a
variable-length vector assumes the shape of a vector at run time. To avoid
the issue, specify the input explicitly as a variable-length vector instead of
a variable-size array.
Array-to-scalar restriction
The function issues an error if a variable-size array assumes a scalar value at
run time. To avoid this issue, specify all scalars as fixed size.
8-43
8 Code Generation for Variable-Size Data
8-44
Restrictions on Variable Sizing in Toolbox Functions Supported for Code Generation
8-45
8 Code Generation for Variable-Size Data
8-46
Restrictions on Variable Sizing in Toolbox Functions Supported for Code Generation
8-47
8 Code Generation for Variable-Size Data
8-48
Restrictions on Variable Sizing in Toolbox Functions Supported for Code Generation
8-49
8 Code Generation for Variable-Size Data
8-50
9
To generate efficient standalone code for enumerated data, you are restricted
to using a subset of the operations you can perform with function handles
in MATLAB, as described in “Limitations with Function Handles for Code
Generation” on page 9-6
9-2
Example: Defining and Passing Function Handles for Code Generation
function addval(m)
%#codegen
disp(m);
function y = map(f,m)
y = m;
for i = 1:numel(y)
y(i) = f(y(i));
end
function y = addone(u)
9-3
9 Code Generation for Function Handles
y = u + 1;
function y = addtwo(u)
y = u + 2;
This code passes function handles @addone and @addtwo to the function map
which increments each element of the matrix m by the amount prescribed
by the referenced function. Note that map stores the function handle in the
input variable f and then uses f to invoke the function — in this case addone
first and then addtwo.
If you have MATLAB Coder, you can use the function codegen to convert the
function addval to a MEX executable that you can run in MATLAB. Follow
these steps:
codegen addval
m = zeros(3)
addval(m)
0 0 0
0 0 0
0 0 0
1 1 1
1 1 1
1 1 1
3 3 3
3 3 3
3 3 3
9-4
Example: Defining and Passing Function Handles for Code Generation
For more information, see “Generating MEX Functions from MATLAB Code
at the Command Line” in the MATLAB Coder documentation.
9-5
9 Code Generation for Function Handles
After you bind a variable to a specific function, you cannot use the same
variable to reference two different function handles, as in this example
%Incorrect code
...
x = @plus;
x = @minus;
...
You cannot pass function handles to or from feval and other extrinsic
MATLAB functions. For more information, see “Declaring MATLAB
Functions as Extrinsic Functions” on page 11-11
coder.extrinsic('plot');
plot(data, fhandle(data));
x = fhandle(data);
9-6
Limitations with Function Handles for Code Generation
In this example, the function plotFcn receives a function handle and its
data as primary inputs. plotFcn attempts to call the function referenced by
the fhandle with the input data and plot the results. However, this code
generates a compilation error, indicating that the function isa does not
recognize 'function_handle' as a class name when called inside a MATLAB
function to specify properties of primary inputs.
You cannot display or watch function handles from the debugger. They
appear as empty matrices.
9-7
9 Code Generation for Function Handles
9-8
10
Code generation relies on loop unrolling to produce simple and efficient code
for varargin and varargout. This technique permits most common uses of
varargin and varargout, but not all (see “Rules for Using Variable Length
Argument Lists for Code Generation” on page 10-10). This following sections
explain how to code effectively using these constructs.
10-2
Supported Index Expressions
%#codegen
function [x,y,z] = fcn(a,b,c)
[x,y,z] = subfcn(a,b,c);
You can use the following index expressions. The exp arguments must be
constant expressions or depend on a loop index variable.
Expression Description
varargin varargin{exp} Read the value of element
(read only) exp
varargin{exp1: exp2} Read the values of elements
exp1 through exp2
varargin{:} Read the values of all
elements
varargout varargout{exp} Read or write the value of
(read and write) element exp
Note The use of () is not supported for indexing into varargin and
varargout arrays.
10-3
10 Defining Functions for Code Generation
%#codegen
function [cmlen,cmwth,cmhgt] = conv_2_metric(inlen,inwth,inhgt)
[cmlen,cmwth,cmhgt] = inch_2_cm(inlen,inwth,inhgt);
In the following example, the function fcn cannot detect a logical relationship
between the index expression j and the index variable i:
%#codegen
function [x,y,z] = fcn(a,b,c)
[x,y,z] = subfcn(a,b,c);
10-4
Using varargin and varargout in for-Loops
end
As a result, the function does not unroll the loop and generates a compilation
error:
To correct the problem, you can force loop unrolling by wrapping the loop
header in the function coder.unroll, as follows:
%#codegen
function [x,y,z] = fcn(a,b,c)
[x,y,z] = subfcn(a,b,c);
%#codegen
function [cmlen,cmwth,cmhgt] = conv_2_metric(inlen,inwth,inhgt)
[cmlen,cmwth,cmhgt] = inch_2_cm(inlen,inwth,inhgt);
10-5
10 Defining Functions for Code Generation
For more information, see “Rules for Using Variable Length Argument Lists
for Code Generation” on page 10-10.
10-6
Implementing Wrapper Functions with varargin and varargout
%#codegen
function answer = fcn(method,a,b,c)
answer = optimize(method,a,b,c);
• You can use {:} to read all elements of varargin and pass them to another
function.
• You can mix variable and fixed numbers of arguments.
For more information, see “Rules for Using Variable Length Argument Lists
for Code Generation” on page 10-10.
10-7
10 Defining Functions for Code Generation
If Do This:
You assign varargin array elements Verify that for all pairs, the size,
to local variables in the for-loop type, and complexity are the same
for each property and the same for
each value
Properties or values have different Do not assign varargin array
sizes, types, or complexity elements to local variables in a
for-loop; reference the elements
directly
For example, in the following function test1, the sizes of the property strings
and numeric values are not the same in each pair:
%#codegen
function test1
v = create_value('size', 18, 'rgb', [240 9 44]);
end
function v = create_value(varargin)
v = new_value();
for i = 1 : 2 : length(varargin)
name = varargin{i};
value = varargin{i+1};
switch name
case 'size'
v = set_size(v, value);
case 'rgb'
v = set_color(v, value);
otherwise
end
end
end
10-8
Passing Property/Value Pairs with varargin
...
Generated code determines the size, type, and complexity of a local variable
based on its first assignment. In this example, the first assignments occur
in the first iteration of the for-loop:
However, in the second iteration, the size of the property string changes to
3 and the size of the numeric value changes to a vector, resulting in a type
mismatch error. To avoid such errors, reference varargin array values
directly, not through local variables, as highlighted in this code:
%#codegen
function test1
v = create_value('size', 18, 'rgb', [240 9 44]);
end
function v = create_value(varargin)
v = new_value();
for i = 1 : 2 : length(varargin)
switch varargin{i}
case 'size'
v = set_size(v, varargin{i+1});
case 'rgb'
v = set_color(v, varargin{i+1});
otherwise
end
end
end
...
10-9
10 Defining Functions for Code Generation
%#codegen
function varargout = inch_2_cm(varargin)
for i = 1:length(varargin)
varargout{i} = varargin{i} * 2.54;
end
To fix the problem, write a top-level function that specifies a fixed number
of inputs and outputs and then call inch_2_cm as an external function or
subfunction, as in this example:
%#codegen
function [cmL, cmW, cmH] = conv_2_metric(inL, inW, inH)
[cmL, cmW, cmH] = inch_2_cm(inL, inW, inH);
For code generation, you can use curly braces {}, but not parentheses (),
to index into varargin and varargout arrays. For more information, see
“Supported Index Expressions” on page 10-3.
10-10
Rules for Using Variable Length Argument Lists for Code Generation
If you use an expression to index into varargin or varargout, make sure that
the value of the expression can be computed at compile time. For examples,
see “Using varargin and varargout in for-Loops” on page 10-4.
10-11
10 Defining Functions for Code Generation
10-12
11
11-2
How MATLAB® Resolves Function Calls in Generated Code
Start
Dispatch to Function
Yes on Yes
MATLAB Extrinsic
for execution MATLAB function?
at runtime path?
No No
Yes
Subfunction?
No
No No
Generate
C code
Function
on Yes
MATLAB
path?
No
Generate error
11-3
11 Calling Functions for Code Generation
• Searches two paths, the code generation path and the MATLAB path
See “Compile Path Search Order” on page 11-4.
• Attempts to compile all functions unless you explicitly declare them to
be extrinsic
An extrinsic function is a function on the MATLAB path that the compiler
dispatches to MATLAB software for execution because the target language
does not support the function. MATLAB does not generate code for extrinsic
functions. You declare functions to be extrinsic by using the construct
coder.extrinsic, as described in “Declaring MATLAB Functions as
Extrinsic Functions” on page 11-11.
• Resolves file type based on precedence rules described in “How MATLAB
Resolves File Types on the Path for Code Generation” on page 11-6
MATLAB searches this path first during code generation. The code
generation path contains the toolbox functions supported for code
generation.
2 MATLAB path
If the function is not on the code generation path, MATLAB searches this
path.
MATLAB applies the same dispatcher rules when searching each path (see
“Determining Which Function Gets Called” in the MATLAB Programming
Fundamentals documentation).
11-4
How MATLAB® Resolves Function Calls in Generated Code
11-5
11 Calling Functions for Code Generation
11-6
How MATLAB® Resolves File Types on the Path for Code Generation
Start
No
Yes
MEX-file?
No
Yes
Generate MDL-file? Compile
error M-file
No
Yes
P-file?
No
No Yes
M-file?
11-7
11 Calling Functions for Code Generation
11-8
Calling Subfunctions
Calling Subfunctions
Subfunctions are functions defined in the body of MATLAB function. They
work the same way for code generation as they do when executing your
algorithm in the MATLAB environment.
The following example illustrates how to define and call a subfunction mean:
coder.extrinsic('plot');
len = length(vals);
mean = avg(vals, len);
stdev = sqrt(sum(((vals-avg(vals,len)).^2))/len;
plot(vals,'-+');
11-9
11 Calling Functions for Code Generation
11-10
Calling MATLAB® Functions
c = sqrt(a^2 + b^2);
create_plot(a, b, color);
coder.extrinsic('patch', 'axis');
11-11
11 Calling Functions for Code Generation
x = [0;a;a];
y = [0;0;b];
patch(x, y, color);
axis('equal');
11-12
Calling MATLAB® Functions
11-13
11 Calling Functions for Code Generation
In this example, rat and min as treated as extrinsic every time they are
called in the main function foo. There are two ways to narrow the scope of
an extrinsic declaration inside the main function:
11-14
Calling MATLAB® Functions
function y = mymin(a,b)
coder.extrinsic('min');
y = min(a,b);
Here, the function rat is extrinsic every time it is called inside the main
function foo, but the function min is extrinsic only when called inside the
subfunction mymin.
• Call the MATLAB function using feval, as described in “Calling MATLAB
Functions Using feval” on page 11-15.
function y = foo
coder.extrinsic('rat');
[N D] = rat(pi);
y = 0;
y = feval('min', N, D);
11-15
11 Calling Functions for Code Generation
11-16
Calling MATLAB® Functions
Here, the top-level function foo calls the extrinsic MATLAB function rat,
which returns two mxArrays representing the numerator N and denominator
D of the rational fraction approximation of pi. Although you can pass these
mxArrays to another MATLAB function — in this case, min — you cannot
assign the mxArray returned by min to the output y.
To correct this problem, define y to be the type and size of the value that you
expect min to return — in this case, a scalar double — as follows:
11-17
11 Calling Functions for Code Generation
• MATLAB functions that inspect the caller or write to the caller’s workspace
do not work during code generation. Such functions include:
- dbstack
- evalin
- assignin
• The MATLAB debugger cannot inspect variables defined in extrinsic
functions.
• Functions in generated code may produce unpredictable results if your
extrinsic function performs any of the following actions at run time:
- Change folders
- Change the MATLAB path
- Delete or add MATLAB files
- Change warning states
- Change MATLAB preferences
- Change Simulink parameters
11-18
12
Unrolling for-Loops
Unrolling for-loops eliminates the loop logic by creating a separate copy of the
loop body in the generated code for each iteration. Within each iteration, the
loop index variable becomes a constant. By unrolling short loops with known
bounds at compile time, MATLAB generates highly optimized code with no
branches.
You can also force loop unrolling for individual functions by wrapping
the loop header in an coder.unroll function. For more information, see
coder.unroll in the Code Generation from MATLAB Function Reference.
Inlining Functions
MATLAB uses internal heuristics to determine whether or not to inline
functions in the generated code. You can use the coder.inline directive to
fine-tune these heuristics for individual functions. See coder.inline in the
Code Generation from MATLAB Function Reference.
12-2
Generating Efficient Code
...
/* Function Definitions */
void foo(real_T *A, real_T B)
{
*A *= B;
}
...
By contrast, suppose you rewrite function foo without using this optimization:
In this case, MATLAB generates code that passes the inputs by value and
returns the value of the output:
...
/* Function Definitions */
real_T foo2(real_T A, real_T B)
{
return A * B;
}
...
12-3
12 Generating Efficient and Reusable Code
See “How MATLAB Resolves Function Calls in Generated Code” on page 11-2.
12-4
A
Examples
Data Management
Example: Defining a Variable for Multiple Execution Paths on page 4-4
Example: Defining All Fields in a Structure on page 4-5
“Defining Uninitialized Variables” on page 4-9
Variable Reuse in an if Statement on page 4-12
A-2
Code Generation for Function Handles
A-3
A Examples
A-4
Index
A
Index resolving extrinsic function calls in generated
arguments code 11-16
limit on number for code generation from rules for defining uninitialized variables 4-8
MATLAB 11-18 setting properties of indexed variables 4-6
supported toolbox functions 11-10
unrolling for-loops 12-2
C using type cast operators in variable
C/C++ code generation for supported definitions 4-6
functions 2-1 variables, complex 5-4
code generation from MATLAB working with mxArrays 11-16
best practices for working with variables 4-3 coder.extrinsic 11-11
calling MATLAB functions 11-11 coder.nullcopy
calling MATLAB functions using feval 11-15 uninitialized variables 4-8
calling subfunctions 11-9 communications system toolbox System objects
characters 5-6 supported for code generation from
communications system toolbox System MATLAB 3-7
objects 3-7 computer vision system toolbox System objects
compilation directive %#codegen 11-8 supported for code generation from
computer vision system toolbox System MATLAB 3-3
objects 3-3
converting mxArrays to known types 11-17
D
declaring MATLAB functions as extrinsic
functions 11-11 defining uninitialized variables
defining persistent variables 4-10 rules 4-8
defining variables 4-2 defining variables
defining variables by assignment 4-3 for C/C++ code generation 4-3
dsp system toolbox System objects 3-13 dsp system toolbox System objects
eliminating redundant copies of function supported for code generation from
inputs 12-2 MATLAB 3-13
eliminating redundant copies of uninitialized
variables 4-8 E
function handles 9-1
eliminating redundant copies of function
generating efficient code 12-2
inputs 12-2
how it resolves function calls 11-2
extrinsic functions 11-11
initializing persistent variables 4-10
inlining functions 12-2
limit on number of function arguments 11-18 F
pragma 11-8 function handles
resolving extrinsic function calls during for code generation from MATLAB 9-1
simulation 11-15 functions
Index-1
Index
Index-2
Index
T variables
type cast operators eliminating redundant copies in C/C++ code
using in variable definitions 4-6 generated from MATLAB 4-8
Variables
defining by assignment for code generation
U from MATLAB 4-3
uninitialized variables defining for code generation from
eliminating redundant copies in generated MATLAB 4-2
code 4-8
V
variable types supported for code generation
from MATLAB 4-16
Index-3