0% found this document useful (0 votes)
650 views2,114 pages

MATLAB Coder Documentation (PDFDrive)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
650 views2,114 pages

MATLAB Coder Documentation (PDFDrive)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2114

MATLAB® Coder™

Getting Started Guide

R2016a
How to Contact MathWorks

Latest news: www.mathworks.com

Sales and services: www.mathworks.com/sales_and_services

User community: www.mathworks.com/matlabcentral

Technical support: www.mathworks.com/support/contact_us

Phone: 508-647-7000

The MathWorks, Inc.


3 Apple Hill Drive
Natick, MA 01760-2098

MATLAB® Coder™ Getting Started Guide


© COPYRIGHT 2011–2016 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and
govern the use, modification, reproduction, release, performance, display, and disclosure of the Program
and Documentation by the federal government (or other entity acquiring for or through the federal
government) and shall supersede any conflicting contractual terms or conditions. If this License fails
to meet the government's needs or is inconsistent in any respect with federal procurement law, the
government agrees to return the Program and Documentation, unused, to The MathWorks, Inc.
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
April 2011 Online only New for R2011a
September 2011 Online only Revised for Version 2.1 (Release 2011b)
March 2012 Online only Revised for Version 2.2 (Release 2012a)
September 2012 Online only Revised for Version 2.3 (Release 2012b)
March 2013 Online only Revised for Version 2.4 (Release 2013a)
September 2013 Online only Revised for Version 2.5 (Release 2013b)
March 2014 Online only Revised for Version 2.6 (Release 2014a)
October 2014 Online only Revised for Version 2.7 (Release 2014b)
March 2015 Online only Revised for Version 2.8 (Release 2015a)
September 2015 Online only Revised for Version 3.0 (Release 2015b)
October 2015 Online only Rereleased for Version 2.8.1 (Release
2015aSP1)
March 2016 Online only Revised for Version 3.1 (Release 2016a)
Check Bug Reports for Issues and Fixes
Software is inherently complex and is not free of errors. The output of a code generator
might contain bugs, some of which are not detected by a compiler. MathWorks
reports critical known bugs brought to its attention on its Bug Report system at
www.mathworks.com/support/bugreports/. Use the Saved Searches and Watched Bugs
tool with the search phrase "Incorrect Code Generation" to obtain a report of known bugs
that produce code that might compile and execute, but still produce wrong answers.

The bug reports are an integral part of the documentation for each release. Examine
periodically all bug reports for a release, as such reports may identify inconsistencies
between the actual behavior of a release you are using and the behavior described in this
documentation.

In addition to reviewing bug reports, you should implement a verification and validation
strategy to identify potential bugs in your design, code, and tools.
Contents

Product Overview
1
MATLAB Coder Product Description . . . . . . . . . . . . . . . . . . . 1-2
Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2

About MATLAB Coder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3


When to Use MATLAB Coder . . . . . . . . . . . . . . . . . . . . . . . . 1-3
What You Can Do with the Project Interface . . . . . . . . . . . . . 1-3
When to Use the Command Line (codegen function) . . . . . . . 1-3

Code Generation for Embedded Software Applications . . . . 1-5

Code Generation for Fixed-Point Algorithms . . . . . . . . . . . . 1-6

Installing Prerequisite Products . . . . . . . . . . . . . . . . . . . . . . . 1-7

Related Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8

Setting Up the C or C++ Compiler . . . . . . . . . . . . . . . . . . . . . 1-9

Expected Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10

MATLAB Code for Code Generation Workflow Overview . . 1-11


See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11

Tutorials
2
C Code Generation Using the MATLAB Coder App . . . . . . . . 2-2
Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Tutorial Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2

vii
Example: The Kalman Filter . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Files for the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
Design Considerations When Writing MATLAB Code for Code
Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Tutorial Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Key Points to Remember . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-29
Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-29

C Code Generation at the Command Line . . . . . . . . . . . . . . 2-31


Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-31
Tutorial Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-31
Example: The Kalman Filter . . . . . . . . . . . . . . . . . . . . . . . . 2-32
Files for the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-34
Design Considerations When Writing MATLAB Code for Code
Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-36
Tutorial Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-37
Key Points to Remember . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-55
Best Practices Used in This Tutorial . . . . . . . . . . . . . . . . . . 2-55
Where to Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-56

MEX Function Generation at the Command Line . . . . . . . . 2-58


Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-58
Tutorial Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-58
Example: Euclidean Minimum Distance . . . . . . . . . . . . . . . 2-59
Files for the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-61
Tutorial Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-62
Key Points to Remember . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-78
Best Practices Used in This Tutorial . . . . . . . . . . . . . . . . . . 2-78
Where to Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-79

Best Practices for Working with MATLAB Coder


3
Recommended Compilation Options for codegen . . . . . . . . . 3-2
-c Generate Code Only . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
-report Generate Code Generation Report . . . . . . . . . . . . . . . 3-2

Testing MEX Functions in MATLAB . . . . . . . . . . . . . . . . . . . . 3-3

viii Contents
Comparing C Code and MATLAB Code Using Tiling in the
MATLAB Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4

Using Build Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5

Check Code Using the MATLAB Code Analyzer . . . . . . . . . . 3-6

Separating Your Test Bench from Your Function Code . . . . 3-7

Preserving Your Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8

File Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-9

ix
1

Product Overview

• “MATLAB Coder Product Description” on page 1-2


• “About MATLAB Coder” on page 1-3
• “Code Generation for Embedded Software Applications” on page 1-5
• “Code Generation for Fixed-Point Algorithms” on page 1-6
• “Installing Prerequisite Products” on page 1-7
• “Related Products” on page 1-8
• “Setting Up the C or C++ Compiler” on page 1-9
• “Expected Background” on page 1-10
• “MATLAB Code for Code Generation Workflow Overview” on page 1-11
1 Product Overview

MATLAB Coder Product Description


Generate C and C++ code from MATLAB code

MATLAB® Coder™ generates readable and portable C and C++ code from MATLAB
code. It supports most of the MATLAB language and a wide range of toolboxes. You
can integrate the generated code into your projects as source code, static libraries, or
dynamic libraries. You can also use the generated code within the MATLAB environment
to accelerate computationally intensive portions of your MATLAB code. MATLAB Coder
lets you incorporate legacy C code into your MATLAB algorithm and into the generated
code.

By using MATLAB Coder with Embedded Coder®, you can further optimize code
efficiency and customize the generated code. You can then verify the numerical behavior
of the generated code using software-in-the-loop (SIL) and processor-in-the-loop (PIL)
execution.

Key Features
• ANSI®/ISO® compliant C and C++ code generation
• Code generation support for toolboxes including Communications System Toolbox™,
Computer Vision System Toolbox™, DSP System Toolbox™, Image Processing
Toolbox™, and Signal Processing Toolbox™
• MEX function generation for code verification and acceleration
• Legacy C code integration into MATLAB algorithms and generated code
• Multicore-capable code generation using OpenMP
• Static or dynamic memory-allocation control
• App and equivalent command-line functions for managing code generation projects

1-2
About MATLAB Coder

About MATLAB Coder


When to Use MATLAB Coder
Use MATLAB Coder to:

• Generate readable, efficient, standalone C/C++ code from MATLAB code.


• Generate MEX functions from MATLAB code to:

• Accelerate your MATLAB algorithms.


• Verify generated C code within MATLAB.
• Integrate custom C/C++ code into MATLAB.

What You Can Do with the Project Interface


• Specify the MATLAB files from which you want to generate code
• Specify the data types for the inputs to these MATLAB files
• Select an output type:

• MEX function
• C/C++ Static Library
• C/C++ Dynamic Library
• C/C++ Executable
• Configure build settings to customize your environment for code generation
• Open the code generation report to view build status, generated code, and compile-
time information for the variables and expressions in your MATLAB code

See Also

• “Set Up a MATLAB Coder Project”


• “C Code Generation Using the MATLAB Coder App” on page 2-2

When to Use the Command Line (codegen function)


Use the command line if you use build scripts to specify input parameter types and code
generation options.

1-3
1 Product Overview

See Also

• The codegen function reference page


• “C Code Generation at the Command Line” on page 2-31
• “MEX Function Generation at the Command Line” on page 2-58

1-4
Code Generation for Embedded Software Applications

Code Generation for Embedded Software Applications


The Embedded Coder product extends the MATLAB Coder product with features that
are important for embedded software development. Using the Embedded Coder add-
on product, you can generate code that has the clarity and efficiency of professional
handwritten code. For example, you can:

• Generate code that is compact and fast, which is essential for real-time simulators,
on-target rapid prototyping boards, microprocessors used in mass production, and
embedded systems.
• Customize the appearance of the generated code.
• Optimize the generated code for a specific target environment.
• Enable tracing options that help you to verify the generated code.
• Generate reusable, reentrant code.

1-5
1 Product Overview

Code Generation for Fixed-Point Algorithms


Using the Fixed-Point Designer™ product, you can generate:

• MEX functions to accelerate fixed-point algorithms.


• Fixed-point code that provides a bit-wise match to MEX function results.

1-6
Installing Prerequisite Products

Installing Prerequisite Products


To generate C and C++ code using MATLAB Coder, you must install the following
products:

• MATLAB

Note: If MATLAB is installed on a path that contains non 7-bit ASCII characters,
such as Japanese characters, MATLAB Coder might not work because it cannot locate
code generation library functions.
• MATLAB Coder
• C or C++ compiler

For most platforms, a default compiler is supplied with MATLAB.

MATLAB Coder automatically locates and uses a supported installed compiler. For
the current list of supported compilers, see Supported and Compatible Compilers on
the MathWorks® Web site.

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

For instructions on installing MathWorks products, see the MATLAB installation


documentation for your platform. If you have installed MATLAB and want to check
which other MathWorks products are installed, enter ver in the MATLAB Command
Window.

1-7
1 Product Overview

Related Products
• Embedded Coder
• Simulink® Coder

1-8
Setting Up the C or C++ Compiler

Setting Up the C or C++ Compiler


MATLAB Coder automatically locates and uses a supported installed compiler. For the
current list of supported compilers, see Supported and Compatible Compilers on the
MathWorks Web site.

You can use mex -setup to change the default compiler. See “Change Default
Compiler”. If you generate C++ code, see “Choose a C++ Compiler”.

1-9
1 Product Overview

Expected Background
You should be familiar with :

• MATLAB software
• MEX functions

For more information, see “Introducing MEX Files” in the MATLAB External
Interfaces documentation.
• C/C++ programming concepts

To generate C code on embedded targets, you should also be familiar with how to re-
compile the generated code in the target environment.

To integrate the generated code into external applications, you should be familiar with
the C/C++ compilation and linking process.

1-10
MATLAB Code for Code Generation Workflow Overview

MATLAB Code for Code Generation Workflow Overview

See Also
• “Set Up a MATLAB Coder Project”
• “Workflow for Preparing MATLAB Code for Code Generation”
• “Workflow for Testing MEX Functions in MATLAB”
• “Code Generation Workflow”
• “Workflow for Accelerating MATLAB Algorithms”
• “Optimization Strategies”
• “Accelerate MATLAB Algorithms”

1-11
2

Tutorials

• “C Code Generation Using the MATLAB Coder App” on page 2-2


• “C Code Generation at the Command Line” on page 2-31
• “MEX Function Generation at the Command Line” on page 2-58
2 Tutorials

C Code Generation Using the MATLAB Coder App


In this section...
“Learning Objectives” on page 2-2
“Tutorial Prerequisites” on page 2-2
“Example: The Kalman Filter” on page 2-3
“Files for the Tutorial” on page 2-5
“Design Considerations When Writing MATLAB Code for Code Generation” on page
2-7
“Tutorial Steps” on page 2-8
“Key Points to Remember” on page 2-29
“Learn More” on page 2-29

Learning Objectives
In this tutorial, you learn how to:

• Create and set up a MATLAB Coder project.


• Define function input properties.
• Check for code generation readiness and run-time issues.
• Generate C code from your MATLAB code.
• Specify variable-size inputs when generating code.
• Specify code generation properties.
• Generate a code generation report that you can use to debug your MATLAB code and
verify that it is suitable for code generation.

Tutorial Prerequisites
Required Products

This tutorial requires the following products:

• MATLAB
• MATLAB Coder

2-2
C Code Generation Using the MATLAB Coder App

• C compiler

For most platforms, a default compiler is supplied with MATLAB.

MATLAB Coder locates and uses a supported installed compiler. See Supported and
Compatible Compilers on the MathWorks website.

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

For instructions on installing MathWorks products, see the MATLAB installation


documentation for your platform. If you have installed MATLAB and want to check
which other MathWorks products are installed, at the MATLAB prompt, enter ver.

Example: The Kalman Filter


• “Description” on page 2-3
• “Algorithm” on page 2-3
• “Filtering Process” on page 2-4
• “Reference” on page 2-5

Description

You do not have to be familiar with the algorithm in the example to complete the
tutorial.

The Kalman filter estimates the position of an object moving in a two-dimensional


space from a series of noisy inputs based on past positions. The position vector has two
components, x and y, indicating its horizontal and vertical coordinates.

Kalman filters have a wide range of applications, including control, signal processing,
and image processing; radar and sonar; and financial modeling. They are recursive filters
that estimate the state of a linear dynamic system from a series of incomplete or noisy
measurements. The Kalman filter algorithm relies on the state-space representation of
filters. It uses a set of variables stored in the state vector to characterize completely the
behavior of the system. It updates the state vector linearly and recursively using a state
transition matrix and a process noise estimate.

Algorithm

This section describes the Kalman filter algorithm that this example uses.

2-3
2 Tutorials

The algorithm predicts the position of a moving object based on its past positions using a
Kalman filter estimator. It estimates the present position by updating the Kalman state
vector. The Kalman state vector includes the position (x and y), velocity (Vx and Vy),
and acceleration (Ax and Ay) of the moving object. The Kalman state vector, x_est, is a
persistent variable.
% Initial conditions
persistent x_est p_est
if isempty(x_est)
x_est = zeros(6, 1);
p_est = zeros(6, 6);
end
The algorithm initializes x_est to an empty 6x1 column vector. It updates x_est each
time the filter is used.

The Kalman filter uses the laws of motion to estimate the new state:

X = X 0 + Vx.dt
Y = Y0 + Vy.dt
Vx = Vx0 + Ax.dt
Vy = Vy0 + Ay.dt

The state transition matrix A, contains the coefficient values of x, y, Vx, Vy, Ax, and Ay. A
captures these laws of motion.
% Initialize state transition matrix
dt=1;
A=[ 1 0 dt 0 0 0;...
0 1 0 dt 0 0;...
0 0 1 0 dt 0;...
0 0 0 1 0 dt;...
0 0 0 0 1 0 ;...
0 0 0 0 0 1 ];

Filtering Process

The filtering process has two phases:

• Predicted state and covariance

The Kalman filter uses the previously estimated state, x_est, to predict the current
state, x_prd. The predicted state and covariance are calculated in:

2-4
C Code Generation Using the MATLAB Coder App

% Predicted state and covariance


x_prd = A * x_est;
p_prd = A * p_est * A' + Q;
• Estimation

The filter also uses the current measurement, z, and the predicted state, x_prd,
to estimate a closer approximation of the current state. The estimated state and
covariance are calculated in:
% Measurement matrix
H = [ 1 0 0 0 0 0; 0 1 0 0 0 0 ];
Q = eye(6);
R = 1000 * eye(2);

% Estimation
S = H * p_prd' * H' + R;
B = H * p_prd';
klm_gain = (S \ B)';

% Estimated state and covariance


x_est = x_prd + klm_gain * (z - H * x_prd);
p_est = p_prd - klm_gain * H * p_prd;

% Compute the estimated measurements


y = H * x_est;

Reference

Haykin, Simon. Adaptive Filter Theory. Upper Saddle River, NJ: Prentice-Hall, Inc.,
1996.

Files for the Tutorial


• “About the Tutorial Files” on page 2-5
• “Location of Files” on page 2-6
• “Names and Descriptions of Files” on page 2-6

About the Tutorial Files

The tutorial uses the following files:

• Example MATLAB code files for each step of the tutorial.

2-5
2 Tutorials

Throughout this tutorial, you work with MATLAB files that contain a simple Kalman
filter algorithm.
• Test files that:

• Perform the preprocessing functions.


• Call the Kalman filter.
• Perform the post-processing functions.
• A MAT-file that contains input data.

Location of Files

The tutorial files are available in the following folder: docroot\toolbox\coder


\examples\kalman. Copy these files to a local folder. For instructions, see “Copying
Files Locally” on page 2-38.

Names and Descriptions of Files

Type Name Description


Function kalman01.m Baseline MATLAB implementation of a
code scalar Kalman filter. In the example, you
modify this file to make it suitable for code
generation and for use with frame-based and
packet-based inputs.
kalman02.m The kalman01 function after modification to
make it suitable for code generation.
kalman03.m The kalman01 function after modification to
make it suitable for frame-based and packet-
based inputs.
Test test01_ui.m Tests the scalar Kalman filter and plots the
scripts trajectory.
test02_ui.m Tests the frame-based Kalman filter.
test03_ui.m Tests the variable-size (packet-based)
Kalman filter.
MAT-file position.mat Contains the input data used by the
algorithm.

2-6
C Code Generation Using the MATLAB Coder App

Type Name Description


Plot plot_trajectory.m Plots the trajectory of the object and the
function Kalman filter estimated position.

Design Considerations When Writing MATLAB Code for Code Generation


When writing MATLAB code that you want to convert into efficient, standalone C/C++
code, consider the following:

• Data types

C and C++ use static typing. Before you use your variables, to determine the types of
your variables, MATLAB Coder requires a complete assignment to each variable.
• Array sizing

Variable-size arrays and matrices are supported for code generation. You can define
inputs, outputs, and local variables in MATLAB functions to represent data that
varies in size at run time.
• Memory

You can choose whether the generated code uses static or dynamic memory allocation.

With dynamic memory allocation, you potentially use less memory at the expense of
time to manage the memory. With static memory, you get the best speed, but with
higher memory usage. Most MATLAB code takes advantage of the dynamic-sizing
features in MATLAB. Therefore, dynamic memory allocation typically enables you
to generate code from existing MATLAB code without much modification. Dynamic
memory allocation also allows some programs to compile even when the software
cannot find upper bounds.
• Speed

Because embedded applications run in real time, the code must be fast enough to
meet the required clock rate.

To improve the speed of the generated code:

• Choose a suitable C/C++ compiler. The default compiler that MathWorks supplies
with MATLAB for Windows® platforms is not a good compiler for performance.
• Consider disabling run-time checks.

2-7
2 Tutorials

By default, for safety, the code generated for your MATLAB code contains memory
integrity checks and responsiveness checks. These checks can result in more
generated code and slower simulation. Disabling run-time checks can result in
streamlined generated code and faster simulation. Disable these checks only if you
have verified that array bounds and dimension checking is unnecessary.

See Also

• “Data Definition Basics”


• “Variable-Size Data”
• “Bounded Versus Unbounded Variable-Size Data”
• “Control Dynamic Memory Allocation”
• “Control Run-Time Checks”

Tutorial Steps
• “Copy Files to Local Working Folder” on page 2-8
• “Run the Original MATLAB Code” on page 2-9
• “Set Up Your C Compiler” on page 2-10
• “Prepare MATLAB Code for Code Generation” on page 2-11
• “Make the MATLAB Code Suitable for Code Generation” on page 2-12
• “Opening the MATLAB Coder App” on page 2-14
• “Select Source Files” on page 2-14
• “Define Input Types” on page 2-15
• “Check for Run-Time Issues” on page 2-16
• “Generate C Code” on page 2-19
• “Reviewing the Finish Workflow Page” on page 2-20
• “Comparing the Generated C Code to Original MATLAB Code” on page 2-21
• “Modifying the Filter to Accept a Fixed-Size Input” on page 2-22
• “Use the Filter to Accept a Variable-Size Input” on page 2-26

Copy Files to Local Working Folder

Copy the tutorial files to a local working folder:

1 Create a local solutions folder, for example, c:\coder\kalman\solutions.

2-8
C Code Generation Using the MATLAB Coder App

2 Change to the docroot\toolbox\coder\examples folder. At the MATLAB


command prompt, enter:
cd(fullfile(docroot, 'toolbox', 'coder', 'examples'))
3 Copy the contents of the kalman subfolder to your local solutions folder, specifying
the full path name of the solutions folder:
copyfile('kalman', 'solutions')
Your solutions folder now contains a complete set of solutions for the tutorial. If
you do not want to perform the steps for each task in the tutorial, you can view the
solutions to see the modified code.
4 Create a local work folder, for example, c:\coder\kalman\work.
5 Copy the following files from your solutions folder to your work folder.

• kalman01.m
• position.mat
• Test script test01_ui.m
• plot_trajectory.m

Your work folder now contains the files to get started with the tutorial.

Run the Original MATLAB Code


In this tutorial, you work with a MATLAB function that implements a Kalman filter
algorithm. The algorithm predicts the position of a moving object based on its past
positions. Before generating C code for this algorithm, you make the MATLAB version
suitable for code generation and generate a MEX function. You then test the resulting
MEX function to validate the functionality of the modified code. As you work through the
tutorial, you refine the design of the algorithm to accept variable-size inputs.

First, use the script test01_ui.m to run the original MATLAB function to see how the
Kalman filter algorithm works. This script loads the input data and calls the Kalman
filter algorithm to estimate the location. It then calls a plot function, plot_trajectory,
which plots the trajectory of the object and the Kalman filter estimated position.

1 Set your MATLAB current folder to the work folder that contains your files for this
tutorial. At the MATLAB command prompt, enter:
cd work
where work is the full path name of the work folder containing your files. For more
information, see “Files and Folders that MATLAB Accesses”.

2-9
2 Tutorials

2 At the MATLAB command prompt, enter:

test01_ui

The test script runs and plots the trajectory of the object in blue and the Kalman
filter estimated position in green. Initially, you see that it takes a short time for
the estimated position to converge with the actual position of the object. Then three
sudden shifts in position occur—each time the Kalman filter readjusts and tracks the
object after a few iterations.

Set Up Your C Compiler

MATLAB Coder locates and uses a supported installed compiler. See Supported and
Compatible Compilers on the MathWorks website.

2-10
C Code Generation Using the MATLAB Coder App

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

Prepare MATLAB Code for Code Generation

Before generating code, prepare your MATLAB code for code generation:

• To check for coding issues, use the Code Analyzer in the MATLAB Editor.
• To screen the code for unsupported features and functions, use the code generation
readiness tool.
• To identify build and run-time issues, generate a MEX function from your entry-point
functions. Run the MEX function.

During MATLAB code design, to prepare your code for code generation, you can use tools
outside of the MATLAB Coder app. When you use the MATLAB Coder app to generate
code, the app screens your code for coding issues and code generation readiness. If you
perform the Check for Run-Time Issues step, the app generates and runs a MEX
function. If the app finds issues, it displays warning and error messages. If you click a
message, the app highlights the problem code in a pane where you can edit the code.
Checking for Issues at Design Time

There are two tools that help you detect code generation issues at design time: the Code
Analyzer and the code generation readiness tool.

Use the Code Analyzer in the MATLAB Editor to check for coding issues at design time.
The Code Analyzer continuously checks your code as you enter it. It reports issues and
recommends modifications to maximize performance and maintainability.

To use the Code Analyzer to identify warnings and errors specific to MATLAB for
code generation, add the %#codegen directive to your MATLAB file. A complete list of
MATLAB for code generation Code Analyzer messages is available in the MATLAB Code
Analyzer preferences. See “Running the Code Analyzer Report”.

Note: The Code Analyzer might not detect all code generation issues. After eliminating
the errors or warnings that the Code Analyzer detects, compile your code with MATLAB
Coder to determine if the code has other compliance issues.

The code generation readiness tool screens MATLAB code for features and functions
that code generation does not support. The tool provides a report that lists the source

2-11
2 Tutorials

files that contain unsupported features and functions. It also gives an indication of the
amount of work to make the MATLAB code suitable for code generation.

You can access the code generation readiness tool in the following ways:

• In the current folder browser — right-click a MATLAB file


• Using the command-line interface — use the coder.screener function.
• Using the MATLAB Coder app — after you specify your entry-point files, the app runs
the Code Analyzer and code generation readiness tool.

Checking for Issues at Code Generation Time

You can use MATLAB Coder to check for issues at code generation time. MATLAB Coder
checks that your MATLAB code is suitable for code generation.

When MATLAB Coder detects errors or warnings, it generates an error report that
describes the issues and provides links to the problematic MATLAB code. For more
information, see “Code Generation Reports”.
Checking for Issues at Run Time

You can use MATLAB Coder to generate a MEX function and check for issues at run
time. The MEX function generated for your MATLAB functions includes run-time checks.
Disabling run-time checks and extrinsic calls usually results in streamlined generated
code and faster simulation. Disabling run-time checks allows bugs in your code to cause
MATLAB to fail. For more information, see “Control Run-Time Checks”.

If you encounter run-time errors in your MATLAB functions, a run-time stack appears in
the Command Window. See “Debug Run-Time Errors”.

Make the MATLAB Code Suitable for Code Generation

To begin the process of making your MATLAB code suitable for code generation, you
work with the file kalman01.m. This code is a MATLAB version of a scalar Kalman filter
that estimates the state of a dynamic system from a series of noisy measurements.

1 Set your MATLAB current folder to the work folder that contains your files for this
tutorial. At the MATLAB command prompt, enter:

cd work
work is the full path of the work folder containing your files. See “Files and Folders
that MATLAB Accesses”.

2-12
C Code Generation Using the MATLAB Coder App

2 Open kalman01.m in the MATLAB Editor. At the MATLAB command prompt,


enter:

edit kalman01.m

Tip Before modifying your code, it is a best practice to back up your code.

The file opens in the MATLAB Editor. The Code Analyzer message indicator in the
top right corner of the MATLAB Editor is green. The analyzer did not detect errors,
warnings, or opportunities for improvement in the code.
3 Turn on MATLAB for code generation error checking. After the function declaration,
add the %#codegen directive.

function y = kalman01(z) %#codegen

The Code Analyzer message indicator remains green, indicating that it has not
detected code generation issues.

For more information about using the Code Analyzer, see “Running the Code
Analyzer Report”.
4 Save the file.

You are now ready to compile your code using the MATLAB Coder app.

2-13
2 Tutorials

Opening the MATLAB Coder App

On the MATLAB Toolstrip Apps tab, under Code Generation, click the MATLAB
Coder app icon.

The app opens the Select Source Files page.

Select Source Files

1 On the Select Source Files page, enter or select the name of the entry-point
function kalman01. The app creates a project with the default name kalman01.prj
in the current folder.

2-14
C Code Generation Using the MATLAB Coder App

2 Click Next to go to the Define Input Types step. The app analyzes the function for
coding issues and code generation readiness. If the app identifies issues, it opens the
Review Code Generation Readiness page where you can review and fix issues.
In this example, because the app does not detect issues, it opens the Define Input
Types page.

Define Input Types

Because C uses static typing, MATLAB Coder must determine the properties of
all variables in the MATLAB files at compile time. Therefore, you must specify the
properties of all function inputs. To specify input properties, you can:

• Instruct the app to determine input properties using code that you provide.
• Specify properties directly.

2-15
2 Tutorials

In this example, to define the properties of the input z, specify the test file test01_ui.m
that MATLAB Coder can use to define types automatically for z:

1 Enter or select the test file test01_ui.m.


2 Click Autodefine Input Types.

The test file, test01_ui.m, calls the entry-point function, kalman01.m, with the
expected input types. The test file runs. The app infers that input z is double(2x1).

3 Click Next to go to the Check for Run-Time Issues step.

Check for Run-Time Issues

The Check for Run-Time Issues step generates a MEX file from your entry-point
functions, runs the MEX function, and reports issues. This step is optional. However,
it is a best practice to perform this step. Using this step, you can detect and fix run-
time errors that are harder to diagnose in the generated C code. By default, the MEX
function includes memory integrity checks. These checks perform array bounds and
dimension checking. The checks detect violations of memory integrity in code generated
for MATLAB functions. For more information, see “Control Run-Time Checks”.

2-16
C Code Generation Using the MATLAB Coder App

1 To open the Check for Run-Time Issues dialog box, click the Check for Issues
arrow .
2 In the Check for Run-Time Issues dialog box, specify a test file or enter code that
calls the entry-point file with example inputs. For this example, use the test file
test01_ui that you used to define the input types. Make sure that the dialog box
specifies the test01_ui script.

3 Click Check for Issues.

The app generates a MEX function. It runs the test script test01_ui replacing calls
to kalman01 with calls to the generated MEX. If the app detects issues during the
MEX function generation or execution, it provides warning and error messages. You
can click these messages to navigate to the problematic code and fix the issue. In this
example, the app does not detect issues.

2-17
2 Tutorials

The test script plots the output from generated MEX version of kalman01. The MEX
function has the same functionality as the original kalman01 function.
4 By default, the app collects line execution counts. These counts help you to see
how well the test file, test01_ui exercised the kalman01 function. To view line
execution counts, click View MATLAB line execution counts. The app editor
displays a color-coded bar to the left of the code. To extend the color highlighting over
the code and to see line execution counts, place your cursor over the bar.

2-18
C Code Generation Using the MATLAB Coder App

The orange color indicates that lines 26 and 27 executed one time. This behavior is
expected because this code initializes a persistent variable. A particular shade of
green indicates that the line execution count for this code falls in a certain range. In
this case, the code executes 300 times. For information about how to interpret line
execution counts and turn off collection of the counts, see “Collect and View Line
Execution Counts for Your MATLAB Code”.
5 Click Next to go to the Generate Code step.

Generate C Code

1
To open the Generate dialog box, click the Generate arrow .
2 In the Generate dialog box, set Build type to Static Library (.lib) and
Language to C. Use the default values for the other project build configuration
settings. Different project settings are available for MEX and C/C++ output types.
When you switch between MEX and C/C++ code generation, verify these settings.

2-19
2 Tutorials

3 Click Generate.

MATLAB Coder generates a standalone C static library kalman01 in the


work\codegen\lib\kalman01. work is the folder that contains your tutorial files.
The MATLAB Coder app indicates that code generation succeeded. It displays the
source MATLAB files and generated output files on the left side of the page. On the
Variables tab, it displays information about the MATLAB source variables. On the
Build Log tab, it displays the build log, including compiler warnings and errors. By
default, in the code window, the app displays the C source code file, kalman01.c. To
view a different file, in the Source Code or Output Files pane, click the file name.
4 To view the code generation report, click View Report.
5 Click Next to open the Finish Workflow page.

Reviewing the Finish Workflow Page

The Finish Workflow page indicates that code generation succeeded. It provides a
project summary and links to generated output.

2-20
C Code Generation Using the MATLAB Coder App

Comparing the Generated C Code to Original MATLAB Code

To compare your generated C code to the original MATLAB code, open the C file,
kalman01.c, and the kalman01.m file in the MATLAB Editor.

Here are some important points about the generated C code:

• The function signature is:

void kalman01(const double z[2], double y[2])

z corresponds to the input z in your MATLAB code. The size of z is 2, which


corresponds to the total size (2 x 1) of the example input you used when you compiled
your MATLAB code.

2-21
2 Tutorials

• You can easily compare the generated C code to your original MATLAB code. The code
generation software preserves your function name and comments. When possible, the
software preserves your variable names.

Note: If a variable in your MATLAB code is set to a constant value, it does not appear
as a variable in the generated C code. Instead, the generated C code contains the
actual value of the variable.

Modifying the Filter to Accept a Fixed-Size Input

The filter uses a simple batch process that accepts one input at a time. You must call the
function repeatedly for each input. In this part of the tutorial, you learn how to modify
the algorithm to accept a fixed-sized input. This modification makes the algorithm
suitable for frame-based processing.
Modify Your MATLAB Code

The original filter algorithm accepts only one input. You can modify the algorithm to
process a vector containing more than one input. Modify the algorithm to find the length
of the vector. To call the filter code for each element in the vector, call the filter algorithm
in a for-loop.

1 Open kalman01.m in the MATLAB Editor.

edit kalman01.m
2 Add a for-loop around the filter code.

a Before the comment

% Predicted state and covariance


insert:

for i=1:size(z,2)
b After the comment

% Compute the estimated measurements


y = H * x_est;
insert:

end

Your filter code now looks like this code:

2-22
C Code Generation Using the MATLAB Coder App

for i=1:size(z,2)
% Predicted state and covariance
x_prd = A * x_est;
p_prd = A * p_est * A' + Q;

% Estimation
S = H * p_prd' * H' + R;
B = H * p_prd';
klm_gain = (S \ B)';

% Estimated state and covariance


x_est = x_prd + klm_gain * (z - H * x_prd);
p_est = p_prd - klm_gain * H * p_prd;

% Compute the estimated measurements


y = H * x_est;
end
3 Modify the line that calculates the estimated state and covariance to use the i
th

element of input z.

Change

x_est = x_prd + klm_gain * (z - H * x_prd);


to

x_est = x_prd + klm_gain * (z(:,i) - H * x_prd);


4 Modify the line that computes the estimated measurements to append the result to
the i element of the output y.
th

Change

y = H * x_est;
to

y(:, 1) = H * x_est;

The Code Analyzer message indicator in the top right turns red to indicate that the
Code Analyzer detects an error. The Code Analyzer underlines the offending code in
red and places a red marker to the right.
5 Move your cursor over the red marker to view the error.

2-23
2 Tutorials

The Code Analyzer reports that code generation requires that you fully define
variable y before subscripting it.

Why Preallocate the Outputs?

Preallocate the output y because code generation does not support increasing the
size of an array through indexing. Repeatedly expanding the size of an array over
time can adversely affect the performance of your program. See “Preallocating
Memory”.

6 To address the error, preallocate memory for the output y which is the same size as
the input z. Before the for-loop, add this code:

% Pre-allocate output signal:


y = zeros(size(z));

You no longer see the red error marker and the Code Analyzer message indicator in
the top right edge of the code turns green. The Code Analyzer does not detect errors
or warnings.

For more information about using the Code Analyzer, see “Running the Code
Analyzer Report”.
7 Save the file.

2-24
C Code Generation Using the MATLAB Coder App

Generating C Code for Your Modified Algorithm

The modified algorithm expects fixed-size input. Define the input types for the modified
kalman01 function. Use the test file test02_ui.m to define input types for kalman01.
This script sets the frame size to 10 and calculates the number of frames in the example
input. It then calls the Kalman filter and plots the results for each frame.

1
To go to the Define Input Types step, expand the workflow steps and click
Define Input Types.

2 To delete the type information for z, above the input argument type definitions, click

3 To specify the test file to use for defining input types, enter or select test02_ui.m.
4 Click Autodefine Input Types.

The test file runs. The app infers that the type of z is double(2x10).
5 Click Next to go to the Check for Run-Time Issues step.
6
To open the Check for Issues dialog box, click the Check for Issues arrow .
7 On the Check for Run-Time Issues page, make sure that the dialog box specifies
the test02_ui.m file.
8 Click Check for Issues.

The app generates a MEX function. It runs the test script test02_ui replacing calls
to kalman-01 with calls to the generated MEX. If the app detects issues during
the MEX function generation or execution, it provides warning and error messages.
You can click these messages to navigate to the problematic code and fix the issue.
In this example, the app does not detect issues. The test script plots the output
from generated the MEX version of kalman01. The MEX function has the same
functionality as the original kalman01 function.

2-25
2 Tutorials

9 Click Next to go to the Generate Code step.


10
To open the Generate Code dialog box, click the Generate arrow .
11 Set Build type to Source Code and Language to C.

Selecting Source Code instructs MATLAB Coder to generate code without invoking
the make command. If you use this option, MATLAB Coder does not generate
compiled object code. This option saves you time during the development cycle
when you want to iterate rapidly between modifying MATLAB code and inspecting
generated C code.
12 Click Generate.

MATLAB Coder generates C code in the work\codegen\lib\kalman01 folder.


work is the folder that contains your tutorial files. The MATLAB Coder app
indicates that code generation succeeded. It displays the source MATLAB files and
generated output files on the left side of the page. On the Variables tab, it displays
information about the MATLAB source variables. On the Build Log, it displays the
build log, including compiler warnings and errors. By default, the app displays the
C source code file, kalman01.c. To view a different file, in the Source Code or
Output Files pane, click the file name.
13 View the generated C code.

Some important points about the generated C code are:

• The function signature is now:

void kalman01(const double z[20], double y[20])


The sizes of z and y are now 20, which corresponds to the size of the example
input z (2x10) used to compile your MATLAB code.
• The filtering now takes place in a for-loop. The for-loop iterates over all 10
inputs.

for(i = 0; i < 10; i++)


{
/* Predicted state and covariance */ ...

Use the Filter to Accept a Variable-Size Input

To show that the algorithm is suitable for processing packets of data of varying size, test
your algorithm with variable-size inputs.

2-26
C Code Generation Using the MATLAB Coder App

Test the Algorithm with Variable-Size Inputs

Use the test script test03_ui.m to test the filter with variable-size inputs. The test
script calls the filter algorithm in a loop, passing a different size input to the filter each
time. Each time through the loop, the test script calls the plot_trajectory function for
every position in the input.

To run the test script, at the MATLAB command prompt, enter:

test03_ui

The test script runs and plots the trajectory of the object and the Kalman filter estimated
position.
Generating C Code for Variable-Size Inputs

1
To go to the Define Input Types step, expand the workflow steps and click
Define Input Types.

To specify the test file to use for defining input types, enter or select test03_ui.m.
2 To delete the type information for z, above the input argument type definitions, click

.
3 Click Autodefine Input Types.

The test file runs. The app infers that the input type of z is double(2x:100). The
: in front of the second dimension indicates that this dimension is variable size. The
test file calls kalman01 multiple times with different-size inputs. Therefore, the app
takes the union of the inputs and infers that the inputs are variable size. The upper
bound is equal to the size of the largest input.
4 Click Next to go to the Check for Run-Time Issues step.
5
To open the Check for Issues dialog box, click the Check for Issues arrow .
6 On the Check for Run-Time Issues page, make sure that the dialog box specifies
the test03_ui.m file.
7 Click Check for Issues.

2-27
2 Tutorials

The app builds a MEX file and runs it replacing calls to kalman01 with calls to the
MEX function. The app indicates that it does not detect issues.
8 Click Next to go to the Generate Code step.
9
To open the Generate Code dialog box, click the Generate arrow .
10 Set Build type to Source Code and Language to C.

Selecting Source Code instructs MATLAB Coder to generate code without invoking
the make command. If you use this option, MATLAB Coder does not generate
compiled object code. This option saves you time during the development cycle when
you want to iterate rapidly between MATLAB code modification code and inspection
of generated C code
11 Click Generate.

MATLAB Coder generates C code in the work\codegen\lib\kalman01 folder.


work is the folder that contains your tutorial files. The MATLAB Coder app
indicates that code generation succeeded. It displays the source MATLAB files and
generated output files on the left side of the page. On the Variables tab, it displays
information about the MATLAB source variables. On the Build Log, it displays the
build log, including compiler warnings and errors. By default, the app displays the
C source code file, kalman01.c. To view a different file, in the Source Code or
Output Files pane, click the file name.
12 View the generated C code.

Some important points about the generated C code are:

• The generated C code can process inputs from 2 x 1 to 2 x 100. The function
signature is now:
void kalman01(const double z_data[], const int z_size[2], double y_data[], int y_size[2])

Because y and z are variable size, the generated code contains two pieces of
information about each of them: the data and the actual size of the sample. For
example, for variable z, the generated code contains:

• The data z_data[].


• z_size[2], which contains the actual size of the input data. This information
varies each time the filter is called.

2-28
C Code Generation Using the MATLAB Coder App

• To maximize efficiency, the actual size of the input data z_size is used when
calculating the estimated position. The filter processes only the number of
samples available in the input.

for (i = 0; i <= z_size[1]; i++) {


/* Predicted state and covariance */
for(k = 0; k < 6; k++) {
...

Key Points to Remember


• Before you modify your MATLAB code, back it up.

Use test scripts to separate the pre- and post-processing from the core algorithm.
• If you have a test file that calls the entry-point function with the required class, size,
and complexity, use the Autodefine Input Types option to specify input parameters.
• Perform the Check for Run-Time Issues step to check for run-time errors.

Learn More
• “Next Steps” on page 2-29
• “Product Help” on page 2-30
• “MathWorks Online” on page 2-30

Next Steps

To See
Learn how to integrate your MATLAB code with “Track Object Using MATLAB Code”
Simulink models
Learn more about using MATLAB for code “MATLAB Programming for Code Generation”
generation
Use variable-size data “Variable-Size Data Definition for Code
Generation”
Speed up fixed-point MATLAB code fiaccel
Integrate custom C code into MATLAB code and “Specify External File Locations”
generate embeddable code

2-29
2 Tutorials

To See
Integrate custom C code into a MATLAB coder.ceval
function for code generation

Product Help

MathWorks product documentation is available from the Help menu on the MATLAB
desktop.

MathWorks Online

For additional information and support, visit the MATLAB Coder page on the
MathWorks website at:

www.mathworks.com/products/matlab-coder

2-30
C Code Generation at the Command Line

C Code Generation at the Command Line


In this section...
“Learning Objectives” on page 2-31
“Tutorial Prerequisites” on page 2-31
“Example: The Kalman Filter” on page 2-32
“Files for the Tutorial” on page 2-34
“Design Considerations When Writing MATLAB Code for Code Generation” on page
2-36
“Tutorial Steps” on page 2-37
“Key Points to Remember” on page 2-55
“Best Practices Used in This Tutorial” on page 2-55
“Where to Learn More” on page 2-56

Learning Objectives
In this tutorial, you will learn how to:

• Automatically generate a MEX function from your MATLAB code and use this MEX
function to validate your algorithm in MATLAB before generating C code.
• Automatically generate C code from your MATLAB code.
• Define function input properties at the command line.
• Specify variable-size inputs when generating code.
• Specify code generation properties.
• Generate a code generation report that you can use to debug your MATLAB code and
verify that it is suitable for code generation.

Tutorial Prerequisites
• “What You Need to Know” on page 2-31
• “Required Products” on page 2-32

What You Need to Know

To complete this tutorial, you should have basic familiarity with MATLAB software.

2-31
2 Tutorials

Required Products

To complete this tutorial, you must install the following products:

• MATLAB
• MATLAB Coder
• C compiler

For most platforms, a default compiler is supplied with MATLAB.

MATLAB Coder automatically locates and uses a supported installed compiler. For
the current list of supported compilers, see Supported and Compatible Compilers on
the MathWorks website.

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

For instructions on installing MathWorks products, see the MATLAB installation


documentation for your platform. If you have installed MATLAB and want to check
which other MathWorks products are installed, enter ver in the MATLAB Command
Window.

Example: The Kalman Filter


• “Description” on page 2-32
• “Algorithm” on page 2-33
• “Filtering Process” on page 2-34
• “Reference” on page 2-34

Description

This section describes the example used by the tutorial. You do not have to be familiar
with the algorithm to complete the tutorial.

The example for this tutorial uses a Kalman filter to estimate the position of an object
moving in a two-dimensional space from a series of noisy inputs based on past positions.
The position vector has two components, x and y, indicating its horizontal and vertical
coordinates.

Kalman filters have a wide range of applications, including control, signal and image
processing; radar and sonar; and financial modeling. They are recursive filters that

2-32
C Code Generation at the Command Line

estimate the state of a linear dynamic system from a series of incomplete or noisy
measurements. The Kalman filter algorithm relies on the state-space representation of
filters and uses a set of variables stored in the state vector to characterize completely the
behavior of the system. It updates the state vector linearly and recursively using a state
transition matrix and a process noise estimate.

Algorithm

This section describes the algorithm of the Kalman filter and is implemented in the
MATLAB version of the filter supplied with this tutorial.

The algorithm predicts the position of a moving object based on its past positions using a
Kalman filter estimator. It estimates the present position by updating the Kalman state
vector, which includes the position (x and y), velocity (Vx and Vy), and acceleration (Ax
and Ay) of the moving object. The Kalman state vector, x_est, is a persistent variable.
% Initial conditions
persistent x_est p_est
if isempty(x_est)
x_est = zeros(6, 1);
p_est = zeros(6, 6);
end
x_est is initialized to an empty 6x1 column vector and updated each time the filter is
used.

The Kalman filter uses the laws of motion to estimate the new state:

X = X 0 + Vx.dt
Y = Y0 + Vy.dt
Vx = Vx0 + Ax.dt
Vy = Vy0 + Ay.dt

These laws of motion are captured in the state transition matrix A, which is a matrix that
contains the coefficient values of x, y, Vx, Vy, Ax, and Ay.
% Initialize state transition matrix
dt=1;
A=[ 1 0 dt 0 0 0;...
0 1 0 dt 0 0;...
0 0 1 0 dt 0;...
0 0 0 1 0 dt;...
0 0 0 0 1 0 ;...
0 0 0 0 0 1 ];

2-33
2 Tutorials

Filtering Process

The filtering process has two phases:

• Predicted state and covariance

The Kalman filter uses the previously estimated state, x_est, to predict the current
state, x_prd. The predicted state and covariance are calculated in:

% Predicted state and covariance


x_prd = A * x_est;
p_prd = A * p_est * A' + Q;
• Estimation

The filter also uses the current measurement, z, and the predicted state, x_prd,
to estimate a closer approximation of the current state. The estimated state and
covariance are calculated in:

% Measurement matrix
H = [ 1 0 0 0 0 0; 0 1 0 0 0 0 ];
Q = eye(6);
R = 1000 * eye(2);

% Estimation
S = H * p_prd' * H' + R;
B = H * p_prd';
klm_gain = (S \ B)';

% Estimated state and covariance


x_est = x_prd + klm_gain * (z - H * x_prd);
p_est = p_prd - klm_gain * H * p_prd;

% Compute the estimated measurements


y = H * x_est;

Reference

Haykin, Simon. Adaptive Filter Theory. Upper Saddle River, NJ: Prentice-Hall, Inc.,
1996.

Files for the Tutorial


• “About the Tutorial Files” on page 2-35

2-34
C Code Generation at the Command Line

• “Location of Files” on page 2-35


• “Names and Descriptions of Files” on page 2-35

About the Tutorial Files

The tutorial uses the following files:

• Example MATLAB code files for each step of the tutorial.

Throughout this tutorial, you work with MATLAB files that contain a simple Kalman
filter algorithm.
• Build scripts that you use to compile your function code.
• Test files that:

• Perform the preprocessing functions.


• Call the Kalman filter.
• Perform the post-processing functions.
• A MAT-file that contains input data.

Location of Files

The tutorial files are available in the following folder: docroot\toolbox\coder


\examples\kalman. To run the tutorial, you must copy these files to a local folder. For
instructions, see “Copying Files Locally” on page 2-38.

Names and Descriptions of Files

Type Name Description


Function kalman01.m Baseline MATLAB implementation of a
code scalar Kalman filter.
kalman02.m Version of the original algorithm that is
suitable for code generation.
kalman03.m Kalman filter suitable for use with frame-
based and packet-based inputs.
Build build01.m Generates MEX function for the original
scripts Kalman filter.
build02.m Generates C code for the original Kalman
filter.

2-35
2 Tutorials

Type Name Description


build03.m Generates C code for the frame-based
Kalman filter.
build04.m Generates C code for the variable-size
(packet-based) Kalman filter.
Test test01.m Tests the scalar Kalman filter and plots the
scripts trajectory.
test02.m Tests MEX function for the original Kalman
filter and plots the trajectory.
test03.m Tests the frame-based Kalman filter.
test04.m Tests the variable-size (packet-based)
Kalman filter.
MAT-file position.mat Contains the input data used by the
algorithm.
Plot plot_trajectory.m Plots the trajectory of the object and the
function Kalman filter estimated position.

Design Considerations When Writing MATLAB Code for Code Generation


When writing MATLAB code that you want to convert into efficient, standalone C/C++
code, you must consider the following:

• Data types

C and C++ use static typing. To determine the types of your variables before use,
MATLAB Coder requires a complete assignment to each variable.
• Array sizing

Variable-size arrays and matrices are supported for code generation. You can define
inputs, outputs, and local variables in MATLAB functions to represent data that
varies in size at run time.
• Memory

You can choose whether the generated code uses static or dynamic memory allocation.

With dynamic memory allocation, you potentially use less memory at the expense of
time to manage the memory. With static memory, you get the best speed, but with

2-36
C Code Generation at the Command Line

higher memory usage. Most MATLAB code takes advantage of the dynamic sizing
features in MATLAB, therefore dynamic memory allocation typically enables you
to generate code from existing MATLAB code without much modification. Dynamic
memory allocation also allows some programs to compile even when upper bounds
cannot be found.
• Speed

Because embedded applications must run in real time, the code must be fast enough
to meet the required clock rate.

To improve the speed of the generated code:

• Choose a suitable C/C++ compiler. The default compiler that MathWorks


supplies with MATLAB for Windows 64-bit platforms is not a good compiler for
performance.
• Consider disabling run-time checks.

By default, for safety, the code generated for your MATLAB code contains memory
integrity checks and responsiveness checks. Generally, these checks result in more
generated code and slower simulation. Disabling run-time checks usually results
in streamlined generated code and faster simulation. Disable these checks only if
you have verified that array bounds and dimension checking is unnecessary.

See Also

• “Data Definition Basics”


• “Variable-Size Data”
• “Bounded Versus Unbounded Variable-Size Data”
• “Control Dynamic Memory Allocation”
• “Control Run-Time Checks”

Tutorial Steps
• “Copying Files Locally” on page 2-38
• “Running the Original MATLAB Code” on page 2-39
• “Setting Up Your C Compiler” on page 2-40
• “Considerations for Making Your Code Suitable for Code Generation” on page 2-41
• “Making the MATLAB Code Suitable for Code Generation” on page 2-42

2-37
2 Tutorials

• “Generating a MEX Function Using codegen” on page 2-44


• “Verifying the MEX Function” on page 2-45
• “Generating C Code Using codegen” on page 2-46
• “Comparing the Generated C Code to Original MATLAB Code” on page 2-47
• “Modifying the Filter to Accept a Fixed-Size Input” on page 2-48
• “Modifying the Filter to Accept a Variable-Size Input” on page 2-52
• “Testing the Algorithm with Variable-Size Inputs” on page 2-53
• “Generating C Code for a Variable-Size Input” on page 2-53

Copying Files Locally

Copy the tutorial files to a local working folder:

1 Create a local solutions folder, for example, c:\coder\kalman\solutions.


2 Change to the docroot\toolbox\coder\examples folder. At the MATLAB
command prompt, enter:

cd(fullfile(docroot, 'toolbox', 'coder', 'examples'))


3 Copy the contents of the kalman subfolder to your local solutions folder, specifying
the full path name of the solutions folder:

copyfile('kalman', 'solutions')
Your solutions folder now contains a complete set of solutions for the tutorial. If
you do not want to perform the steps for each task in the tutorial, you can view the
solutions to see how the code should look.
4 Create a local work folder, for example, c:\coder\kalman\work.
5 Copy the following files from your solutions folder to your work folder.

• kalman01.m
• position.mat
• Build files build01.m through build04.m
• Test scripts test01.m through test04.m
• plot_trajectory.m

Your work folder now contains the files that you need to get started with the
tutorial.

2-38
C Code Generation at the Command Line

Running the Original MATLAB Code

In this tutorial, you work with a MATLAB function that implements a Kalman filter
algorithm, which predicts the position of a moving object based on its past positions.
Before generating C code for this algorithm, you make the MATLAB version suitable for
code generation and generate a MEX function. Then you test the resulting MEX function
to validate the functionality of the modified code. As you work through the tutorial, you
refine the design of the algorithm to accept variable-size inputs.

First, use the script test01.m to run the original MATLAB function to see how the
Kalman filter algorithm works. This script loads the input data and calls the Kalman
filter algorithm to estimate the location. It then calls a plot function, plot_trajectory,
which plots the trajectory of the object and the Kalman filter estimated position.

1 Set your MATLAB current folder to the work folder that contains your files for this
tutorial. At the MATLAB command prompt, enter:

cd work
where work is the full path name of the work folder containing your files. For more
information, see “Files and Folders that MATLAB Accesses”.
2 At the MATLAB command prompt, enter:

test01

The test script runs and plots the trajectory of the object in blue and the Kalman
filter estimated position in green. Initially, you see that it takes a short time for
the estimated position to converge with the actual position of the object. Then three
sudden shifts in position occur—each time the Kalman filter readjusts and tracks the
object after a few iterations.

2-39
2 Tutorials

Setting Up Your C Compiler

MATLAB Coder automatically locates and uses a supported installed compiler. For the
current list of supported compilers, see Supported and Compatible Compilers on the
MathWorks website.

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

2-40
C Code Generation at the Command Line

Considerations for Making Your Code Suitable for Code Generation


Designing for Code Generation

Before generating code, you must prepare your MATLAB code for code generation. The
first step is to eliminate unsupported constructs.
Checking for Issues at Design Time

There are two tools that help you detect code generation issues at design time: the code
analyzer and the code generation readiness tool.

You use the code analyzer in the MATLAB Editor to check for coding issues at design
time, minimizing compilation errors. The code analyzer continuously checks your code as
you enter it. It reports issues and recommends modifications to maximize performance
and maintainability.

To use the code analyzer to identify warnings and errors specific to MATLAB for code
generation, you must add the %#codegen directive (or pragma) to your MATLAB file. A
complete list of MATLAB for Code Generation code analyzer messages is available in the
MATLAB Code Analyzer preferences. See “Running the Code Analyzer Report”.

Note: The code analyzer might not detect all MATLAB for code generation issues. After
eliminating errors or warnings that the code analyzer detects, compile your code with
MATLAB Coder to determine if the code has other compliance issues.

The code generation readiness tool screens MATLAB code for features and functions that
are not supported for code generation. The tool provides a report that lists the source files
that contain unsupported features and functions and an indication of how much work is
required to make the MATLAB code suitable for code generation.

You can access the code generation readiness tool in the following ways:

• In the current folder browser — by right-clicking a MATLAB file


• At the command line — by using the coder.screener function.
• Using the MATLAB Coder app — after you specify your entry-point files, the app runs
the Code Analyzer and code generation readiness tool.
Checking Issues at Code Generation Time

You can use codegen to check for issues at code generation time. codegen checks that
your MATLAB code is suitable for code generation.

2-41
2 Tutorials

When codegen detects errors or warnings, it automatically generates an error report


that describes the issues and provides links to the offending MATLAB code. For more
information, see “Code Generation Reports”.

After code generation, codegen generates a MEX function that you can use to test your
implementation in MATLAB.
Checking for Issues at Run Time

You can use codegen to generate a MEX function and check for issues at run time. In
simulation, the code generated for your MATLAB functions includes the run-time checks.
Disabling run-time checks and extrinsic calls usually results in streamlined generated
code and faster simulation. You control run-time checks using the MEX configuration
object, coder.MexCodeConfig. For more information, see “Control Run-Time Checks”.

If you encounter run-time errors in your MATLAB functions, a run-time stack appears
automatically in the MATLAB Command Window. See “Debug Run-Time Errors”.

Making the MATLAB Code Suitable for Code Generation


Making Your Code Suitable for Code Generation

To modify the code yourself, work through the exercises in this section. Otherwise,
open the supplied file kalman02.m in your solutions subfolder to see the modified
algorithm.

To begin the process of making your MATLAB code suitable for code generation, you
work with the file kalman01.m. This code is a MATLAB version of a scalar Kalman filter
that estimates the state of a dynamic system from a series of noisy measurements.

1 Set your MATLAB current folder to the work folder that contains your files for this
tutorial. At the MATLAB command prompt, enter:
cd work
where work is the full path name of the work folder containing your files. See “Files
and Folders that MATLAB Accesses”.
2 Open kalman01.m in the MATLAB Editor. At the MATLAB command prompt,
enter:
edit kalman01.m

The file opens in the MATLAB Editor. The code analyzer message indicator in the
top right corner of the MATLAB Editor is green, which indicates that it has not
detected errors, warnings, or opportunities for improvement in the code.

2-42
C Code Generation at the Command Line

3 Turn on MATLAB for code generation error checking by adding the %#codegen
directive after the function declaration.

function y = kalman01(z) %#codegen

The code analyzer message indicator remains green, indicating that it has not
detected code generation related issues.

For more information on using the code analyzer, see “Running the Code Analyzer
Report”.
4 Save the file in the current folder as kalman02.m:

a To match the function name to the file name, change the function name to
kalman02.

function y = kalman02(z)
b In the MATLAB Editor, select Save As from the File menu.
c Enter kalman02.m as the new file name.

Note: If you do not match the file name to the function name, the code analyzer
warns you that these names are not the same and highlights the function name
in orange to indicate that it can provide an automatic correction. For more
information, see “Changing Code Based on Code Analyzer Messages”.
d Click Save.

2-43
2 Tutorials

You are now ready to compile your code using codegen. By default, codegen checks
that your MATLAB code is suitable for code generation. Then, after compilation,
codegen generates a MEX function that you can test in MATLAB.

Generating a MEX Function Using codegen

Because C uses static typing, codegen must determine the properties of all variables
in the MATLAB files at compile time. Therefore, you must specify the properties of all
function inputs at the same time as you compile the file with codegen.

To compile kalman02.m, you must specify the size of the input vector y.

1 Load the position.mat file into your MATLAB workspace.

load position.mat
This command loads a matrix position containing the x and y coordinates of 310
points in Cartesian space.
2 Get the first vector in the position matrix.

z = position(1:2,1);
3 Compile the file kalman02.m using codegen.

codegen -report kalman02.m -args {z}

codegen reports that the code generation is complete. By default, it generates a


MEX function, kalman02_mex, in the current folder and provides a link to the code
generation report.

Note that:

• The -report option instructs codegen to generate a code generation report,


which you can use to debug your MATLAB code and verify that it is suitable for
code generation.
• The -args option instructs codegen to compile the file kalman02.m using the
class, size, and complexity of the sample input parameter z.

You have proved that the Kalman filter example code is suitable for code generation
using codegen. You are ready to begin the next task in this tutorial, “Verifying the MEX
Function” on page 2-45.

2-44
C Code Generation at the Command Line

Verifying the MEX Function

In this part of the tutorial, you test the MEX function to verify that it provides the same
functionality as the original MATLAB code.

In addition, simulating your algorithm in MATLAB before generating C code enables


you to detect and fix run-time errors that would be much harder to diagnose in the
generated C code. By default, the MEX function includes memory integrity checks. These
checks perform array bounds and dimension checking and detect violations of memory
integrity in code generated for MATLAB functions. If a violation is detected, MATLAB
stops execution with a diagnostic message. For more information, see “Control Run-Time
Checks”.
Running the Generated MEX Function

You run the MEX function, kalman02_mex, using coder.runTest to call the test file,
test02. This test file is the same as test01 that you used in “Running the Original
MATLAB Code” on page 2-39 except that it calls kalman02 instead of kalman01.

Contents of test02.m

% Figure setup
clear all;
load position.mat
numPts = 300;
figure;hold;grid;

% Kalman filter loop


for idx = 1: numPts
% Generate the location data
z = position(:,idx);

% Use Kalman filter to estimate the location


y = kalman02(z);

% Plot the results


plot_trajectory(z,y);
end
hold;

coder.runTest runs the test file and replaces calls to the MATLAB algorithm with
calls to the MEX function.
coder.runTest('test02','kalman02')

2-45
2 Tutorials

coder.runTest runs the MEX function, kalman02_mex, using the same inputs you
used in “Running the Original MATLAB Code” on page 2-39.

The test script runs and plots the trajectory of the object and the Kalman filter estimated
position as before.

You have generated a MEX function for your MATLAB code, verified that it is
functionally equivalent to your original MATLAB code, and checked for run-time errors.
Now you are ready to begin the next task in this tutorial, “Generating C Code Using
codegen” on page 2-46.

Generating C Code Using codegen

In this task, you use codegen to generate C code for your MATLAB filter algorithm. You
then view the generated C code using the MATLAB Coder code generation report and
compare the generated C code with the original MATLAB code. You use the supplied
build script build02.m to generate code.
About the Build Script

A build script automates a series of MATLAB commands that you want to perform
repeatedly from the command line, saving you time and eliminating input errors.

The build script build02.m contains:


% Load the position vector
load position.mat
% Get the first vector in the position matrix
% to use as an example input
z = position(1:2,1);
% Generate C code only, create a code generation report
codegen -c -d build02 -config coder.config('lib')
-report kalman02.m -args {z}
Note that:

• codegen opens the file kalman02.m and automatically translates the MATLAB code
into C source code.
• The -c option instructs codegen to generate code only, without compiling the code to
an object file. This option enables you to iterate rapidly between modifying MATLAB
code and generating C code.
• The -config coder.config('lib') option instructs codegen to generate
embeddable C code suitable for targeting a static library instead of generating the
default MEX function. For more information, see coder.config.

2-46
C Code Generation at the Command Line

• The -d option instructs codegen to generate code in the output folder build02.
• The -report option instructs codegen to generate a code generation report that you
can use to debug your MATLAB code and verify that it is suitable for code generation.
• The -args option instructs codegen to compile the file kalman01.m using the class,
size, and complexity of the sample input parameter z.
How to Generate C Code

1 Run the build script.


build02

MATLAB processes the build file and outputs the message:


Code generation successful: View report.
codegen generates files in the folder, build02.
2 To view the code generation report, click View report.

The MATLAB Coder Code Generation Report opens and displays the generated code,
kalman02.c.

The file appears in the right pane. The code generation report provides a hyperlink
to open the C code in the MATLAB Editor.

To learn more about the report, see “Code Generation Reports”.

Comparing the Generated C Code to Original MATLAB Code

To compare your generated C code to the original MATLAB code, open the C file,
kalman02.c, and the kalman02.m file in the MATLAB Editor.

Here are some important points about the generated C code:

• The function signature is:


void kalman02(const double z[2], double y[2])
z corresponds to the input z in your MATLAB code. The size of z is 2, which
corresponds to the total size (2 x 1) of the example input you used when you compiled
your MATLAB code.
• You can easily compare the generated C code to your original MATLAB code. In the
generated C code:

• Your function name is unchanged.

2-47
2 Tutorials

• Your comments are preserved in the same position.


• Your variable names are the same as in the original MATLAB code.

Note: If a variable in your MATLAB code is set to a constant value, it does not
appear as a variable in the generated C code. Instead, the generated C code
contains the actual value of the variable.

Modifying the Filter to Accept a Fixed-Size Input

The filter you have worked on so far in this tutorial uses a simple batch process that
accepts one input at a time, so you must call the function repeatedly for each input. In
this part of the tutorial, you learn how to modify the algorithm to accept a fixed-sized
input, which makes the algorithm suitable for frame-based processing.
Modifying Your MATLAB Code

To modify the code yourself, work through the exercises in this section. Otherwise, open
the supplied file kalman03.m in your solutions subfolder to see the modified algorithm.

The filter algorithm you have used so far in this tutorial accepts only one input. You can
now modify the algorithm to process a vector containing more than one input. You need
to find the length of the vector and call the filter code for each element in the vector in
turn. You do this by calling the filter algorithm in a for-loop.

1 Open kalman02.m in the MATLAB Editor.


edit kalman02.m
2 Add a for-loop around the filter code.

a Before the comment


% Predicted state and covariance
insert:
for i=1:size(z,2)
b After
% Compute the estimated measurements
y = H * x_est;
insert:
end

2-48
C Code Generation at the Command Line

Your filter code should now look like this:


for i=1:size(z,2)
% Predicted state and covariance
x_prd = A * x_est;
p_prd = A * p_est * A' + Q;

% Estimation
S = H * p_prd' * H' + R;
B = H * p_prd';
klm_gain = (S \ B)';

% Estimated state and covariance


x_est = x_prd + klm_gain * (z - H * x_prd);
p_est = p_prd - klm_gain * H * p_prd;

% Compute the estimated measurements


y = H * x_est;
end
3 Modify the line that calculates the estimated state and covariance to use the i
th

element of input z.

Change
x_est = x_prd + klm_gain * (z - H * x_prd);
to
x_est = x_prd + klm_gain * (z(:,i) - H * x_prd);
4 Modify the line that computes the estimated measurements to append the result to
the i element of the output y.
th

Change
y = H * x_est;
to
y(:,i) = H * x_est;

The code analyzer message indicator in the top right turns red to indicate that the
code analyzer has detected an error. The code analyzer underlines the offending code
in red and places a red marker to the right.
5 Move your pointer over the red marker to view the error.

2-49
2 Tutorials

The code analyzer reports that code generation requires variable y to be fully defined
before subscripting it.

Why Preallocate the Outputs?

You must preallocate outputs here because the MATLAB for code generation does
not support increasing the size of an array over time. Repeatedly expanding the size
of an array over time can adversely affect the performance of your program. See
“Preallocating Memory”.

6 To address the error, preallocate memory for the output y, which is the same size as
the input z. Add this code before the for-loop.

% Pre-allocate output signal:


y=zeros(size(z));

The red error marker disappears and the code analyzer message indicator in the top
right edge of the code turns green, which indicates that you have fixed the errors and
warnings detected by the code analyzer.

For more information on using the code analyzer, see “Running the Code Analyzer
Report”.

2-50
C Code Generation at the Command Line

7 Change the function name to kalman03 and save the file as kalman03.m in the
current folder.

You are ready to begin the next task in the tutorial, “Testing Your Modified Algorithm”
on page 2-51.

Testing Your Modified Algorithm

Use the test script test03.m to test kalman03.m. This script sets the frame size to 10
and calculates the number of frames in the example input. It then calls the Kalman filter
and plots the results for each frame in turn.

At the MATLAB command prompt, enter:

test03

The test script runs and plots the trajectory of the object and the Kalman filter estimated
position as before.

You are ready to begin the next task in the tutorial, “Generating C Code for Your
Modified Algorithm” on page 2-51.

Note: Before generating C code, it is best practice to generate a MEX function that you
can execute within the MATLAB environment to test your algorithm and check for run-
time errors.

Generating C Code for Your Modified Algorithm

You use the supplied build script build03.m to generate code. The only difference
between this build script and the script for the initial version of the filter is the example
input used when compiling the file. build03.m specifies that the input to the function is
a matrix containing five 2x1 position vectors, which corresponds to a frame size of 10.

Contents of build03.m

% Load the position vector


load position.mat
% Get the first 5 positions in the position matrix to use
% as an example input
z = position(1:2,1:5);

2-51
2 Tutorials

% Generate C code only, create a code generation report


codegen -c -config coder.config('lib') -report kalman03.m -args {z}

To generate C code for kalman03:

1 At the MATLAB command prompt, enter:


build03

MATLAB processes the build file and outputs the message:


Code generation successful: View report.

The generated C code is in work\codegen\lib\kalman03, where work is the folder


that contains your tutorial files.
2 To view the generated C code:

a Click View report.

The MATLAB Coder Code Generation Report opens and displays the generated
coder, kalman03.c.
3 Compare the generated C code with the C code for the scalar Kalman filter. You see
that the code is almost identical except that there is a now a for-loop for the frame
processing.

Here are some important points about the generated C code:

• The function signature is now:


void kalman03(const double z[10], double y[10])
The size of z and y is now 10, which corresponds to the size of the example input
z (2x5) used to compile your MATLAB code.
• The filtering now takes place in a for-loop. The for-loop iterates over all 5
inputs.
for(i = 0; i < 5; i++)
{
/* Predicted state and covariance */ ...

Modifying the Filter to Accept a Variable-Size Input

The algorithm you have used so far in this tutorial is suitable for processing input data
that consists of fixed-size frames. In this part of the tutorial, you test your algorithm with

2-52
C Code Generation at the Command Line

variable-size inputs and see that the algorithm is suitable for processing packets of data
of varying size. You then learn how to generate code for a variable-size input.

Testing the Algorithm with Variable-Size Inputs

Use the test script test04.m to test kalman03.m with variable-size inputs.

The test script calls the filter algorithm in a loop, passing a different size input to the
filter each time. Each time through the loop, the test script calls the plot_trajectory
function for every position in the input.

To run the test script, at the MATLAB command prompt, enter:


test04

The test script runs and plots the trajectory of the object and the Kalman filter estimated
position as before.

You have created an algorithm that accepts variable-size inputs. You are ready to begin
the next task in the tutorial, “Generating C Code for a Variable-Size Input” on page
2-53.

Note: Before generating C code, it is best practice to generate a MEX function that you
can execute within the MATLAB environment to test your algorithm and check for run-
time errors.

Generating C Code for a Variable-Size Input

You use the supplied build script build04.m to generate code.


About the Build Script

Contents of build04.m
% Load the position vector
load position.mat
N=100;
% Get the first N vectors in the position matrix to
% use as an example input
z = position(1:2,1:N);
% Specify the upper bounds of the variable-size input z
% using the coder.typeof declaration - the upper bound

2-53
2 Tutorials

% for the first dimension is 2; the upper bound for


% the second dimension is N. The first dimension is fixed,
% the second is variable.
eg_z = coder.typeof(z, [2 N], [0 1]);
% Generate C code only
% specify upper bounds for variable-size input z
codegen -c -config coder.config('lib') -report kalman03.m -args {eg_z}

This build file:

• Specifies the upper bounds explicitly for the variable-size input using the declaration
coder.typeof(z, [2 N], [0 1]) with the -args option on the codegen
command line. The second input, [2 N], specifies the size and upper bounds of the
variable size input z. Because N=100, coder.typeof specifies that the input to the
function is a matrix with two dimensions, the upper bound for the first dimension
is 2; the upper bound for the second dimension is 100. The third input specifies
which dimensions are variable. A value of true or one means that the corresponding
dimension is variable; a value of false or zero means that the corresponding
dimension is fixed. The value [0 1] specifies that the first dimension is fixed,
the second dimension is variable. For more information, see “Generating Code for
MATLAB Functions with Variable-Size Data”.
• Creates a code configuration object cfg and uses it with the -config option to specify
code generation parameters. For more information, see coder.config.

How to Generate C Code for a Variable-Size Input

1 Use the build script build04 to generate C code.

build04
2 View the generated C code as before.

Here are some important points about the generated C code:

• The generated C code can process inputs from 2 x 1 to 2 x 100. The function
signature is now:
void kalman01(const double z_data[], const int z_size[2], double y_data[], int y_size[2])

Because y and z are variable size, the generated code contains two pieces of
information about each of them: the data and the actual size of the sample. For
example, for variable z, the generated code contains:

• The data z_data[].

2-54
C Code Generation at the Command Line

• z_size[2], which contains the actual size of the input data. This information
varies each time the filter is called.
• To maximize efficiency, the actual size of the input data z_size is used when
calculating the estimated position. The filter processes only the number of
samples available in the input.

for(i = 0; i+1 <= z_size[1]; i++) {


/* Predicted state and covariance */
for(k = 0; k < 6; k++) {
...

Key Points to Remember


• Back up your MATLAB code before you modify it.
• Decide on a naming convention for your files and save interim versions frequently.
For example, this tutorial uses a two-digit suffix to differentiate the various versions
of the filter algorithm.
• Use build scripts to build your files.
• Use test scripts to separate the pre- and post-processing from the core algorithm.
• Generate a MEX function before generating C code. Use this MEX function to
simulate your algorithm in MATLAB to validate its operation and check for run-time
errors.
• Use the -args option to specify input parameters at the command line.
• Use the -report option to create a code generation report.
• Use coder.typeof to specify variable-size inputs.
• Use the code generation configuration object (coder.config) to specify parameters
for standalone C code generation.

Best Practices Used in This Tutorial


Best Practice — Preserving Your Code

Preserve your code before making further modifications. This practice provides a
fallback in case of error and a baseline for testing and validation. Use a consistent file
naming convention. For example, add a two-digit suffix to the file name for each file in a
sequence.

2-55
2 Tutorials

Best Practice — Comparing Files

Use the MATLAB Compare Against option to compare two MATLAB files to examine
differences between files.

Best Practice — Generating a Code Generation Report

Use the -report option to generate an HTML report with links to your MATLAB code
files and compile-time type information for the variables and expressions in your code.
This information simplifies finding sources of error messages and aids understanding
of type propagation rules. If you do not specify this option, codegen generates a report
only if errors or warnings occur. See “-report Generate Code Generation Report” on page
3-2.

Best Practice — Using Build Scripts

A build script automates a series of MATLAB commands that you want to perform
repeatedly from the command line, saving you time and eliminating input errors. See
“Using Build Scripts” on page 3-5.

Best Practice — Separating Your Test Bench from Your Function Code

Separate your core algorithm from your test bench. Create a separate test script to do
the pre- and post-processing such as loading inputs, setting up input values, calling the
function under test, and outputting test results.

Where to Learn More


• “Next Steps” on page 2-56
• “Product Help” on page 2-57
• “MathWorks Online” on page 2-57

Next Steps

To... See...
See the compilation options for codegen codegen
Learn how to integrate your MATLAB code with “Track Object Using MATLAB Code”
Simulink models
Learn more about using MATLAB for code “MATLAB Programming for Code Generation”
generation

2-56
C Code Generation at the Command Line

To... See...
Use variable-size data “Variable-Size Data Definition for Code
Generation”
Speed up fixed-point MATLAB code fiaccel
Integrate custom C code into MATLAB code and “Specify External File Locations”
generate standalone code
Integrate custom C code into a MATLAB coder.ceval
function for code generation
Generate HDL from MATLAB code www.mathworks.com/products/slhdlcoder

Product Help

MathWorks product documentation is available from the Help menu on the MATLAB
desktop.

MathWorks Online

For additional information and support, visit the MATLAB Coder page on the
MathWorks website at:

www.mathworks.com/products/matlab-coder

2-57
2 Tutorials

MEX Function Generation at the Command Line


In this section...
“Learning Objectives” on page 2-58
“Tutorial Prerequisites” on page 2-58
“Example: Euclidean Minimum Distance” on page 2-59
“Files for the Tutorial” on page 2-61
“Tutorial Steps” on page 2-62
“Key Points to Remember” on page 2-78
“Best Practices Used in This Tutorial” on page 2-78
“Where to Learn More” on page 2-79

Learning Objectives
In this tutorial, you will learn how to:

• Automatically generate a MEX function from your MATLAB code.


• Define function input properties at the command line.
• Specify the upper bounds of variable-size data.
• Specify variable-size inputs.
• Generate a code generation report that you can use to debug your MATLAB code and
verify that it is suitable for code generation.

Tutorial Prerequisites
• “What You Need to Know” on page 2-58
• “Required Products” on page 2-58

What You Need to Know

To complete this tutorial, you should have basic familiarity with MATLAB software.

Required Products

To complete this tutorial, you must install the following products:

2-58
MEX Function Generation at the Command Line

• MATLAB
• MATLAB Coder
• C compiler

For most platforms, a default compiler is supplied with MATLAB.

MATLAB Coder automatically locates and uses a supported installed compiler. For
the current list of supported compilers, see Supported and Compatible Compilers on
the MathWorks website.

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

For instructions on installing MathWorks products, refer to the installation


documentation. If you have installed MATLAB and want to check which other
MathWorks products are installed, enter ver in the MATLAB Command Window.

Example: Euclidean Minimum Distance


• “Description” on page 2-59
• “Algorithm” on page 2-60

Description

The Euclidean distance between points p and q is the length of the line segment pq .
In Cartesian coordinates, if p = ( p1 , p2,..., pn) and q = ( q1 , q2,..., qn) are two points in
Euclidean n-space, then the distance from p to q is given by:

d( p, q) = p - q

= ( p1 - q1 )2 + ( p2 - q2 )2 + ... + ( pn - qn ) 2
n
= Â ( pi - qi )2
i=1

In one dimension, the distance between two points, x1 and x2, on a line is simply the
absolute value of the difference between the two points:

2-59
2 Tutorials

( x2 - x1 ) 2 = x2 - x1

In two dimensions, the distance between p = ( p1 , p2 ) and q = ( q1 , q2 ) is:

( p1 - q1 )2 + ( p2 - q2 )2

The example for this tutorial computes the minimum Euclidean distance between
a column vector x and a collection of column vectors in the codebook matrix cb. The
function has three output variables:

• y, the vector in cb with the minimum distance to x


• idx, the index of the column vector in cb corresponding to the closest vector
• distance, the distance between x and y

Algorithm

This algorithm computes the minimum Euclidean distance between a column vector x
and a collection of column vectors in the codebook matrix cb. The algorithm computes the
minimum distance to x and finds the column vector in cb that is closest to x. It outputs
this column vector, y, its index, idx, in cb, and distance, the distance between x and y.

The function signature for the algorithm is:


function [y,idx,distance] = euclidean(x,cb)

The minimum distance is initially set to the first element of cb.


idx=1;
distance=norm(x-cb(:,1));

The minimum distance calculation is performed in the for-loop.


for index=2:size(cb,2)
d=norm(x-cb(:,index));
if d < distance
distance=d;
idx=index;
end
end

The output y is set to the minimum distance vector.


y=cb(:,idx);

2-60
MEX Function Generation at the Command Line

Files for the Tutorial


• “About the Tutorial Files” on page 2-61
• “Location of Files” on page 2-61
• “Names and Descriptions of Files” on page 2-61

About the Tutorial Files

The tutorial uses the following files:

• Example MATLAB code files for each step of the tutorial.

Throughout this tutorial, you work with MATLAB files that contain a simple
Euclidean distance algorithm.
• Build scripts that you use to compile your function code.
• Test files that:

• Perform the preprocessing functions, for example, setting up input data.


• Call the specified Euclidean function.
• Perform the post-processing functions, for example, plotting the distances.
• A MAT-file that contains example input data.

Location of Files

The tutorial files are available in the following folder: docroot\toolbox\coder


\examples\euclidean. To run the tutorial, you must copy these files to a local folder.
For instructions, see “Copying Files Locally” on page 2-63.

Names and Descriptions of Files

Type Name Description


Function euclidean01.m Baseline MATLAB implementation of
code Euclidean minimum distance algorithm
including plot functions.
euclidean02.m Version of the original algorithm with the
%#codegen directive.
euclidean03.m Version of the original algorithm without
plotting functions.

2-61
2 Tutorials

Type Name Description


euclidean04.m Modified algorithm that uses assert to specify
the upper bounds of variable N.
Build build01.m Build script for euclidean03.m.
script build02.m Build script for euclidean03.m specifying
two-dimensional inputs.
build03.m Build script for euclidean03.m specifying
variable-size inputs.
build04.m Build script for euclidean04.m.
Test script test01.m Initial version of test script, includes plot
functions. Tests euclidean03 MEX function.
test02.m Tests the three-dimensional euclidean03
MEX function with two-dimensional inputs.
test03.m Tests the two-dimensional euclidean04 MEX
function with two-dimensional inputs.
test04.m Tests euclidean03_varsize MEX function
with two-dimensional and three-dimensional
inputs.
test05.m Tests euclidean04 MEX function specifying
how many elements of each input to process.
MAT-file euclidean.mat Contains the input data used by the algorithm.

Tutorial Steps
• “Copying Files Locally” on page 2-63
• “Running the Original MATLAB Code” on page 2-63
• “Setting Up Your C Compiler” on page 2-66
• “Considerations for Making Your Code Compliant” on page 2-66
• “Making the MATLAB Code Suitable for Code Generation” on page 2-67
• “Generating a MEX Function Using codegen” on page 2-68
• “Validating the MEX Function” on page 2-69
• “Using Build and Test Scripts” on page 2-70
• “Modifying the Algorithm to Accept Variable-Size Inputs” on page 2-73

2-62
MEX Function Generation at the Command Line

• “Specifying Upper Bounds for Local Variables” on page 2-76

Copying Files Locally

Copy the tutorial files to a local solutions folder and create a local working folder:

1 Create a local solutions folder, for example, c:\coder\euclidean\solutions.


2 Change to the docroot\toolbox\coder\examples folder. At the MATLAB
command prompt, enter:

cd(fullfile(docroot, 'toolbox', 'coder', 'examples'))


3 Copy the contents of the euclidean subfolder to your local solutions folder,
specifying the full pathname of the solutions folder:

copyfile('euclidean', 'solutions')
Your solutions folder now contains a complete set of solutions for the tutorial. If
you do not want to perform the steps for each task in the tutorial, you can view the
solutions to see how the code should look.
4 Create a local work folder, for example, c:\coder\euclidean\work.
5 Copy the following files from your solutions folder to your work folder.

• euclidean01.m
• euclidean.mat
• Build files build01.m through build04.m
• Test scripts test01.m through test05.m

Your work folder now contains the files that you need to get started with the
tutorial.

Running the Original MATLAB Code

In this tutorial, you work with a MATLAB function that implements the Euclidean
distance minimizing algorithm. You make the MATLAB version of this algorithm
suitable for code generation and test the resulting MEX function to validate the
functionality of the modified code. As you work through the tutorial, you refine the design
of the algorithm to accept variable-size inputs.

Before generating a MEX function, run the original MATLAB function to see how the
Euclidean distance minimizing algorithm works.

2-63
2 Tutorials

1 Set your MATLAB current folder to the work folder that contains your files for this
tutorial.

cd work
work is the full path name of the work folder containing your files. For more
information, see “Files and Folders that MATLAB Accesses”.
2 Load the euclidean.mat file into your MATLAB workspace.

load euclidean.mat
Your MATLAB workspace now contains:

• A matrix x containing 40000 three-dimensional vectors.


• A matrix cb containing 216 three-dimensional vectors.

The Euclidean algorithm minimizes the distance between a column vector, x1, taken
from matrix x, and the column vectors in the codebook matrix cb. It outputs the
column vector in cb that is closest to x1.
3 Create a single input vector x1 from the matrix x.

x1=x(:,1)

The result is the first vector from x:

x1 =

0.8568
0.7455
0.3835
4 Use the Euclidean algorithm to find the vector in codebook matrix cb that is closest
to x1. At the MATLAB command prompt, enter:

[y, idx, distance]=euclidean01(x1,cb)

The Euclidean algorithm runs and plots the lines from x1 to each vector in cb.

2-64
MEX Function Generation at the Command Line

After completing the algorithm, it outputs the coordinates of the point y, which is the
vector in cb closest to x1, together with the index idx of x1 in cb, and the distance,
distance, between y and x1.

y =
0.8000
0.8000
0.4000

idx =
171

distance =
0.0804

The algorithm computes that the point y=0.8000, 0.8000, 0.4000, the 171st
vector in cb, is closest to point x1. The distance between y and x1 is 0.0804.

2-65
2 Tutorials

Where to Go Next

Before continuing with the tutorial, you must set up your C compiler as detailed in
“Setting Up Your C Compiler” on page 2-66.

Setting Up Your C Compiler


MATLAB Coder automatically locates and uses a supported installed compiler. For the
current list of supported compilers, see Supported and Compatible Compilers on the
MathWorks website.

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

Considerations for Making Your Code Compliant


Designing for Code Generation

Before generating code, you must prepare your MATLAB code for code generation. The
first step is to eliminate unsupported constructs.
Checking for Issues at Design Time

There are two tools that help you detect code generation issues at design time: the code
analyzer and the code generation readiness tool.

You use the code analyzer in the MATLAB Editor to check for code issues at design time,
minimizing compilation errors. The code analyzer continuously checks your code as you
enter it. It reports problems and recommends modifications to maximize performance
and maintainability.

To use the code analyzer to identify warnings and errors specific to MATLAB for code
generation, you must add the %#codegen directive (or pragma) to your MATLAB file. A
complete list of MATLAB for Code Generation code analyzer messages is available in the
MATLAB Code Analyzer preferences. See “Running the Code Analyzer Report” for more
details.

Note: The code analyzer might not detect all MATLAB for code generation issues. After
eliminating errors or warnings that the code analyzer detects, compile your code with
MATLAB Coder to determine if the code has other compliance issues.

The code generation readiness tool screens MATLAB code for features and functions that
are not supported for code generation. The tool provides a report that lists the source files

2-66
MEX Function Generation at the Command Line

that contain unsupported features and functions and an indication of how much work is
required to make the MATLAB code suitable for code generation.

You can access the code generation readiness tool in the following ways:

• In the current folder browser — by right-clicking a MATLAB file


• At the command line — by using the coder.screener function.
• In a project — when you add a MATLAB file to a project, if MATLAB Coder detects
code generation issues, it provides a link to the code generation readiness report.
Checking for Issues at Code Generation Time

You can use codegen to check for issues at code generation time. codegen checks that
your MATLAB code is suitable for code generation.

When codegen detects errors or warnings, it automatically generates an error report


that describes the issues and provides links to the offending MATLAB code. For more
information, see “Code Generation Reports”.

After code generation, codegen generates a MEX function that you can use to test your
implementation in MATLAB.
Checking for Issues at Run Time

You can use codegen to generate a MEX function and check for issues at run time. In
simulation, the code generated for your MATLAB functions includes the run-time checks.
Disabling run-time checks and extrinsic calls usually results in streamlined generated
code and faster simulation. You control run-time checks using the MEX configuration
object, coder.MexCodeConfig. For more information, see “Control Run-Time Checks”.

If you encounter run-time errors in your MATLAB functions, a run-time stack appears
automatically in the MATLAB Command Window. See “Debug Run-Time Errors”.
Where to Go Next

The next section of the tutorial, “Making Your Code Suitable for Code Generation” on
page 2-67, shows you how to use the MATLAB code analyzer and codegen to make
your code suitable for code generation.

Making the MATLAB Code Suitable for Code Generation


Making Your Code Suitable for Code Generation

To begin the process of making your MATLAB code suitable for code generation,
you work with the euclidean01.m file. This file is a MATLAB version of a three-

2-67
2 Tutorials

dimensional Euclidean example that plots the distances between an input vector x and
each of the vectors in the codebook matrix cb. It determines which vector in cb is closest
to x, and outputs this vector, its position in cb, and the distance to y.

1 In your work folder, open euclidean01.m in the MATLAB Editor.


edit euclidean01.m

The file opens. The code analyzer message indicator in the top right corner of the
MATLAB Editor is green, which indicates that the code analyzer has not detected
errors, warnings, or opportunities for improvement in the code.
2 Turn on code generation error checking by adding the %#codegen compilation
directive after the function declaration.
function [ y, idx, distance ] = ...
euclidean01( x, cb ) %#codegen
The code analyzer message indicator remains green, indicating that it has not
detected code generation issues.

For more information on using the code analyzer, see “Running the Code Analyzer
Report”.
3 Change the function name to euclidean02 and save the file as euclidean02.m in
the current folder.

You are now ready to compile your code using codegen, which checks that your code
is suitable for code generation. After code generation, codegen generates a MEX
function that you can test in MATLAB.

Generating a MEX Function Using codegen


About codegen

You generate MEX functions using codegen, a function that compiles MATLAB code
to a MEX function. codegen also checks that your MATLAB code is suitable for code
generation.
Using codegen

Because C uses static typing, codegen must determine the properties of all variables
in the MATLAB files at compile time. Therefore, you must specify the properties of
all function inputs at the same time as you compile the file with codegen. To compile
euclidean02.m, you must specify the size of the input vector x and the codebook matrix
cb.

2-68
MEX Function Generation at the Command Line

1 Compile the euclidean02.m file.

codegen -report euclidean02.m -args {x(:,1), cb}

• By default, codegen generates a MEX function named euclidean02_mex in the


current folder. You can compare the results of running the MEX function with the
results of running the original MATLAB code.
• The -args option instructs codegen to compile the file euclidean02.m by using
the sample input parameters x(:,1) and cb.
• The -report option instructs codegen to produce a code generation report.
2 At the MATLAB command prompt, click the link to the code generation report. View
the MATLAB code for the plot_distances function.

MATLAB Coder treats common MATLAB visualization functions as extrinsic. It does


not generate code for these functions. Instead, for a MEX function, it generates code
to run the function in MATLAB. These functions include line, grid, clf, axis, and
pause. The report highlights extrinsic functions. If a function is not supported for code
generation, and is not treated as extrinsic, you must explicitly declare that the function is
extrinsic by using coder.extrinsic. See “Call MATLAB Functions”.

You are ready to begin the next task in this tutorial, “Validating the MEX Function” on
page 2-69.

Validating the MEX Function

Test the MEX function that you generated in “Generating a MEX Function Using
codegen” on page 2-68 to verify that it provides the same functionality as the original

2-69
2 Tutorials

MATLAB code. You run the MEX function with the same inputs that you used in
“Running the Original MATLAB Code” on page 2-63.
Running the Generated MEX Function

1 Create a single input vector x1 from the matrix x.


x1=x(:,1)

The result is the first vector in x:


x1 =
0.8568
0.7455
0.3835
2 Use the MEX function euclidean02_mex to find the vector in codebook matrix cb
that is closest to x1.
[y, idx, distance] = euclidean02_mex(x1,cb)

The MEX function runs and plots the lines from x1 to each vector in cb. After
completing the algorithm, it outputs the coordinates of the point y, which is the
vector in cb closest to x1, together with the index idx of y in cb, and the distance,
distance, between y and x1.
y =
0.8000
0.8000
0.4000

idx =
171

distance =
0.0804

The plots and outputs are identical to those generated with the original MATLAB
function. The MEX function euclidean02_mex is functionally equivalent to the
original MATLAB code in euclidean01.m.

Using Build and Test Scripts

In “Check for Run-Time Issues” on page 2-16, you generated a MEX function for your
MATLAB code by calling codegen from the MATLAB command line. In this part of the

2-70
MEX Function Generation at the Command Line

tutorial, you use a build script to generate your MEX function and a test script to test it.
The first step is to modify the code in euclidean02.m to move the plotting function to a
separate test script.

Why Use Build Scripts?

A build script automates a series of MATLAB commands that you want to perform
repeatedly from the command line, saving you time and eliminating input errors.

Why Use Test Scripts?

The euclidean02.m file contains both the Euclidean minimum distance algorithm and
the plot function. It is good practice to separate your core algorithm from your test bench.
This practice allows you to reuse your algorithm easily. Create a separate test script to
do the pre- and post-processing such as loading inputs, setting up input values, calling
the function under test, and outputting test results.
Modifying the Code to Remove the Plot Function

In the file euclidean02.m:

1 Delete the call to plot_distances.


2 Delete the local function plot_distances.
3 Change the function name to euclidean03 and save the file as euclidean03.m in
the current folder.
Using the Build Script build01.m

Next you use the build script build01.m that compiles euclidean03.m using codegen.
Use the -report option, which instructs codegen to generate a code generation report
that you can use to debug your MATLAB code and verify that it is suitable for code
generation.

Contents of Build File build01.m


% Load the test data
load euclidean.mat
% Compile euclidean03.m with codegen
codegen -report euclidean03.m -args {x(:,1), cb}

At the MATLAB command prompt, enter:


build01
codegen runs and generates a MEX function euclidean03_mex in the current folder.

2-71
2 Tutorials

You are ready to test the MEX function euclidean03_mex.


Using the Test Script test01.m

You use the test script test01.m to test the MEX function euclidean03_mex.

The test script:

• Loads the test data from the file euclidean.mat.


• Runs the original MATLAB file euclidean03.m and plots the distances.
• Runs the MEX function euclidean03_mex and plots the distances.

Contents of Test Script test01.m


% Load test data
load euclidean.mat
% Take a single input vector from the matrix x
x1=x(:,1);
% Run the original MATLAB function
disp('Running MATLAB function euclidean03');
[y, idx, distance] = euclidean03(x1,cb);
disp(['y = ', num2str(y')]);
disp(['idx = ', num2str(idx)]);
disp(['distance = ', num2str(distance)]);
% Visualize the distance minimization
% plot_distances
clf;
for index=1:size(cb,2)
line([x(1,1) cb(1,index)], [x(2,1) cb(2,index)], ...
[x(3,1) cb(3,index)]);
end
axis([0 1 0 1 0 1]);grid;
pause(.5);
% Run the MEX function euclidean03_mex
disp('Running MEX function euclidean03_mex');
[y, idx, distance] = euclidean03_mex(x1,cb);
disp(['y = ', num2str(y')]);
disp(['idx = ', num2str(idx)]);
disp(['distance = ', num2str(distance)]);
% Visualize the distance minimization
% plot_distances
clf;
for index=1:size(cb,2)
line([x(1,1) cb(1,index)], [x(2,1) cb(2,index)], ...
[x(3,1) cb(3,index)]);

2-72
MEX Function Generation at the Command Line

end
axis([0 1 0 1 0 1]);grid;
pause(.5);
Running the Test Script

At the MATLAB command prompt, enter:


test01

The test file runs, plots the lines from x1 to each vector in cb, and outputs:
Running MATLAB function euclidean03
y = 0.8 0.8 0.4
idx = 171
distance = 0.080374
Running MEX function euclidean03_mex
y = 0.8 0.8 0.4
idx = 171
distance = 0.080374
The outputs for the original MATLAB code and the MEX function are identical.

You are now ready to begin the next task in this tutorial, “Modifying the Algorithm to
Accept Variable-Size Inputs” on page 2-73.

Modifying the Algorithm to Accept Variable-Size Inputs


Why Modify the Algorithm?

The algorithm you have used so far in this tutorial is suitable only to process inputs
whose dimensions match the dimensions of the example inputs provided using the -
args option. In this part of the tutorial, you run euclidean03_mex to see that it does
not accept two-dimensional inputs. You then recompile your code using two-dimensional
example inputs and test the resulting MEX function with the two-dimensional inputs.
About the Build and Test Scripts

Contents of test02.m
This test script creates two-dimensional inputs x2 and cb2, then calls
euclidean03_mex using these input parameters. You run this test script to see that
your existing algorithm does not accept two-dimensional inputs.
% Load the test data
load euclidean.mat

% Create 2-D versions of x and cb

2-73
2 Tutorials

x2=x(1:2,:);
x2d=x2(:,47);
cb2d=cb(1:2,1:6:216);

% Run euclidean03_mex with these 2-D inputs


disp('Attempting to run euclidean03_mex with 2-D inputs');
[y, idx, distance] = euclidean03_mex(x2d,cb2d);

Contents of build02.m

This build file creates two-dimensional example inputs x2d and cb2d then uses these
inputs to compile euclidean03.m.
% Load the test data
load euclidean.mat
% Create 2-D versions of x and cb
x2=x(1:2,:);
x2d=x2(:,47);
cb2d=cb(1:2,1:6:216);
% Recompile euclidean03 with 2-D example inputs
% The -o option instructs codegen to name the MEX function euclidean03_2d
disp('Recompiling euclidean03.m with 2-D example inputs');
codegen -o euclidean03_2d -report euclidean03.m -args {x2d, cb2d};

Contents of test03.m

This test script runs the MEX function euclidean03_2d with two-dimensional inputs.
% Load input data
load euclidean.mat
% Create 2-D versions of x and cb
x2=x(1:2,:);
x2d=x2(:,47);
cb2d=cb(1:2,1:6:216);
% Run new 2-D version of euclidean03
disp('Running new 2-D version of MEX function');
[y, idx, distance] = euclidean03_2d(x2d, cb2d);
disp(['y = ', num2str(y')]);
disp(['idx = ', num2str(idx)]);
disp(['distance = ', num2str(distance)]);
Running the Build and Test Scripts

1 Run the test script test02.m to test euclidean03x with two-dimensional inputs.
test02

2-74
MEX Function Generation at the Command Line

MATLAB reports an error indicating that the MEX function does not accept two-
dimensional variables for the input cb.

MATLAB expression 'x' is not of the correct size:


expected [3x1] found [2x1].

Error in ==> euclidean03

To process two-dimensional inputs, you must recompile your code providing two-
dimensional example inputs.
2 Run the build file build02.m to recompile euclidean03.m with two-dimensional
inputs.

build02
codegen compiles the file and generates a MEX function euclidean03_2d in the
current folder.
3 Run the test file test03.m to run the resulting MEX function euclidean03_2d
with two-dimensional inputs.

At the MATLAB command prompt, enter:

test03
This time, the MEX function runs and outputs the vector y in matrix cb that is
closest to x2d in two dimensions.

Running new 2-D version of MEX function


y = 0 0.4
idx = 3
distance = 0.053094

This part of the tutorial demonstrates how to create MEX functions to handle inputs with
different dimensions. Using this approach, you would need a library of MEX functions,
each one suitable only for inputs with specified data types, dimensions, and complexity.
Alternatively, you can modify your code to accept variable-size inputs. To learn how, see
“Specifying Variable-Size Inputs” on page 2-75.

Specifying Variable-Size Inputs

The original MATLAB function is suitable for many different size inputs. To provide this
same flexibility in your generated C code, use coder.typeof with the codegen -args
command-line option.

2-75
2 Tutorials

coder.typeof(a,b,1) specifies a variable-size input with the same class and


complexity as a and same size and upper bounds as the size vector b. For more
information, see “Specify Variable-Size Inputs at the Command Line”.

1 Compile this code using the build file build03.m. This build file uses
coder.typeof to specify variable-size inputs to the euclidean03 function.

build03

codegen compiles the file without warnings or errors and generates a MEX function
euclidean03_varsizex in the current folder.
2 Run the resulting MEX function with two-dimensional and then three-dimensional
inputs using the test file test04.m.

At the MATLAB command prompt, enter:

test04

The test file runs and outputs:

Running euclidean03_varsizex with 2-D inputs


y = 0 0.4
idx = 3
distance = 0.053094
Running euclidean04_varsizex with 3-D inputs
y = 0.6 0.8 0.2
idx = 134
distance = 0.053631
You have created an algorithm that accepts variable-size inputs.

Specifying Upper Bounds for Local Variables

In this part of the tutorial, you modify the algorithm to compute only the distance
between the first N elements of a given vector x and the first N elements of every column
vector in the matrix cb.

To modify the Euclidean minimum distance algorithm, euclidean03.m, to accommodate


changes in dimensions over which to compute the distances:

1 Provide a new input parameter, N, to specify the number of elements to consider. The
new function signature is:

function [y,idx,distance] = euclidean03(x,cb,N)

2-76
MEX Function Generation at the Command Line

2 Specify an upper bound for the variable N using assert. Add this line after the
function declaration.

assert(N<=3);

The value of the upper bound must correspond to the maximum number of
dimensions of matrix cb. If you do not specify an upper bound, an array bounds error
occurs if you run the MEX function with a value for N that exceeds the number of
dimensions of matrix cb. For more information, see “Specifying Upper Bounds for
Variable-Size Data”.
3 Modify the line of code that calculates the initial distance to use N. Replace the line:

distance=norm(x-cb(:,1));
with:

distance=norm(x(1:N)-cb(1:N,1));
4 Modify the line of code that calculates each successive distance to use N. Replace the
line:

d=norm(x-cb(:,index));
with:

d=norm(x(1:N)-cb(1:N,index));
5 Change the function name to euclidean04 and save the file as euclidean04.m in
the current folder.
6 Compile this code using the build file build04.m.

At the MATLAB command prompt, enter:

build04

codegen compiles the file without warnings or errors and generates a MEX function
euclidean04x in the current folder.
7 Run the resulting MEX function to process the first two elements of the inputs x and
cb , then to process all three elements of these inputs. Use the test file test05.m.

At the MATLAB command prompt, enter:

test05

The test file runs and outputs:


2-77
2 Tutorials

Running euclidean04_mex for first two elements of inputs x and cb


y = 0.8 0.8 0
idx = 169
distance = 0.078672
Running eucidean04_mex for three elements of inputs x and cb
y = 0.8 0.8 0.4
idx = 171
distance = 0.080374

Key Points to Remember


• Back up your MATLAB code before you modify it.
• Decide on a naming convention for your files and save interim versions frequently.
For example, this tutorial uses a two-digit suffix to differentiate the various versions
of the filter algorithm.
• Use build scripts to build your files.
• Use test scripts to separate the pre- and post-processing from the core algorithm.
• Use the -args option to specify input parameters at the command line.
• Use the MATLAB assert function to specify the upper bounds of variable-size data.
• Use the -report option to create a code generation report.
• Use coder.typeof(a,b,1) to specify variable-size inputs.

Best Practices Used in This Tutorial


Best Practice — Preserving Your Code

Preserve your code before making further modifications. This practice provides a fallback
in case of error and a baseline for testing and validation. Use a consistent file naming
convention. For example, add a 2-digit suffix to the file name for each file in a sequence.

Best Practice — Generating a Code Generation Report

Use the -report option to generate an HTML report with links to your MATLAB code
files and compile-time type information for the variables and expressions in your code.
This information simplifies finding sources of error messages and aids understanding of
type propagation rules. If you do not specify this option, codegen generates a report only
if errors or warnings occur. For more information, see “-report Generate Code Generation
Report” on page 3-2.

2-78
MEX Function Generation at the Command Line

Where to Learn More


• “Next Steps” on page 2-79
• “Product Help” on page 2-79
• “MathWorks Online” on page 2-79

Next Steps

To... See...
Learn how to generate C code from your “C Code Generation at the Command Line” on
MATLAB code page 2-31
Learn how to integrate your MATLAB code with “Track Object Using MATLAB Code”
Simulink models
Learn more about using code generation from “MATLAB Programming for Code Generation”
MATLAB
Use variable-size data “Variable-Size Data Definition for Code
Generation”
Speed up fixed-point MATLAB code fiaccel
Integrate custom C code into MATLAB code and “External Code Integration”
generate embeddable code
Integrate custom C code into a MATLAB coder.ceval
function
Generate HDL from MATLAB code www.mathworks.com/products/slhdlcoder

Product Help

MathWorks product documentation is available online from the Help menu on the
MATLAB desktop.

MathWorks Online

For additional information and support, visit the MATLAB Coder page on the
MathWorks website at:

www.mathworks.com/products/featured/matlab-coder

2-79
3

Best Practices for Working with


MATLAB Coder

• “Recommended Compilation Options for codegen” on page 3-2


• “Testing MEX Functions in MATLAB” on page 3-3
• “Comparing C Code and MATLAB Code Using Tiling in the MATLAB Editor” on page
3-4
• “Using Build Scripts” on page 3-5
• “Check Code Using the MATLAB Code Analyzer” on page 3-6
• “Separating Your Test Bench from Your Function Code” on page 3-7
• “Preserving Your Code” on page 3-8
• “File Naming Conventions” on page 3-9
3 Best Practices for Working with MATLAB Coder

Recommended Compilation Options for codegen


In this section...
“-c Generate Code Only” on page 3-2
“-report Generate Code Generation Report” on page 3-2

-c Generate Code Only


Use the -c option to generate code only without invoking the make command. If this
option is used, codegen does not generate compiled object code. This option saves you
time during the development cycle when you want to iterate rapidly between modifying
MATLAB code and generating C code and are mainly interested in inspecting the C code.

For more information and a complete list of compilation options, see codegen.

-report Generate Code Generation Report


Use the -report option to generate a code generation report in HTML format at
compile time to help you debug your MATLAB code and verify that it is suitable for code
generation. If the -report option is not specified, codegen generates a report only if
compilation errors or warnings occur.

The code generation report contains the following information:

• Summary of compilation results, including type of target and number of warnings or


errors
• Target build log that records compilation and linking activities
• Links to generated files
• Error and warning messages

For more information, see codegen.

3-2
Testing MEX Functions in MATLAB

Testing MEX Functions in MATLAB


To prepare your MATLAB code before you generate C code, use codegen to convert your
MATLAB code to a MEX function. codegen generates a platform-specific MEX-file,
which you can execute within the MATLAB environment to test your algorithm.

For more information, see codegen.

3-3
3 Best Practices for Working with MATLAB Coder

Comparing C Code and MATLAB Code Using Tiling in the MATLAB


Editor
Use the MATLAB Editor's left/right tile feature to compare your generated C code to the
original MATLAB code. You can easily compare the generated C code to your original
MATLAB code. In the generated C code:

• Your function name is unchanged.


• Your comments are preserved in the same position.

To compare two files, follow these steps:

1 Open the C file and the MATLAB file in the Editor. (Dock both windows if they are
not docked.)
2
Select Window > Left/Right Tile (or the toolbar button) to view the files side
by side.

The MATLAB file kalman02.m and its generated C code kalman02.c are displayed in
the following figure.

3-4
Using Build Scripts

Using Build Scripts


If you use codegen to generate code from the command line, use build scripts to call
codegen to generate MEX functions from your MATLAB function.

A build script automates a series of MATLAB commands that you want to perform
repeatedly from the command line, saving you time and eliminating input errors. For
instance, you can use a build script to clear your workspace before each build and to
specify code generation options.

Here is an example of a build script to run codegen to process lms_02.m:


close all;
clear all;
clc;

N = 73113;

codegen -report lms_02.m ...


-args { zeros(N,1) zeros(N,1) }
where:

• close all deletes figures whose handles are not hidden. See close in the MATLAB
Graphics function reference for more information.
• clear all removes variables, functions, and MEX-files from memory, leaving the
workspace empty. It also clears breakpoints.

Note: Remove the clear all command from the build scripts if you want to preserve
breakpoints for debugging.
• clc clears all input and output from the Command Window display, giving you a
“clean screen.”
• N = 73113 sets the value of the variable N, which represents the number of samples
in each of the two input parameters for the function lms_02
• codegen -report lms_02.m -args { zeros(N,1) zeros(N,1) } calls
codegen to generate C code for file lms_02.m using the following options:

• -report generates a code generation report


• -args { zeros(N,1) zeros(N,1) } specifies the properties of the function
inputs as a cell array of example values. In this case, the input parameters are N-
by-1 vectors of real doubles.

3-5
3 Best Practices for Working with MATLAB Coder

Check Code Using the MATLAB Code Analyzer


The code analyzer checks your code for problems and recommends modifications. You can
use the code analyzer to check your code interactively in the MATLAB Editor while you
work.

To verify that continuous code checking is enabled:

1 In MATLAB, select the Home tab and then click Preferences.


2 In the Preferences dialog box, select Code Analyzer.
3 In the Code Analyzer Preferences pane, verify that Enable integrated warning
and error messages is selected.

3-6
Separating Your Test Bench from Your Function Code

Separating Your Test Bench from Your Function Code


If you use codegen to generate code from the command line, separate your core
algorithm from your test bench. Create a separate test script to do the pre- and post-
processing such as loading inputs, setting up input values, calling the function under
test, and outputting test results.

3-7
3 Best Practices for Working with MATLAB Coder

Preserving Your Code


Preserve your code before making further modifications. This practice provides a fallback
in case of error and a baseline for testing and validation. Use a consistent file naming
convention. For example, add a 2-digit suffix to the file name for each file in a sequence.
See “File Naming Conventions” on page 3-9 for more details.

3-8
File Naming Conventions

File Naming Conventions


Use a consistent file naming convention to identify different types and versions of your
MATLAB files. This approach keeps your files organized and minimizes the risk of
overwriting existing files or creating two files with the same name in different folders.

For example, the file naming convention in the Generating MEX Functions getting
started tutorial is:

• The suffix _build identifies a build script.


• The suffix _test identifies a test script.
• A numerical suffix, for example, _01 identifies the version of a file. These numbers
are typically two-digit sequential integers, beginning with 01, 02, 03, and so on.

For example:

• The file build_01.m is the first version of the build script for this tutorial.
• The file test_03.m is the third version of the test script for this tutorial.

3-9
MATLAB® Coder™
User's Guide

R2016a
How to Contact MathWorks

Latest news: www.mathworks.com

Sales and services: www.mathworks.com/sales_and_services

User community: www.mathworks.com/matlabcentral

Technical support: www.mathworks.com/support/contact_us

Phone: 508-647-7000

The MathWorks, Inc.


3 Apple Hill Drive
Natick, MA 01760-2098

MATLAB® Coder™ User's Guide


© COPYRIGHT 2011–2016 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and
govern the use, modification, reproduction, release, performance, display, and disclosure of the Program
and Documentation by the federal government (or other entity acquiring for or through the federal
government) and shall supersede any conflicting contractual terms or conditions. If this License fails
to meet the government's needs or is inconsistent in any respect with federal procurement law, the
government agrees to return the Program and Documentation, unused, to The MathWorks, Inc.
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
April 2011 Online only New for Version 2 (R2011a)
September 2011 Online only Revised for Version 2.1 (Release 2011b)
March 2012 Online only Revised for Version 2.2 (Release 2012a)
September 2012 Online only Revised for Version 2.3 (Release 2012b)
March 2013 Online only Revised for Version 2.4 (Release 2013a)
September 2013 Online only Revised for Version 2.5 (Release 2013b)
March 2014 Online only Revised for Version 2.6 (Release 2014a)
October 2014 Online only Revised for Version 2.7 (Release 2014b)
March 2015 Online only Revised for Version 2.8 (Release 2015a)
September 2015 Online only Revised for Version 3.0 (Release 2015b)
October 2015 Online only Rereleased for Version 2.8.1 (Release
2015aSP1)
March 2016 Online only Revised for Version 3.1 (Release 2016a)
Check Bug Reports for Issues and Fixes
Software is inherently complex and is not free of errors. The output of a code generator
might contain bugs, some of which are not detected by a compiler. MathWorks
reports critical known bugs brought to its attention on its Bug Report system at
www.mathworks.com/support/bugreports/. Use the Saved Searches and Watched Bugs
tool with the search phrase "Incorrect Code Generation" to obtain a report of known bugs
that produce code that might compile and execute, but still produce wrong answers.

The bug reports are an integral part of the documentation for each release. Examine
periodically all bug reports for a release, as such reports may identify inconsistencies
between the actual behavior of a release you are using and the behavior described in this
documentation.

In addition to reviewing bug reports, you should implement a verification and validation
strategy to identify potential bugs in your design, code, and tools.
Contents

About MATLAB Coder


1
MATLAB Coder Product Description . . . . . . . . . . . . . . . . . . . 1-2
Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2

Product Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3


When to Use MATLAB Coder . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Code Generation for Embedded Software Applications . . . . . 1-3
Code Generation for Fixed-Point Algorithms . . . . . . . . . . . . . 1-3

Code Generation Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5


See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5

Design Considerations for C/C++ Code Generation


2
When to Generate Code from MATLAB Algorithms . . . . . . . 2-2
When Not to Generate Code from MATLAB Algorithms . . . . 2-2

Which Code Generation Feature to Use . . . . . . . . . . . . . . . . . 2-4

Prerequisites for C/C++ Code Generation from MATLAB . . . 2-5

MATLAB Code Design Considerations for Code Generation 2-6


See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7

Differences in Behavior After Compiling MATLAB Code . . . 2-8


Why Are There Differences? . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Character Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Order of Evaluation in Expressions . . . . . . . . . . . . . . . . . . . . 2-8
Termination Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10

vii
Size of Variable-Size N-D Arrays . . . . . . . . . . . . . . . . . . . . 2-10
Size of Empty Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
Size of Empty Array That Results from Deleting Elements of an
Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
Floating-Point Numerical Results . . . . . . . . . . . . . . . . . . . . 2-11
NaN and Infinity Patterns . . . . . . . . . . . . . . . . . . . . . . . . . 2-12
Code Generation Target . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12
MATLAB Class Initial Values . . . . . . . . . . . . . . . . . . . . . . . 2-12
Variable-Size Support for Code Generation . . . . . . . . . . . . . 2-12
Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12

MATLAB Language Features Supported for C/C++ Code


Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13
MATLAB Features That Code Generation Supports . . . . . . 2-13
MATLAB Language Features That Code Generation Does Not
Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14

System Objects Supported for Code Generation


3
Code Generation for System Objects . . . . . . . . . . . . . . . . . . . 3-2

Functions, Classes, and System Objects Supported


for Code Generation
4
Functions and Objects Supported for C and C++ Code
Generation — Alphabetical List . . . . . . . . . . . . . . . . . . . . . . 4-2

Functions and Objects Supported for C and C++ Code


Generation — Category List . . . . . . . . . . . . . . . . . . . . . . . 4-175
Aerospace Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-177
Arithmetic Operations in MATLAB . . . . . . . . . . . . . . . . . . 4-177
Audio System Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-178
Bit-Wise Operations MATLAB . . . . . . . . . . . . . . . . . . . . . 4-180
Casting in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-180
Communications System Toolbox . . . . . . . . . . . . . . . . . . . 4-181

viii Contents
Complex Numbers in MATLAB . . . . . . . . . . . . . . . . . . . . . 4-187
Computer Vision System Toolbox . . . . . . . . . . . . . . . . . . . 4-187
Control Flow in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . 4-197
Data and File Management in MATLAB . . . . . . . . . . . . . . 4-197
Data Types in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 4-201
Desktop Environment in MATLAB . . . . . . . . . . . . . . . . . . 4-202
Discrete Math in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . 4-203
DSP System Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-203
Error Handling in MATLAB . . . . . . . . . . . . . . . . . . . . . . . 4-211
Exponents in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-211
Filtering and Convolution in MATLAB . . . . . . . . . . . . . . . 4-212
Fixed-Point Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-213
HDL Coder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-223
Histograms in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 4-223
Image Acquisition Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . 4-224
Image Processing in MATLAB . . . . . . . . . . . . . . . . . . . . . . 4-224
Image Processing Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . 4-224
Input and Output Arguments in MATLAB . . . . . . . . . . . . 4-240
Interpolation and Computational Geometry in MATLAB . . 4-241
Linear Algebra in MATLAB . . . . . . . . . . . . . . . . . . . . . . . 4-245
Logical and Bit-Wise Operations in MATLAB . . . . . . . . . . 4-246
MATLAB Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-247
Matrices and Arrays in MATLAB . . . . . . . . . . . . . . . . . . . 4-247
Neural Network Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . 4-256
Numerical Integration and Differentiation in MATLAB . . . 4-256
Optimization Functions in MATLAB . . . . . . . . . . . . . . . . . 4-257
Phased Array System Toolbox . . . . . . . . . . . . . . . . . . . . . . 4-258
Polynomials in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 4-267
Programming Utilities in MATLAB . . . . . . . . . . . . . . . . . . 4-267
Relational Operators in MATLAB . . . . . . . . . . . . . . . . . . . 4-268
Robotics System Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . 4-268
Rounding and Remainder Functions in MATLAB . . . . . . . 4-269
Set Operations in MATLAB . . . . . . . . . . . . . . . . . . . . . . . 4-270
Signal Processing in MATLAB . . . . . . . . . . . . . . . . . . . . . 4-274
Signal Processing Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . 4-275
Special Values in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . 4-280
Specialized Math in MATLAB . . . . . . . . . . . . . . . . . . . . . . 4-281
Statistics in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-281
Statistics and Machine Learning Toolbox . . . . . . . . . . . . . 4-282
String Functions in MATLAB . . . . . . . . . . . . . . . . . . . . . . 4-292
System Identification Toolbox . . . . . . . . . . . . . . . . . . . . . . 4-294
Trigonometry in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . 4-296
WLAN System Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-298

ix
Defining MATLAB Variables for C/C++ Code
Generation
5
Variables Definition for Code Generation . . . . . . . . . . . . . . . 5-2

Best Practices for Defining Variables for C/C++ Code


Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
Define Variables By Assignment Before Using Them . . . . . . 5-3
Use Caution When Reassigning Variables . . . . . . . . . . . . . . . 5-5
Use Type Cast Operators in Variable Definitions . . . . . . . . . 5-5
Define Matrices Before Assigning Indexed Variables . . . . . . . 5-6

Eliminate Redundant Copies of Variables in Generated


Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7
When Redundant Copies Occur . . . . . . . . . . . . . . . . . . . . . . . 5-7
How to Eliminate Redundant Copies by Defining Uninitialized
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7
Defining Uninitialized Variables . . . . . . . . . . . . . . . . . . . . . . 5-8

Reassignment of Variable Properties . . . . . . . . . . . . . . . . . . . 5-9

Define and Initialize Persistent Variables . . . . . . . . . . . . . . 5-10

Reuse the Same Variable with Different Properties . . . . . . 5-11


When You Can Reuse the Same Variable with Different
Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11
When You Cannot Reuse Variables . . . . . . . . . . . . . . . . . . . 5-11
Limitations of Variable Reuse . . . . . . . . . . . . . . . . . . . . . . . 5-14

Avoid Overflows in for-Loops . . . . . . . . . . . . . . . . . . . . . . . . . 5-15

Supported Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-17

Defining Data for Code Generation


6
Data Definition for Code Generation . . . . . . . . . . . . . . . . . . . 6-2

x Contents
Code Generation for Complex Data . . . . . . . . . . . . . . . . . . . . 6-4
Restrictions When Defining Complex Variables . . . . . . . . . . . 6-4
Code Generation for Complex Data with Zero-Valued Imaginary
Parts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4
Results of Expressions That Have Complex Operands . . . . . . 6-8

Code Generation for Characters and Strings . . . . . . . . . . . . 6-9

Array Size Restrictions for Code Generation . . . . . . . . . . . . 6-10


See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-10

Code Generation for Constants in Structures and Arrays . 6-11

Code Generation for Variable-Size Data


7
What Is Variable-Size Data? . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2

Variable-Size Data Definition for Code Generation . . . . . . . 7-3

Bounded Versus Unbounded Variable-Size Data . . . . . . . . . . 7-4

Control Memory Allocation of Variable-Size Data . . . . . . . . . 7-5

Specify Variable-Size Data Without Dynamic Memory


Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6
Fixing Upper Bounds Errors . . . . . . . . . . . . . . . . . . . . . . . . . 7-6
Specifying Upper Bounds for Variable-Size Data . . . . . . . . . . 7-6

Variable-Size Data in Code Generation Reports . . . . . . . . . . 7-9


What Reports Tell You About Size . . . . . . . . . . . . . . . . . . . . 7-9
How Size Appears in Code Generation Reports . . . . . . . . . . 7-10
How to Generate a Code Generation Report . . . . . . . . . . . . 7-10

Define Variable-Size Data for Code Generation . . . . . . . . . 7-11


When to Define Variable-Size Data Explicitly . . . . . . . . . . . 7-11
Using a Matrix Constructor with Nonconstant Dimensions . 7-11
Inferring Variable Size from Multiple Assignments . . . . . . . 7-12
Defining Variable-Size Data Explicitly Using coder.varsize . 7-13

xi
C Code Interface for Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 7-17
C Code Interface for Statically Allocated Arrays . . . . . . . . . 7-17
C Code Interface for Dynamically Allocated Arrays . . . . . . . 7-18
Utility Functions for Creating emxArray Data Structures . . 7-20

Diagnose and Fix Variable-Size Data Errors . . . . . . . . . . . . 7-22


Diagnosing and Fixing Size Mismatch Errors . . . . . . . . . . . 7-22
Diagnosing and Fixing Errors in Detecting Upper Bounds . . 7-24

Incompatibilities with MATLAB in Variable-Size Support for


Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-26
Incompatibility with MATLAB for Scalar Expansion . . . . . . 7-26
Incompatibility with MATLAB in Determining Size of Variable-
Size N-D Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-28
Incompatibility with MATLAB in Determining Size of Empty
Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-29
Incompatibility with MATLAB in Determining Class of Empty
Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-30
Incompatibility with MATLAB in Vector-Vector Indexing . . 7-31
Incompatibility with MATLAB in Matrix Indexing Operations
for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-32
Incompatibility with MATLAB in Concatenating Variable-Size
Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-33
Differences When Curly-Brace Indexing of Variable-Size Cell
Array Inside Concatenation Returns No Elements . . . . . . 7-33
Dynamic Memory Allocation Not Supported for MATLAB
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-34

Variable-Sizing Restrictions for Code Generation of Toolbox


Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-35
Common Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-35
Toolbox Functions with Restrictions For Variable-Size Data 7-36

Code Generation for MATLAB Structures


8
Structure Definition for Code Generation . . . . . . . . . . . . . . . 8-2

Structure Operations Allowed for Code Generation . . . . . . . 8-3

xii Contents
Define Scalar Structures for Code Generation . . . . . . . . . . . 8-4
Restrictions When Defining Scalar Structures by
Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4
Adding Fields in Consistent Order on Each Control Flow
Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4
Restriction on Adding New Fields After First Use . . . . . . . . . 8-5

Define Arrays of Structures for Code Generation . . . . . . . . . 8-6


Ensuring Consistency of Fields . . . . . . . . . . . . . . . . . . . . . . . 8-6
Using repmat to Define an Array of Structures with Consistent
Field Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-6
Defining an Array of Structures by Using struct . . . . . . . . . . 8-7
Defining an Array of Structures Using Concatenation . . . . . . 8-7

Make Structures Persistent . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-8

Index Substructures and Fields . . . . . . . . . . . . . . . . . . . . . . . 8-9

Assign Values to Structures and Fields . . . . . . . . . . . . . . . . 8-11

Pass Structure Arguments by Reference or by Value . . . . . 8-13

Code Generation for Cell Arrays


9
Homogeneous vs. Heterogeneous Cell Arrays . . . . . . . . . . . . 9-2

Control Whether a Cell Array is Homogeneous or


Heterogeneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4

Define Cell Array Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-5

Make a Cell Array Variable-Size . . . . . . . . . . . . . . . . . . . . . . . 9-6

Name the Structure Type That Represents a Cell Array . . . 9-8

Cell Array Requirements and Limitations for Code


Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-10
Cell Array Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-10
Cell Array Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-11

xiii
Growing a Cell Array by Using {end + 1} . . . . . . . . . . . . . . 9-11
Variable-Size Cell Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 9-12
Cell Array Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-13
Cell Arrays in Structures . . . . . . . . . . . . . . . . . . . . . . . . . . 9-13
Passing to External C/C++ Functions . . . . . . . . . . . . . . . . . 9-13

Cell Arrays in Code Generation Reports . . . . . . . . . . . . . . . 9-14


Cell Array Variable in the MATLAB Code Pane . . . . . . . . . 9-14
Cell Array Variable on the Variables Tab . . . . . . . . . . . . . . 9-14

Code Generation for Enumerated Data


10
Enumerated Data Definition for Code Generation . . . . . . . 10-2

Enumerated Types Supported for Code Generation . . . . . . 10-3


Enumeration Class Base Types for Code Generation . . . . . . 10-3
C Code Representation for Base Type int32 . . . . . . . . . . . . 10-4
C Code Representation for Base Type Other Than int32 . . 10-4

When to Use Enumerated Data for Code Generation . . . . . 10-6

Generate Code for Enumerated Data from MATLAB


Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-7
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-7

Define Enumerated Data for Code Generation . . . . . . . . . . 10-8


Naming Enumerated Types for Code Generation . . . . . . . . . 10-9

Operations on Enumerated Data for Code Generation . . . 10-10


Assignment Operator, = . . . . . . . . . . . . . . . . . . . . . . . . . . 10-10
Relational Operators, < > <= >= == ~= . . . . . . . . . . . . . . . 10-10
Cast Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-10
Indexing Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-11
Control Flow Statements: if, switch, while . . . . . . . . . . . . 10-11

Include Enumerated Data in Control Flow Statements . . 10-13


if Statement with Enumerated Data Types . . . . . . . . . . . 10-13
switch Statement with Enumerated Data Types . . . . . . . 10-14
while Statement with Enumerated Data Types . . . . . . . . 10-16

xiv Contents
Customize Enumerated Types for Code Generation . . . . . 10-19
Customizing Enumerated Types . . . . . . . . . . . . . . . . . . . . 10-19
Specify a Default Enumerated Value . . . . . . . . . . . . . . . . . 10-20
Specify a Header File . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-21

Use Enumerated Types in LED Control Function . . . . . . . 10-23

Control Names of Enumerated Type Values in Generated


Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-27

Change and Reload Enumerated Data Types . . . . . . . . . . . 10-30

Restrictions on Use of Enumerated Data in for-Loops . . . 10-31

Toolbox Functions That Support Enumerated Types for Code


Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-32

Code Generation for MATLAB Classes


11
MATLAB Classes Definition for Code Generation . . . . . . . . 11-2
Language Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2
Code Generation Features Not Compatible with Classes . . . 11-3
Defining Class Properties for Code Generation . . . . . . . . . . 11-4
Calls to Base Class Constructor . . . . . . . . . . . . . . . . . . . . . 11-5
Inheritance from Built-In MATLAB Classes Not Supported . 11-7

Classes That Support Code Generation . . . . . . . . . . . . . . . . 11-8

Generate Code for MATLAB Value Classes . . . . . . . . . . . . . 11-9

Generate Code for MATLAB Handle Classes and System


Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-14

MATLAB Classes in Code Generation Reports . . . . . . . . . . 11-17


What Reports Tell You About Classes . . . . . . . . . . . . . . . . 11-17
How Classes Appear in Code Generation Reports . . . . . . . 11-17

Troubleshooting Issues with MATLAB Classes . . . . . . . . . 11-20


Class class does not have a property with name name . . . . 11-20

xv
Handle Object Limitations for Code Generation . . . . . . . . 11-22
A Variable Outside a Loop Cannot Refer to a Handle Object
Created Inside a Loop . . . . . . . . . . . . . . . . . . . . . . . . . . 11-22
A Handle Object That a Persistent Variable Refers To Must Be
a Singleton Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-22

System Objects Requirements and Limitations for Code


Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-25

Code Generation for Function Handles


12
Function Handle Definition for Code Generation . . . . . . . . 12-2

Define and Pass Function Handles for Code Generation . . 12-3

Function Handle Limitations for Code Generation . . . . . . . 12-5

Defining Functions for Code Generation


13
Specify Variable Numbers of Arguments . . . . . . . . . . . . . . . 13-2

Supported Index Expressions . . . . . . . . . . . . . . . . . . . . . . . . 13-3

Apply Operations to a Variable Number of Arguments . . . . 13-4


When to Force Loop Unrolling . . . . . . . . . . . . . . . . . . . . . . 13-4
Using Variable Numbers of Arguments in a for-Loop . . . . . . 13-5

Implement Wrapper Functions . . . . . . . . . . . . . . . . . . . . . . . 13-6


Passing Variable Numbers of Arguments from One Function to
Another . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-6

Variable Length Argument Lists for Code Generation . . . . 13-7

xvi Contents
Calling Functions for Code Generation
14
Resolution of Function Calls for Code Generation . . . . . . . 14-2
Key Points About Resolving Function Calls . . . . . . . . . . . . . 14-4
Compile Path Search Order . . . . . . . . . . . . . . . . . . . . . . . . 14-4
When to Use the Code Generation Path . . . . . . . . . . . . . . . 14-5

Resolution of File Types on Code Generation Path . . . . . . . 14-6

Compilation Directive %#codegen . . . . . . . . . . . . . . . . . . . . . 14-8

Call Local Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-9

Call Supported Toolbox Functions . . . . . . . . . . . . . . . . . . . 14-10

Call MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-11


Declaring MATLAB Functions as Extrinsic Functions . . . . 14-12
Calling MATLAB Functions Using feval . . . . . . . . . . . . . . 14-16
Resolution of Extrinsic Functions During Simulation . . . . 14-16
Working with mxArrays . . . . . . . . . . . . . . . . . . . . . . . . . . 14-17
Restrictions on Extrinsic Functions for Code Generation . . 14-19
Limit on Function Arguments . . . . . . . . . . . . . . . . . . . . . . 14-19

Fixed-Point Conversion
15
Detect Dead and Constant-Folded Code . . . . . . . . . . . . . . . . 15-2
What Is Dead Code? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-2
Detect Dead Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-3
Fix Dead Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-5

Convert MATLAB Code to Fixed-Point C Code . . . . . . . . . . 15-7

Propose Fixed-Point Data Types Based on Simulation


Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-9

Propose Fixed-Point Data Types Based on Derived


Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-23

xvii
Specify Type Proposal Options . . . . . . . . . . . . . . . . . . . . . . 15-36

Detect Overflows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-40

Replace the exp Function with a Lookup Table . . . . . . . . 15-50

Replace a Custom Function with a Lookup Table . . . . . . . 15-59

Enable Plotting Using the Simulation Data Inspector . . . 15-68

Visualize Differences Between Floating-Point and Fixed-


Point Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-69

Log Data for Histogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-80

View and Modify Variable Information . . . . . . . . . . . . . . . 15-82


View Variable Information . . . . . . . . . . . . . . . . . . . . . . . . 15-82
Modify Variable Information . . . . . . . . . . . . . . . . . . . . . . . 15-82
Revert Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-84
Promote Sim Min and Sim Max Values . . . . . . . . . . . . . . . 15-85

Automated Fixed-Point Conversion . . . . . . . . . . . . . . . . . . 15-86


Automated Fixed-Point Conversion Capabilities . . . . . . . . 15-86
Code Coverage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-87
Proposing Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-91
Locking Proposed Data Types . . . . . . . . . . . . . . . . . . . . . . 15-93
Viewing Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-93
Viewing Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-100
Log Data for Histogram . . . . . . . . . . . . . . . . . . . . . . . . . . 15-102
Function Replacements . . . . . . . . . . . . . . . . . . . . . . . . . . 15-104
Validating Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-105
Testing Numerics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-105
Detecting Overflows . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-106

Convert Fixed-Point Conversion Project to MATLAB


Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-107

Generated Fixed-Point Code . . . . . . . . . . . . . . . . . . . . . . . 15-110


Location of Generated Fixed-Point Files . . . . . . . . . . . . . 15-110
Minimizing fi-casts to Improve Code Readability . . . . . . 15-111
Avoiding Overflows in the Generated Fixed-Point Code . . 15-111
Controlling Bit Growth . . . . . . . . . . . . . . . . . . . . . . . . . . 15-112
Avoiding Loss of Range or Precision . . . . . . . . . . . . . . . . 15-112

xviii Contents
Handling Non-Constant mpower Exponents . . . . . . . . . . 15-114

Fixed-Point Code for MATLAB Classes . . . . . . . . . . . . . . . 15-116


Automated Conversion Support for MATLAB Classes . . . 15-116
Unsupported Constructs . . . . . . . . . . . . . . . . . . . . . . . . . 15-116
Coding Style Best Practices . . . . . . . . . . . . . . . . . . . . . . . 15-117

Automated Fixed-Point Conversion Best Practices . . . . . 15-119


Create a Test File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-119
Prepare Your Algorithm for Code Acceleration or Code
Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-120
Check for Fixed-Point Support for Functions Used in Your
Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-121
Manage Data Types and Control Bit Growth . . . . . . . . . . 15-121
Convert to Fixed Point . . . . . . . . . . . . . . . . . . . . . . . . . . 15-122
Use the Histogram to Fine-Tune Data Type Settings . . . . 15-123
Optimize Your Algorithm . . . . . . . . . . . . . . . . . . . . . . . . 15-124
Avoid Explicit Double and Single Casts . . . . . . . . . . . . . . 15-126

Replacing Functions Using Lookup Table


Approximations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-127

MATLAB Language Features Supported for Automated


Fixed-Point Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . 15-128

Inspecting Data Using the Simulation Data Inspector . . 15-130


What Is the Simulation Data Inspector? . . . . . . . . . . . . . 15-130
Import Logged Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-130
Export Logged Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-130
Group Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-131
Run Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-131
Create Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-131
Comparison Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-131
Enabling Plotting Using the Simulation Data Inspector . . 15-131
Save and Load Simulation Data Inspector Sessions . . . . . 15-132

Custom Plot Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-133

Data Type Issues in Generated Code . . . . . . . . . . . . . . . . 15-135


Enable the Highlight Option in the MATLAB Coder App . 15-135
Enable the Highlight Option at the Command Line . . . . . 15-135
Stowaway Doubles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-135
Stowaway Singles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-136

xix
Expensive Fixed-Point Operations . . . . . . . . . . . . . . . . . . 15-136

Automated Fixed-Point Conversion Using


Programmatic Workflow
16
Convert MATLAB Code to Fixed-Point C Code . . . . . . . . . . 16-2

Propose Fixed-Point Data Types Based on Simulation


Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-5

Propose Fixed-Point Data Types Based on Derived


Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-11

Detect Overflows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-20

Replace the exp Function with a Lookup Table . . . . . . . . 16-24

Replace a Custom Function with a Lookup Table . . . . . . . 16-26

Enable Plotting Using the Simulation Data Inspector . . . 16-28

Visualize Differences Between Floating-Point and Fixed-


Point Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-29

Single-Precision Conversion
17
Generate Single-Precision C Code at the Command Line . . 17-2
Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2
Create a Folder and Copy Relevant Files . . . . . . . . . . . . . . 17-2
Determine the Type of the Input Argument . . . . . . . . . . . . 17-4
Generate and Run Single-Precision MEX to Verify Numerical
Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-5
Generate Single-Precision C Code . . . . . . . . . . . . . . . . . . . . 17-5
View the Generated Single-Precision C Code . . . . . . . . . . . . 17-6
View Potential Data Type Issues . . . . . . . . . . . . . . . . . . . . . 17-6

xx Contents
Generate Single-Precision C Code Using the MATLAB Coder
App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-8
Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-8
Create a Folder and Copy Relevant Files . . . . . . . . . . . . . . 17-8
Open the MATLAB Coder App . . . . . . . . . . . . . . . . . . . . . 17-10
Enable Single-Precision Conversion . . . . . . . . . . . . . . . . . . 17-11
Select the Source Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-11
Define Input Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-12
Check for Run-Time Issues . . . . . . . . . . . . . . . . . . . . . . . . 17-12
Generate Single-Precision C Code . . . . . . . . . . . . . . . . . . . 17-12
View the Generated C Code . . . . . . . . . . . . . . . . . . . . . . . 17-13
View Potential Data Type Issues . . . . . . . . . . . . . . . . . . . . 17-13

Generate Single-Precision MATLAB Code . . . . . . . . . . . . . 17-14


Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-14
Create a Folder and Copy Relevant Files . . . . . . . . . . . . . 17-14
Set Up the Single-Precision Configuration Object . . . . . . . 17-16
Generate Single-Precision MATLAB Code . . . . . . . . . . . . . 17-16
View the Type Proposal Report . . . . . . . . . . . . . . . . . . . . . 17-17
View Generated Single-Precision MATLAB Code . . . . . . . . 17-18
View Potential Data Type Issues . . . . . . . . . . . . . . . . . . . . 17-19
Compare the Double-Precision and Single-Precision
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-19
Optionally Generate Single-Precision C Code . . . . . . . . . . 17-21

Choose a Single-Precision Conversion Workflow . . . . . . . 17-23

Single-Precision Conversion Best Practices . . . . . . . . . . . . 17-24


Use Integers for Index Variables . . . . . . . . . . . . . . . . . . . . 17-24
Limit Use of assert Statements . . . . . . . . . . . . . . . . . . . . . 17-24
Initialize MATLAB Class Properties in Constructor . . . . . 17-24
Provide a Test File That Calls Your MATLAB Function . . 17-24
Prepare Your Code for Code Generation . . . . . . . . . . . . . . 17-25
Verify Double-Precision Code Before Single-Precision
Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-25
Best Practices for Generation of Single-Precision C/C++
Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-25
Best Practices for Generation of Single-Precision MATLAB
Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-26

Warnings from Conversion to Single-Precision C/C++


Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-28
Function Uses Double-Precision in the C89/C90 Standard . 17-28
Built-In Function Is Implemented in Double-Precision . . . 17-29

xxi
Built-In Function Returns Double-Precision . . . . . . . . . . . 17-30

Combining Integers and Double-Precision Numbers . . . . 17-32

MATLAB Language Features Supported for Single-Precision


Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-33
MATLAB Language Features Supported for Single-Precision
Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-33
MATLAB Language Features Not Supported for Single-
Precision Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-34

Setting Up a MATLAB Coder Project


18
Set Up a MATLAB Coder Project . . . . . . . . . . . . . . . . . . . . . . 18-2
Create a Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-2
Open an Existing Project . . . . . . . . . . . . . . . . . . . . . . . . . . 18-2

Specify Properties of Entry-Point Function Inputs Using the


App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-3
Why Specify Input Properties? . . . . . . . . . . . . . . . . . . . . . . 18-3
Specify an Input Definition Using the App . . . . . . . . . . . . . 18-3

Automatically Define Input Types Using the App . . . . . . . . 18-4

Define Input Parameters by Example Using the App . . . . . 18-5


Define an Input Parameter by Example . . . . . . . . . . . . . . . 18-5
Specify Input Parameters by Example . . . . . . . . . . . . . . . . 18-6
Specify a Structure Type Input Parameter by Example . . . . 18-7
Specify a Cell Array Type Input Parameter by Example . . . 18-7
Specify an Enumerated Type Input Parameter by Example . 18-9
Specify a Fixed-Point Input Parameter by Example . . . . . . 18-10

Define or Edit Input Parameter Type Using the App . . . . 18-12


Define or Edit an Input Parameter Type . . . . . . . . . . . . . . 18-12
Specify an Enumerated Type Input Parameter by Type . . . 18-13
Specify a Fixed-Point Input Parameter by Type . . . . . . . . 18-14
Specify a Structure Input Parameter . . . . . . . . . . . . . . . . . 18-14
Specify a Cell Array Input Parameter . . . . . . . . . . . . . . . . 18-18

xxii Contents
Define Constant Input Parameters Using the App . . . . . . 18-23

Define Inputs Programmatically in the MATLAB File . . . 18-24

Add Global Variables Using the App . . . . . . . . . . . . . . . . . . 18-25

Specify Global Variable Type and Initial Value Using the


App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-26
Why Specify a Type Definition for Global Variables? . . . . . 18-26
Specify a Global Variable Type . . . . . . . . . . . . . . . . . . . . . 18-26
Define a Global Variable by Example . . . . . . . . . . . . . . . . 18-26
Define or Edit Global Variable Type . . . . . . . . . . . . . . . . . 18-27
Define Global Variable Initial Value . . . . . . . . . . . . . . . . . 18-28
Define Global Variable Constant Value . . . . . . . . . . . . . . . 18-29
Remove Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 18-29

Undo and Redo Changes to Type Definitions in the App . 18-30

Changing Output Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-31


Project Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-31
Configuration Object Parameters . . . . . . . . . . . . . . . . . . . 18-32

Code Generation Readiness Screening in the MATLAB Coder


App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-34

Slow Operations in MATLAB Coder App . . . . . . . . . . . . . . 18-36

Unable to Open a MATLAB Coder Project . . . . . . . . . . . . . 18-37

Preparing MATLAB Code for C/C++ Code Generation


19
Workflow for Preparing MATLAB Code for Code
Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-2
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-3

Fixing Errors Detected at Design Time . . . . . . . . . . . . . . . . 19-4


See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-4

Using the Code Analyzer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-5

xxiii
Check Code With the Code Analyzer . . . . . . . . . . . . . . . . . . 19-6

Check Code Using the Code Generation Readiness Tool . . 19-8


Run Code Generation Readiness Tool at the Command Line 19-8
Run Code Generation Readiness Tool from the Current Folder
Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-8
Run the Code Generation Readiness Tool Using the MATLAB
Coder App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-8

Code Generation Readiness Tool . . . . . . . . . . . . . . . . . . . . . . 19-9


Information That the Code Generation Readiness Tool
Provides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-9
Summary Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-9
Code Structure Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-11

Unable to Determine Code Generation Readiness . . . . . . . 19-15

Generate MEX Functions Using the MATLAB Coder App . 19-16


Workflow for Generating MEX Functions Using the MATLAB
Coder App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-16
Generate a MEX Function Using the MATLAB Coder App 19-16
Configure Project Settings . . . . . . . . . . . . . . . . . . . . . . . . . 19-19
Build a MATLAB Coder Project . . . . . . . . . . . . . . . . . . . . 19-19
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-20

Generate MEX Functions at the Command Line . . . . . . . . 19-21


Command-line Workflow for Generating MEX Functions . . 19-21
Generate MEX Functions at the Command Line . . . . . . . . 19-21
Generating MEX Functions at the Command Line Using
codegen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-22
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-22

Fix Errors Detected at Code Generation Time . . . . . . . . . 19-23


See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-23

Design Considerations When Writing MATLAB Code for Code


Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-24
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-25

Running MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-26


Debugging MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . 19-26

Debugging Strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-27

xxiv Contents
Collect and View Line Execution Counts for Your MATLAB
Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-28

Testing MEX Functions in MATLAB


20
Why Test MEX Functions in MATLAB? . . . . . . . . . . . . . . . . . 20-2

Workflow for Testing MEX Functions in MATLAB . . . . . . . 20-3


See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-3

Running MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-5


Debugging MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . . 20-5

Check for Run-Time Issues by Using the App . . . . . . . . . . . 20-6

Verify MEX Functions in the MATLAB Coder App . . . . . . . 20-8

Verify MEX Functions at the Command Line . . . . . . . . . . . 20-9

Debug Run-Time Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-10


Viewing Errors in the Run-Time Stack . . . . . . . . . . . . . . . 20-10
Handling Run-Time Errors . . . . . . . . . . . . . . . . . . . . . . . . 20-12

Using MEX Functions That MATLAB Coder Generates . . 20-13

Using Generated C/C++ Code . . . . . . . . . . . . . . . . . . . . . . . . 20-14

Generating C/C++ Code from MATLAB Code


21
Code Generation Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . 21-3
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-3

C/C++ Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-4


Specify Custom Files to Build . . . . . . . . . . . . . . . . . . . . . . . 21-4

xxv
Generating C/C++ Static Libraries from MATLAB Code . . . 21-5
Generate a C Static Library Using the MATLAB Coder App 21-5
Generate a C Static Library at the Command Line . . . . . . . 21-7

Generating C/C++ Dynamically Linked Libraries from


MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-9
Dynamic Libraries Generated by MATLAB Coder . . . . . . . . 21-9
Generate a C Dynamically Linked Library Using the MATLAB
Coder App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-9
Generate a C Dynamic Library at the Command Line . . . . 21-12

Generating Standalone C/C++ Executables from MATLAB


Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-14
Generate a C Executable Using the MATLAB Coder App . 21-14
Generate a C Executable at the Command Line . . . . . . . . 21-23
Specifying main Functions for C/C++ Executables . . . . . . . 21-24
Specify main Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-25

Configure Build Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-26


Specify Build Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-26
Specify a Language for Code Generation . . . . . . . . . . . . . . 21-28
Specify Output File Name . . . . . . . . . . . . . . . . . . . . . . . . . 21-30
Specify Output File Locations . . . . . . . . . . . . . . . . . . . . . . 21-30
Parameter Specification Methods . . . . . . . . . . . . . . . . . . . 21-32
Specify Build Configuration Parameters . . . . . . . . . . . . . . 21-32

Specify Data Types Used in Generated Code . . . . . . . . . . . 21-38


Specify Data Type Using the MATLAB Coder App . . . . . . 21-38
Specify Data Type at the Command Line . . . . . . . . . . . . . 21-38

Standard Math Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-39

Change the Standard Math Library . . . . . . . . . . . . . . . . . . 21-40


See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-40

Share Build Configuration Settings . . . . . . . . . . . . . . . . . . 21-41


Export Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-41
Import Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-42
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-42

Convert MATLAB Coder Project to MATLAB Script . . . . . 21-43


Convert a Project Using the MATLAB Coder App . . . . . . . 21-43
Convert a Project Using the Command-Line Interface . . . . 21-43

xxvi Contents
Run the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-43

Primary Function Input Specification . . . . . . . . . . . . . . . . 21-45


Why You Must Specify Input Properties . . . . . . . . . . . . . . 21-45
Properties to Specify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-45
Rules for Specifying Properties of Primary Inputs . . . . . . . 21-48
Methods for Defining Properties of Primary Inputs . . . . . . 21-49
Define Input Properties by Example at the Command Line 21-50
Specify Constant Inputs at the Command Line . . . . . . . . . 21-52
Specify Variable-Size Inputs at the Command Line . . . . . . 21-53

Specify Cell Array Inputs at the Command Line . . . . . . . . 21-55


Specify Cell Array Inputs by Example . . . . . . . . . . . . . . . . 21-55
Specify the Type of the Cell Array Input . . . . . . . . . . . . . . 21-56
Make a Homogeneous Copy of a Type . . . . . . . . . . . . . . . . 21-57
Make a Heterogeneous Copy of a Type . . . . . . . . . . . . . . . 21-58
Specify Variable-Size Cell Array Inputs . . . . . . . . . . . . . . 21-59
Specify Type Name for Heterogeneous Cell Array Inputs . . 21-60
Specify Constant Cell Array Inputs . . . . . . . . . . . . . . . . . . 21-60

Control Constant Inputs in MEX Function Signatures . . . 21-62


Control MEX Function Signature Using the MATLAB Coder
App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-62
Control MEX Function Signature at the Command-Line
Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-62
Options for Controlling Constant Inputs in MEX Function
Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-63
Call MEX Function with a Constant Input . . . . . . . . . . . . 21-64
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-65

Define Input Properties Programmatically in the MATLAB


File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-66
How to Use assert with MATLAB Coder . . . . . . . . . . . . . . 21-66
Rules for Using assert Function . . . . . . . . . . . . . . . . . . . . 21-72
Specifying General Properties of Primary Inputs . . . . . . . . 21-72
Specifying Properties of Primary Fixed-Point Inputs . . . . . 21-73
Specifying Properties of Cell Arrays . . . . . . . . . . . . . . . . . 21-74
Specifying Class and Size of Scalar Structure . . . . . . . . . . 21-76
Specifying Class and Size of Structure Array . . . . . . . . . . 21-76

Speed Up Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-78


Generate Code Only . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-78

xxvii
Disable Creation of the Code Generation Report . . . . . . . 21-79

Paths and File Infrastructure Setup . . . . . . . . . . . . . . . . . . 21-80


Compile Path Search Order . . . . . . . . . . . . . . . . . . . . . . . . 21-80
Specify Folders to Search for Custom Code . . . . . . . . . . . . 21-80
Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-81

Generate Code for Multiple Entry-Point Functions . . . . . 21-86


Advantages of Generating Code for Multiple Entry-Point
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-86
Generate Code for More Than One Entry-Point Function Using
the MATLAB Coder App . . . . . . . . . . . . . . . . . . . . . . . . 21-86
Generating Code for More Than One Entry-Point Function at
the Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-89
How to Call an Entry-Point Function in a MEX Function . 21-90
How to Call an Entry-Point Function in a C/C++ Library
Function from C/C++ Code . . . . . . . . . . . . . . . . . . . . . . 21-91

Generate Code for Global Data . . . . . . . . . . . . . . . . . . . . . . 21-92


Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-92
Declare Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 21-92
Define Global Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-93
Synchronizing Global Data with MATLAB . . . . . . . . . . . . 21-94
Define Constant Global Data . . . . . . . . . . . . . . . . . . . . . . . 21-98
Limitations of Using Global Data . . . . . . . . . . . . . . . . . . 21-101

Specify Global Cell Arrays at the Command Line . . . . . . 21-102

Generate Code for Enumerated Types . . . . . . . . . . . . . . . 21-104


See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-104

Generate Code for Variable-Size Data . . . . . . . . . . . . . . . 21-105


Disable Support for Variable-Size Data . . . . . . . . . . . . . . 21-105
Control Dynamic Memory Allocation . . . . . . . . . . . . . . . . 21-106
Generating Code for MATLAB Functions with Variable-Size
Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-108
Generate Code for a MATLAB Function That Expands a Vector
in a Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-109
Using Dynamic Memory Allocation for an "Atoms"
Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-115

Code Generation for MATLAB Classes . . . . . . . . . . . . . . . 21-123

xxviii Contents
How MATLAB Coder Partitions Generated Code . . . . . . 21-124
Partitioning Generated Files . . . . . . . . . . . . . . . . . . . . . . 21-124
How to Select the File Partitioning Method . . . . . . . . . . . 21-124
Partitioning Generated Files with One C/C++ File Per
MATLAB File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-125
Generated Files and Locations . . . . . . . . . . . . . . . . . . . . 21-130
File Partitioning and Inlining . . . . . . . . . . . . . . . . . . . . . 21-132

Requirements for Signed Integer Representation . . . . . . 21-137

Customize the Post-Code-Generation Build Process . . . . 21-138


Customize Build Using coder.updateBuildInfo . . . . . . . . . 21-138
Customize Build Using Post-Code-Generation Command . 21-138
Build Information Object . . . . . . . . . . . . . . . . . . . . . . . . . 21-139
Build Information Methods . . . . . . . . . . . . . . . . . . . . . . . 21-139
Write Post-Code-Generation Command . . . . . . . . . . . . . . 21-173
Use Post-Code-Generation Command to Customize Build 21-174
Write and Use Post-Code-Generation Command at the
Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-175

Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-176
Run-time Stack Overflow . . . . . . . . . . . . . . . . . . . . . . . . 21-176

Verify Generated C/C++ Code


22
Generation of Traceable Code . . . . . . . . . . . . . . . . . . . . . . . . 22-2
Code Traceability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-2
Generate Traceable Code . . . . . . . . . . . . . . . . . . . . . . . . . . 22-2
Format of Traceability Tags . . . . . . . . . . . . . . . . . . . . . . . . 22-4
Location of Comments in Generated Code . . . . . . . . . . . . . . 22-5
Traceability Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-9

Code Generation Reports . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-10


Code Generation Report Overview . . . . . . . . . . . . . . . . . . . 22-10
Generating and Opening Reports . . . . . . . . . . . . . . . . . . . 22-12
Names and Locations of Reports . . . . . . . . . . . . . . . . . . . . 22-12
MATLAB Code in a Report . . . . . . . . . . . . . . . . . . . . . . . . 22-12
Call Stack Information in a Report . . . . . . . . . . . . . . . . . . 22-14
Generated C/C++ Code in a Report . . . . . . . . . . . . . . . . . . 22-16

xxix
Build Summary Information in a Report . . . . . . . . . . . . . . 22-17
Errors and Warnings in a Report . . . . . . . . . . . . . . . . . . . 22-17
MATLAB Code Variables in a Report . . . . . . . . . . . . . . . . 22-18
Target Build Information in a Report . . . . . . . . . . . . . . . . 22-23
Keyboard Shortcuts for a Report . . . . . . . . . . . . . . . . . . . . 22-24
Searching in a Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-26
Report Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-26

Enable Code Generation Reports . . . . . . . . . . . . . . . . . . . . 22-28


Enable Code Generation Reports with the MATLAB Coder
App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-28
Enable Code Generation Reports at the Command Line . . 22-28

Run-Time Error Detection and Reporting in Standalone C/C+


+ Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-29

Generate Standalone Code That Detects and Reports Run-


Time Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-31

Testing Code Generated from MATLAB Code . . . . . . . . . . 22-33

Code Replacement for MATLAB Code


23
What Is Code Replacement? . . . . . . . . . . . . . . . . . . . . . . . . . . 23-2

Code Replacement Libraries . . . . . . . . . . . . . . . . . . . . . . . . . 23-4

Code Replacement Terminology . . . . . . . . . . . . . . . . . . . . . . 23-6

Code Replacement Limitations . . . . . . . . . . . . . . . . . . . . . . . 23-9

Replace Code Generated from MATLAB Code . . . . . . . . . . 23-10

Choose a Code Replacement Library . . . . . . . . . . . . . . . . . 23-12


About Choosing a Code Replacement Library . . . . . . . . . . 23-12
Explore Available Code Replacement Libraries . . . . . . . . . 23-12
Explore Code Replacement Library Contents . . . . . . . . . . 23-12

xxx Contents
Custom Toolchain Registration
24
Custom Toolchain Registration . . . . . . . . . . . . . . . . . . . . . . . 24-2
What Is a Custom Toolchain? . . . . . . . . . . . . . . . . . . . . . . . 24-2
What Is a Factory Toolchain? . . . . . . . . . . . . . . . . . . . . . . . 24-2
What is a Toolchain Definition? . . . . . . . . . . . . . . . . . . . . . 24-3
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-4
Typical Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-4

About coder.make.ToolchainInfo . . . . . . . . . . . . . . . . . . . . . . 24-6

Create and Edit Toolchain Definition File . . . . . . . . . . . . . . 24-8

Toolchain Definition File with Commentary . . . . . . . . . . . 24-10


Steps Involved in Writing a Toolchain Definition File . . . . 24-10
Write a Function That Creates a ToolchainInfo Object . . . 24-10
Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-11
Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-11
C Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-12
C++ Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-12
Linker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-13
Archiver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-13
Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-14
Build Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-14

Create and Validate ToolchainInfo Object . . . . . . . . . . . . . 24-16

Register the Custom Toolchain . . . . . . . . . . . . . . . . . . . . . . 24-17

Use the Custom Toolchain . . . . . . . . . . . . . . . . . . . . . . . . . . 24-19

Troubleshooting Custom Toolchain Validation . . . . . . . . . 24-20


Build Tool Command Path Incorrect . . . . . . . . . . . . . . . . . 24-20
Build Tool Not in System Path . . . . . . . . . . . . . . . . . . . . . 24-20
Tool Path Does Not Exist . . . . . . . . . . . . . . . . . . . . . . . . . 24-21
Unsupported Platform . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-21
Toolchain is Not installed . . . . . . . . . . . . . . . . . . . . . . . . . 24-22
Project or Configuration is Using the Template Makefile . . 24-22
Skipped Validation of Build Tool “Download” or “Execute” . 24-23

xxxi
Prevent Circular Data Dependencies with One-Pass or
Single-Pass Linkers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-24

Deploying Generated Code


25
Call a C Static Library Function from C Code . . . . . . . . . . . 25-2

Call a C/C++ Static Library Function from MATLAB Code . 25-4

Call Generated C/C++ Functions . . . . . . . . . . . . . . . . . . . . . . 25-6


Conventions for Calling Functions in Generated Code . . . . . 25-6
How to Call C/C++ Functions from MATLAB Code . . . . . . . 25-6
Calling Initialize and Terminate Functions . . . . . . . . . . . . . 25-7
Calling C/C++ Functions with Multiple Outputs . . . . . . . . . 25-8
Calling C/C++ Functions that Return Arrays . . . . . . . . . . . 25-8

Use a C Dynamic Library in a Microsoft Visual Studio


Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-9

Specify External File Locations . . . . . . . . . . . . . . . . . . . . . . 25-12


External File Locations for External Code Integration . . . . 25-12
Specify External Files in a Class Derived from
coder.ExternalDependency . . . . . . . . . . . . . . . . . . . . . . . 25-12
Specify External Files in MATLAB Code Using
coder.updateBuildInfo . . . . . . . . . . . . . . . . . . . . . . . . . . 25-12
Specify External Files Using the MATLAB Coder App . . . . 25-13
Specify External Files at the Command Line . . . . . . . . . . . 25-13
Specify External Files with Configuration Objects . . . . . . . 25-14

Code Generation of Matrices and Arrays . . . . . . . . . . . . . . 25-16

Incorporate Generated Code Using an Example Main


Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-18
Workflow for Using an Example Main Function . . . . . . . . 25-18
Control Example Main Generation Using the MATLAB Coder
App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-19
Control Example Main Generation Using the Command-Line
Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-19

xxxii Contents
Use an Example C Main in an Application . . . . . . . . . . . . . 25-21
Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-21
Create a Folder and Copy Relevant Files . . . . . . . . . . . . . 25-22
Run the Sobel Filter on the Image . . . . . . . . . . . . . . . . . . 25-24
Generate and Test a MEX Function . . . . . . . . . . . . . . . . . 25-26
Generate an Example Main Function for sobel.m . . . . . . . 25-26
Copy the Example Main Files . . . . . . . . . . . . . . . . . . . . . . 25-29
Modify the Generated Example Main Function . . . . . . . . . 25-29
Generate the Sobel Filter Application . . . . . . . . . . . . . . . . 25-42
Run the Sobel Filter Application . . . . . . . . . . . . . . . . . . . . 25-42
Display the Resulting Image . . . . . . . . . . . . . . . . . . . . . . . 25-42

Package Code for Other Development Environments . . . . 25-44


When to Package Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-44
Package Generated Code Using the MATLAB Coder App . 25-44
Package Generated Code at the Command Line . . . . . . . . 25-45
Specify packNGo Options . . . . . . . . . . . . . . . . . . . . . . . . . 25-47

Structure of Generated Example C/C++ Main Function . . 25-49


Contents of the File main.c or main.cpp . . . . . . . . . . . . . 25-49
Contents of the File main.h . . . . . . . . . . . . . . . . . . . . . . . 25-52

Troubleshoot Failures in Deployed Code . . . . . . . . . . . . . . 25-53

Accelerating MATLAB Algorithms


26
Workflow for Accelerating MATLAB Algorithms . . . . . . . . . 26-2
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-3

Best Practices for Using MEX Functions to Accelerate


MATLAB Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-4
Accelerate Code That Dominates Execution Time . . . . . . . . 26-4
Include Loops Inside MEX Function . . . . . . . . . . . . . . . . . . 26-4
Avoid Generating MEX Functions from Unsupported
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-5
Avoid Generating MEX Functions if Built-In MATLAB
Functions Dominate Run Time . . . . . . . . . . . . . . . . . . . . 26-6
Minimize MEX Function Calls . . . . . . . . . . . . . . . . . . . . . . 26-6

xxxiii
Edge Detection on Images . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-7

Accelerate MATLAB Algorithms . . . . . . . . . . . . . . . . . . . . . 26-14

Modifying MATLAB Code for Acceleration . . . . . . . . . . . . 26-15


How to Modify Your MATLAB Code for Acceleration . . . . . 26-15

Control Run-Time Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-16


Types of Run-Time Checks . . . . . . . . . . . . . . . . . . . . . . . . 26-16
When to Disable Run-Time Checks . . . . . . . . . . . . . . . . . . 26-16
How to Disable Run-Time Checks . . . . . . . . . . . . . . . . . . . 26-17

Algorithm Acceleration Using Parallel for-Loops (parfor) 26-19


Parallel for-Loops (parfor) in Generated Code . . . . . . . . . . 26-19
How parfor-Loops Improve Execution Speed . . . . . . . . . . . 26-20
When to Use parfor-Loops . . . . . . . . . . . . . . . . . . . . . . . . . 26-20
When Not to Use parfor-Loops . . . . . . . . . . . . . . . . . . . . . 26-20
parfor-Loop Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-21
parfor Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-21

Control Compilation of parfor-Loops . . . . . . . . . . . . . . . . . 26-25


When to Disable parfor . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-25

Reduction Assignments in parfor-Loops . . . . . . . . . . . . . . . 26-26


What are Reduction Assignments? . . . . . . . . . . . . . . . . . . 26-26
Multiple Reductions in a parfor-Loop . . . . . . . . . . . . . . . . 26-26

Classification of Variables in parfor-Loops . . . . . . . . . . . . 26-27


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-27
Sliced Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-28
Broadcast Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-29
Reduction Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-29
Temporary Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-34

Accelerate MATLAB Algorithms That Use Parallel for-Loops


(parfor) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-36

Specify Maximum Number of Threads in parfor-Loops . . 26-37

Troubleshooting parfor-Loops . . . . . . . . . . . . . . . . . . . . . . . 26-38


Global or Persistent Declarations in parfor-Loop . . . . . . . 26-38
Compiler Does Not Support OpenMP . . . . . . . . . . . . . . . . 26-38

xxxiv Contents
Accelerating Simulation of Bouncing Balls . . . . . . . . . . . . 26-39

Calling C/C++ Functions from Generated Code


27
External Function Calls from Generated Code . . . . . . . . . . 27-2
Calling External Functions from Generated Code . . . . . . . . 27-2
Why Call External Functions from Generated Code? . . . . . . 27-2
How To Call External Functions . . . . . . . . . . . . . . . . . . . . . 27-2
Pass Arguments by Reference to External Functions . . . . . . 27-3
Manipulate C Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-4

Call External Functions by Using coder.ceval . . . . . . . . . . . 27-6


Workflow for Calling External Functions . . . . . . . . . . . . . . 27-6
Best Practices for Calling External Code from Generated
Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-7

Return Multiple Values from C Functions . . . . . . . . . . . . . . 27-8

How MATLAB Coder Infers C/C++ Data Types . . . . . . . . . . 27-9


Mapping MATLAB Types to C/C++ Types . . . . . . . . . . . . . . 27-9
Mapping 64-Bit Integer Types to C/C++ . . . . . . . . . . . . . . 27-10
Mapping Fixed-Point Types to C/C++ . . . . . . . . . . . . . . . . 27-11
Mapping Arrays to C/C++ . . . . . . . . . . . . . . . . . . . . . . . . . 27-11
Mapping Complex Values to C/C++ . . . . . . . . . . . . . . . . . . 27-12
Mapping Structures to C/C++ Structures . . . . . . . . . . . . . 27-13
Mapping Strings to C/C++ . . . . . . . . . . . . . . . . . . . . . . . . . 27-13
Mapping Multiword Types to C/C++ . . . . . . . . . . . . . . . . . 27-14

External Code Integration


28
External Code Integration for Code Generation . . . . . . . . . 28-2

Encapsulating the Interface to External Code . . . . . . . . . . . 28-3

xxxv
Best Practices for Using coder.ExternalDependency . . . . . 28-4
Terminate Code Generation for Unsupported External
Dependency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-4
Parameterize Methods for MATLAB and Generated Code . . 28-4
Parameterize updateBuildInfo for Multiple Platforms . . . . . 28-5

Encapsulate Interface to an External C Library . . . . . . . . . 28-6

Update Build Information from MATLAB code . . . . . . . . . . 28-9

Call External Functions Encapsulated by


coder.ExternalDependency . . . . . . . . . . . . . . . . . . . . . . . . 28-10

Generate Efficient and Reusable Code


29
Optimization Strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-3

Modularize MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-6

Eliminate Redundant Copies of Function Inputs . . . . . . . . 29-7

Inline Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-10


Prevent Function Inlining . . . . . . . . . . . . . . . . . . . . . . . . . 29-10
Use Inlining in Control Flow Statements . . . . . . . . . . . . . 29-10

Control Inlining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-12


Control Size of Functions Inlined . . . . . . . . . . . . . . . . . . . 29-12
Control Size of Functions After Inlining . . . . . . . . . . . . . . 29-13
Control Stack Size Limit on Inlined Functions . . . . . . . . . 29-13

Fold Function Calls into Constants . . . . . . . . . . . . . . . . . . . 29-15

Control Stack Space Usage . . . . . . . . . . . . . . . . . . . . . . . . . . 29-17

Stack Allocation and Performance . . . . . . . . . . . . . . . . . . . 29-18

Dynamic Memory Allocation and Performance . . . . . . . . . 29-19


When Dynamic Memory Allocation Occurs . . . . . . . . . . . . 29-19

xxxvi Contents
Minimize Dynamic Memory Allocation . . . . . . . . . . . . . . . . 29-20

Provide Maximum Size for Variable-Size Arrays . . . . . . . . 29-21

Disable Dynamic Memory Allocation During Code


Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-27

Set Dynamic Memory Allocation Threshold . . . . . . . . . . . . 29-28


Set Dynamic Memory Allocation Threshold Using the MATLAB
Coder App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-28
Set Dynamic Memory Allocation Threshold at the Command
Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-29

Excluding Unused Paths from Generated Code . . . . . . . . . 29-30

Prevent Code Generation for Unused Execution Paths . . 29-31


Prevent Code Generation When Local Variable Controls
Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-31
Prevent Code Generation When Input Variable Controls
Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-32

Generate Code with Parallel for-Loops (parfor) . . . . . . . . 29-33

Minimize Redundant Operations in Loops . . . . . . . . . . . . . 29-35

Unroll for-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-37


Limit Copying the for-loop Body in Generated Code . . . . . 29-37

Support for Integer Overflow and Non-Finites . . . . . . . . . 29-40


Disable Support for Integer Overflow . . . . . . . . . . . . . . . . 29-40
Disable Support for Non-Finite Numbers . . . . . . . . . . . . . 29-41

Integrate External/Custom Code . . . . . . . . . . . . . . . . . . . . . 29-42

MATLAB Coder Optimizations in Generated Code . . . . . . 29-48


Constant Folding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-48
Loop Fusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-49
Successive Matrix Operations Combined . . . . . . . . . . . . . . 29-49
Unreachable Code Elimination . . . . . . . . . . . . . . . . . . . . . 29-50
memcpy Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-51
memset Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-51

memcpy Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-52

xxxvii
memset Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-54
memset Optimization for an Integer Constant . . . . . . . . . . 29-54
memset Optimization for Float or Double Zero . . . . . . . . . 29-55

Generate Reusable Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-56

Reuse Large Arrays and Structures . . . . . . . . . . . . . . . . . . 29-57

Variable Reuse in Generated Code . . . . . . . . . . . . . . . . . . . 29-58

LAPACK Calls in Generated Code . . . . . . . . . . . . . . . . . . . . 29-59

Speed Up Linear Algebra in Generated Standalone Code by


Using LAPACK Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-60
Specify LAPACK Library . . . . . . . . . . . . . . . . . . . . . . . . . 29-60
Write LAPACK Callback Class . . . . . . . . . . . . . . . . . . . . . 29-60
Generate LAPACK Calls by Specifying a LAPACK Callback
Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-61
Locate LAPACK Library in Execution Environment . . . . . 29-62

Generating Reentrant C Code from MATLAB Code


30
Generate Reentrant C Code from MATLAB Code . . . . . . . . 30-2
About This Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-2
Copying Files Locally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-3
About the Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-4
Providing a C main Function . . . . . . . . . . . . . . . . . . . . . . . 30-5
Configuring Build Parameters . . . . . . . . . . . . . . . . . . . . . . . 30-6
Generating the C Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-7
Viewing the Generated C Code . . . . . . . . . . . . . . . . . . . . . . 30-7
Running the Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-8
Key Points to Remember . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-8
Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-9

Reentrant Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-10

Specify Generation of Reentrant Code . . . . . . . . . . . . . . . . 30-12


Specify Generation of Reentrant Code Using the MATLAB
Coder App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-12

xxxviii Contents
Specify Generation of Reentrant Code Using the Command-
Line Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-12

Generated Code API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-14

Call Reentrant Code in a Single-Thread Environment . . . 30-15

Call Reentrant Code in a Multithreaded Environment . . . 30-16


Multithreaded Examples . . . . . . . . . . . . . . . . . . . . . . . . . . 30-16

Call Reentrant Code with No Persistent or Global Data (UNIX


Only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-17
Provide a Main Function . . . . . . . . . . . . . . . . . . . . . . . . . . 30-17
Generate Reentrant C Code . . . . . . . . . . . . . . . . . . . . . . . 30-19
Examine the Generated Code . . . . . . . . . . . . . . . . . . . . . . 30-20
Run the Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-21

Call Reentrant Code — Multithreaded with Persistent Data


(Windows Only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-22
MATLAB Code for This Example . . . . . . . . . . . . . . . . . . . 30-22
Provide a Main Function . . . . . . . . . . . . . . . . . . . . . . . . . . 30-23
Generate Reentrant C Code . . . . . . . . . . . . . . . . . . . . . . . 30-25
Examine the Generated Code . . . . . . . . . . . . . . . . . . . . . . 30-25
Run the Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-26

Call Reentrant Code — Multithreaded with Persistent Data


(UNIX Only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-27
MATLAB Code for This Example . . . . . . . . . . . . . . . . . . . 30-27
Provide a Main Function . . . . . . . . . . . . . . . . . . . . . . . . . . 30-28
Generate Reentrant C Code . . . . . . . . . . . . . . . . . . . . . . . 30-30
Examine the Generated Code . . . . . . . . . . . . . . . . . . . . . . 30-31
Run the Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-32

xxxix
1

About MATLAB Coder

• “MATLAB Coder Product Description” on page 1-2


• “Product Overview” on page 1-3
• “Code Generation Workflow” on page 1-5
1 About MATLAB Coder

MATLAB Coder Product Description


Generate C and C++ code from MATLAB code

MATLAB® Coder™ generates readable and portable C and C++ code from MATLAB
code. It supports most of the MATLAB language and a wide range of toolboxes. You
can integrate the generated code into your projects as source code, static libraries, or
dynamic libraries. You can also use the generated code within the MATLAB environment
to accelerate computationally intensive portions of your MATLAB code. MATLAB Coder
lets you incorporate legacy C code into your MATLAB algorithm and into the generated
code.

By using MATLAB Coder with Embedded Coder®, you can further optimize code
efficiency and customize the generated code. You can then verify the numerical behavior
of the generated code using software-in-the-loop (SIL) and processor-in-the-loop (PIL)
execution.

Key Features
• ANSI®/ISO® compliant C and C++ code generation
• Code generation support for toolboxes including Communications System Toolbox™,
Computer Vision System Toolbox™, DSP System Toolbox™, Image Processing
Toolbox™, and Signal Processing Toolbox™
• MEX function generation for code verification and acceleration
• Legacy C code integration into MATLAB algorithms and generated code
• Multicore-capable code generation using OpenMP
• Static or dynamic memory-allocation control
• App and equivalent command-line functions for managing code generation projects

1-2
Product Overview

Product Overview
In this section...
“When to Use MATLAB Coder” on page 1-3
“Code Generation for Embedded Software Applications” on page 1-3
“Code Generation for Fixed-Point Algorithms” on page 1-3

When to Use MATLAB Coder


Use MATLAB Coder to:

• Generate readable, efficient, standalone C/C++ code from MATLAB code.


• Generate MEX functions from MATLAB code to:

• Accelerate your MATLAB algorithms.


• Verify generated C code within MATLAB.
• Integrate custom C/C++ code into MATLAB.

Code Generation for Embedded Software Applications


The Embedded Coder product extends the MATLAB Coder product with features that
are important for embedded software development. Using the Embedded Coder add-
on product, you can generate code that has the clarity and efficiency of professional
handwritten code. For example, you can:

• Generate code that is compact and fast, which is essential for real-time simulators,
on-target rapid prototyping boards, microprocessors used in mass production, and
embedded systems.
• Customize the appearance of the generated code.
• Optimize the generated code for a specific target environment.
• Enable tracing options that help you to verify the generated code.
• Generate reusable, reentrant code.

Code Generation for Fixed-Point Algorithms


Using the Fixed-Point Designer™ product, you can generate:

1-3
1 About MATLAB Coder

• MEX functions to accelerate fixed-point algorithms.


• Fixed-point code that provides a bit-wise match to MEX function results.

1-4
Code Generation Workflow

Code Generation Workflow

See Also
• “Set Up a MATLAB Coder Project” on page 18-2
• “Workflow for Preparing MATLAB Code for Code Generation” on page 19-2
• “Workflow for Testing MEX Functions in MATLAB” on page 20-3
• “Code Generation Workflow” on page 21-3
• “Workflow for Accelerating MATLAB Algorithms” on page 26-2

1-5
2

Design Considerations for C/C++


Code Generation

• “When to Generate Code from MATLAB Algorithms” on page 2-2


• “Which Code Generation Feature to Use” on page 2-4
• “Prerequisites for C/C++ Code Generation from MATLAB” on page 2-5
• “MATLAB Code Design Considerations for Code Generation” on page 2-6
• “Differences in Behavior After Compiling MATLAB Code” on page 2-8
• “MATLAB Language Features Supported for C/C++ Code Generation” on page
2-13
2 Design Considerations for C/C++ Code Generation

When to Generate Code from MATLAB Algorithms


Generating code from MATLAB algorithms for desktop and embedded systems allows
you to perform your software design, implementation, and testing completely within the
MATLAB workspace. You can:

• Verify that your algorithms are suitable for code generation


• Generate efficient, readable, and compact C/C++ code automatically, which eliminates
the need to manually translate your MATLAB algorithms and minimizes the risk of
introducing errors in the code.
• Modify your design in MATLAB code to take into account the specific requirements of
desktop and embedded applications, such as data type management, memory use, and
speed.
• Test the generated code and easily verify that your modified algorithms are
functionally equivalent to your original MATLAB algorithms.
• Generate MEX functions to:

• Accelerate MATLAB algorithms in certain applications.


• Speed up fixed-point MATLAB code.
• Generate hardware description language (HDL) from MATLAB code.

When Not to Generate Code from MATLAB Algorithms


Do not generate code from MATLAB algorithms for the following applications. Use the
recommended MathWorks product instead.

To: Use:
Deploy an application that uses handle MATLAB Compiler™
graphics
Use Java® MATLAB Compiler SDK™
Use toolbox functions that do not support Toolbox functions that you rewrite for
code generation desktop and embedded applications
Deploy MATLAB based GUI applications MATLAB Compiler
on a supported MATLAB host
Deploy web-based or Windows® MATLAB Compiler SDK
applications

2-2
When to Generate Code from MATLAB Algorithms

To: Use:
Interface C code with MATLAB MATLAB mex function

2-3
2 Design Considerations for C/C++ Code Generation

Which Code Generation Feature to Use


To... Use... Required Product To Explore Further...
Generate MEX codegen function MATLAB Coder Try this in “MEX
functions for verifying Function Generation at
generated code the Command Line”.
Produce readable, MATLAB Coder app MATLAB Coder Try this in “C Code
efficient, and compact Generation Using the
code from MATLAB MATLAB Coder App”.
algorithms for codegen function MATLAB Coder Try this in “C Code
deployment to desktop Generation at the
and embedded Command Line”.
systems.
Generate MEX MATLAB Coder app MATLAB Coder See “Accelerate
functions to accelerate codegen function MATLAB Coder MATLAB Algorithms”
MATLAB algorithms on page 26-14.
Integrate MATLAB MATLAB Function Simulink Try this in “Track Object
code into Simulink® block Using MATLAB Code”.
Speed up fixed-point fiaccel function Fixed-Point Designer Learn more in “Code
MATLAB code Acceleration and
Code Generation from
MATLAB”.
Integrate custom C codegen function MATLAB Coder Learn more in “Specify
code into MATLAB External File Locations”
and generate efficient, on page 25-12.
readable code
Integrate custom coder.ceval function MATLAB Coder Learn more in
C code into code coder.ceval.
generated from
MATLAB
Generate HDL from MATLAB Function Simulink and Learn more at
MATLAB code block HDL Coder™ www.mathworks.com/
products/
slhdlcoder.

2-4
Prerequisites for C/C++ Code Generation from MATLAB

Prerequisites for C/C++ Code Generation from MATLAB


To generate C/C++ or MEX code from MATLAB algorithms, you must install the
following software:

• MATLAB Coder product


• C/C++ compiler

2-5
2 Design Considerations for C/C++ Code Generation

MATLAB Code Design Considerations for Code Generation


When writing MATLAB code that you want to convert into efficient, standalone C/C++
code, you must consider the following:

• Data types

C and C++ use static typing. To determine the types of your variables before use,
MATLAB Coder requires a complete assignment to each variable.
• Array sizing

Variable-size arrays and matrices are supported for code generation. You can define
inputs, outputs, and local variables in MATLAB functions to represent data that
varies in size at run time.
• Memory

You can choose whether the generated code uses static or dynamic memory allocation.

With dynamic memory allocation, you potentially use less memory at the expense
of time to manage the memory. With static memory, you get better speed, but with
higher memory usage. Most MATLAB code takes advantage of the dynamic sizing
features in MATLAB, therefore dynamic memory allocation typically enables you
to generate code from existing MATLAB code without modifying it much. Dynamic
memory allocation also allows some programs to compile even when upper bounds
cannot be found.

Static allocation reduces the memory footprint of the generated code, and therefore is
suitable for applications where there is a limited amount of available memory, such as
embedded applications.
• Speed

Because embedded applications must run in real time, the code must be fast enough
to meet the required clock rate.

To improve the speed of the generated code:

• Choose a suitable C/C++ compiler. Do not use the default compiler that
MathWorks supplies with MATLAB for Windows 64-bit platforms.
• Consider disabling run-time checks.

2-6
MATLAB Code Design Considerations for Code Generation

By default, for safety, the code generated for your MATLAB code contains memory
integrity checks and responsiveness checks. Generally, these checks result in more
generated code and slower simulation. Disabling run-time checks usually results
in streamlined generated code and faster simulation. Disable these checks only if
you have verified that array bounds and dimension checking is unnecessary.

See Also
• “Data Definition Basics”
• “Variable-Size Data”
• “Bounded Versus Unbounded Variable-Size Data” on page 7-4
• “Control Dynamic Memory Allocation” on page 21-106
• “Control Run-Time Checks” on page 26-16

2-7
2 Design Considerations for C/C++ Code Generation

Differences in Behavior After Compiling MATLAB Code


In this section...
“Why Are There Differences?” on page 2-8
“Character Size” on page 2-8
“Order of Evaluation in Expressions” on page 2-8
“Termination Behavior” on page 2-10
“Size of Variable-Size N-D Arrays” on page 2-10
“Size of Empty Arrays” on page 2-10
“Size of Empty Array That Results from Deleting Elements of an Array” on page
2-10
“Floating-Point Numerical Results” on page 2-11
“NaN and Infinity Patterns” on page 2-12
“Code Generation Target” on page 2-12
“MATLAB Class Initial Values” on page 2-12
“Variable-Size Support for Code Generation” on page 2-12
“Complex Numbers” on page 2-12

Why Are There Differences?


To convert MATLAB code to C/C++ code that works efficiently, the code generation
process introduces optimizations that intentionally cause the generated code to behave
differently — and sometimes produce different results — from the original source code.
This section describes these differences.

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 and Strings” on page 6-9.

Order of Evaluation in Expressions


Generated code does not enforce order of evaluation in expressions. For most expressions,
order of evaluation is not significant. However, for expressions with side effects, the

2-8
Differences in Behavior After Compiling MATLAB Code

generated code may produce the side effects in different order from the original MATLAB
code. Expressions that produce side effects include those that:

• Modify persistent or global variables


• Display data to the screen
• Write data to files
• Modify the properties of handle class objects

In addition, the generated code does not enforce order of evaluation of logical operators
that do not short circuit.

For more predictable results, it is good coding practice to split expressions that depend on
the order of evaluation into multiple statements.

• Rewrite
A = f1() + f2();

as
A = f1();
A = A + f2();

so that the generated code calls f1 before f2.


• Assign the outputs of a multi-output function call to variables that do not depend on
one another. For example, rewrite
[y, y.f, y.g] = foo;

as
[y, a, b] = foo;
y.f = a;
y.g = b;
• When you access the contents of multiple cells of a cell array, assign the results to
variables that do not depend on one another. For example, rewrite
[y, y.f, y.g] = z{:};

as
[y, a, b] = z{:};
y.f = a;

2-9
2 Design Considerations for C/C++ Code Generation

y.g = b;

Termination Behavior
Generated code does not match the termination behavior of MATLAB source code. For
example, if infinite loops do not have side effects, optimizations remove them from
generated code. As a result, the generated code can possibly terminate even though the
corresponding MATLAB code does not.

Size of Variable-Size N-D Arrays


For variable-size N-D arrays, the size function might return a different result in
generated code than in MATLAB source code. The size function sometimes returns
trailing ones (singleton dimensions) in generated code, but always drops trailing ones
in MATLAB. For example, for an N-D array X with dimensions [4 2 1 1], size(X)
might return [4 2 1 1] in generated code, but always returns [4 2] in MATLAB. See
“Incompatibility with MATLAB in Determining Size of Variable-Size N-D Arrays” on
page 7-28.

Size of Empty Arrays


The size of an empty array in generated code might be different from its size in MATLAB
source code. See “Incompatibility with MATLAB in Determining Size of Empty Arrays”
on page 7-29.

Size of Empty Array That Results from Deleting Elements of an Array


Deleting all elements of an array results in an empty array. The size of this empty array
in generated code might differ from its size in MATLAB source code.

Case Example Code Size of Empty Array Size of Empty Array


in MATLAB in Generated Code
Delete all elements coder.varsize('X',[4,4],[1,1]);
X = zeros(2);
0-by-0 1-by-0
of an m-by-n array X(:) = [];
by using the colon
operator (:).
Delete all elements coder.varsize('X',[1,4],[0,1]);
X = zeros(1,4);
0-by-0 1-by-0
of a row vector by X(:) = [];

2-10
Differences in Behavior After Compiling MATLAB Code

Case Example Code Size of Empty Array Size of Empty Array


in MATLAB in Generated Code
using the colon
operator (:).
Delete all elements coder.varsize('X',[4,1],[1,0]);
X = zeros(4,1);
0-by-0 0-by-1
of a column vector X(:) = [];
by using the colon
operator (:).
Delete all elements coder.varsize('X',[4,1],[1,0]);
X = zeros(4,1);
1-by-0 0-by-1
of a column vector for i = 1:4
by deleting one end
X(1)= [];

element at a time.

Floating-Point Numerical Results


The generated code might not produce the same floating-point numerical results as
MATLAB in the following situations:

When computer hardware uses extended precision registers


Results vary depending on how the C/C++ compiler allocates extended precision floating-
point registers. Computation results might not match MATLAB calculations because of
different compiler optimization settings or different code surrounding the floating-point
calculations.

For certain advanced library functions


The generated code might use different algorithms to implement certain advanced
library functions, such as fft, svd, eig, mldivide, and mrdivide.

For example, the generated code uses a simpler algorithm to implement svd to
accommodate a smaller footprint. Results might also vary according to matrix properties.
For example, MATLAB might detect symmetric or Hermitian matrices at run time and
switch to specialized algorithms that perform computations faster than implementations
in the generated code.

For implementation of BLAS library functions


For implementations of BLAS library functions, generated C/C++ code uses reference
implementations of BLAS functions. These reference implementations might produce
different results from platform-specific BLAS implementations in MATLAB.

2-11
2 Design Considerations for C/C++ Code Generation

NaN and Infinity Patterns


The generated code might not produce exactly the same pattern of NaN and inf values
as MATLAB code when these values are mathematically meaningless. For example, if
MATLAB output contains a NaN, output from the generated code should also contain a
NaN, but not necessarily in the same place.

Code Generation Target


The coder.target function returns different values in MATLAB than in the generated
code. The intent is to help you determine whether your function is executing in MATLAB
or has been compiled for a simulation or code generation target. See coder.target.

MATLAB Class Initial Values


Before code generation, at class loading time, MATLAB computes class initial values.
The code generation software uses the value that MATLAB computes. It does not
recompute the initial value. If the initialization uses a function call to compute the
initial value, the code generation software does not execute this function. If the function
modifies a global state, for example, a persistent variable, code generation software
might provide a different initial value than MATLAB. For more information, see
“Defining Class Properties for Code Generation” on page 11-4.

Variable-Size Support for Code Generation


See “Incompatibilities with MATLAB in Variable-Size Support for Code Generation” on
page 7-26.

Complex Numbers
See “Code Generation for Complex Data” on page 6-4.

2-12
MATLAB Language Features Supported for C/C++ Code Generation

MATLAB Language Features Supported for C/C++ Code


Generation
MATLAB Features That Code Generation Supports
Code generation from MATLAB supports the following language features:

• N-dimensional arrays (see “Array Size Restrictions for Code Generation” on page
6-10)
• Matrix operations, including deletion of rows and columns
• Variable-sized data (see “Variable-Size Data Definition for Code Generation” on page
7-3)
• Subscripting (see “Incompatibility with MATLAB in Matrix Indexing Operations for
Code Generation” on page 7-32)
• Complex numbers (see “Code Generation for Complex Data” on page 6-4)
• Numeric classes (see “Supported Variable Types” on page 5-17)
• Double-precision, single-precision, and integer math
• Fixed-point arithmetic
• Program control statements if, switch, for, while, and break
• Arithmetic, relational, and logical operators
• Local functions
• Persistent variables (see “Define and Initialize Persistent Variables” on page 5-10)
• Global variables (see “Specify Global Variable Type and Initial Value Using the App”
on page 18-26).
• Structures (see “Structure Definition for Code Generation” on page 8-2)
• Cell Arrays (see “Cell Arrays”)
• Characters (see “Code Generation for Characters and Strings” on page 6-9)
• Function handles (see “Function Handle Definition for Code Generation” on page
12-2)
• Frames
• Variable length input and output argument lists
• Subset of MATLAB toolbox functions (see “Functions and Objects Supported for C and
C++ Code Generation — Alphabetical List” on page 4-2)

2-13
2 Design Considerations for C/C++ Code Generation

• Subset of functions and System objects in Aerospace Toolbox, Communications


System Toolbox, Computer Vision System Toolbox, DSP System Toolbox, Fixed-Point
Designer, Image Processing Toolbox, Signal Processing Toolbox, Phased Array System
Toolbox™, Statistics and Machine Learning Toolbox™ (see “Functions and Objects
Supported for C and C++ Code Generation — Category List” on page 4-175)
• MATLAB classes (see “MATLAB Classes Definition for Code Generation” on page
11-2)
• Function calls (see “Resolution of Function Calls for Code Generation” on page
14-2)

MATLAB Language Features That Code Generation Does Not Support


Code generation from MATLAB does not support the following frequently used MATLAB
constructs:

• Anonymous functions
• Categorical Arrays
• Date and Time Arrays
• Java
• Map Containers
• Nested functions
• Recursion
• Sparse matrices
• Tables
• Time Series objects
• try/catch statements

This list is not exhaustive. To see if a construct is supported for code generation, see
“MATLAB Features That Code Generation Supports” on page 2-13.

2-14
3

System Objects Supported for Code


Generation
3 System Objects Supported for Code Generation

Code Generation for System Objects


You can generate C and C++ code for a subset of System objects provided by the following
toolboxes.

Toolbox Name See


Communications System Toolbox “System Objects in MATLAB Code
Generation” in the DSP System Toolbox
documentation.
Computer Vision System Toolbox “System Objects in MATLAB Code
Generation” in the Computer Vision
System Toolbox documentation.
DSP System Toolbox “System Objects in MATLAB Code
Generation” in the DSP System Toolbox
documentation.
Image Acquisition Toolbox™ • imaq.VideoDevice.
• “Code Generation with VideoDevice
System Object” in the Image Acquisition
Toolbox documentation.
Phased Array System Toolbox “Code Generation” in the Phased Array
System Toolbox documentation.
System Identification Toolbox™ “Generate Code for Online Parameter
Estimation in MATLAB” in the System
Identification Toolbox documentation.
WLAN System Toolbox™ “System Objects in MATLAB Code
Generation” in the DSP System Toolbox
documentation.

To use these System objects, you need to install the requisite toolbox. For a list of
System objects supported for C and C++ code generation, see “Functions and Objects
Supported for C and C++ Code Generation — Alphabetical List” on page 4-2 and
“Functions and Objects Supported for C and C++ Code Generation — Category List” on
page 4-175.

System objects are MATLAB object-oriented implementations of algorithms. They


extend MATLAB by enabling you to model dynamic systems represented by time-varying
algorithms. System objects are well integrated into the MATLAB language, regardless of

3-2
Code Generation for System Objects

whether you are writing simple functions, working interactively in the command window,
or creating large applications.

In contrast to MATLAB functions, System objects automatically manage state


information, data indexing, and buffering, which is particularly useful for iterative
computations or stream data processing. This enables efficient processing of long
data sets. For general information about MATLAB objects, see “Object-Oriented
Programming”.

3-3
4

Functions, Classes, and System


Objects Supported for Code
Generation

• “Functions and Objects Supported for C and C++ Code Generation — Alphabetical
List” on page 4-2
• “Functions and Objects Supported for C and C++ Code Generation — Category List”
on page 4-175
4 Functions, Classes, and System Objects Supported for Code Generation

Functions and Objects Supported for C and C++ Code Generation


— Alphabetical List
You can generate efficient C and C++ code for a subset of MATLAB built-in functions and
toolbox functions, classes, and System objects that you call from MATLAB code. These
function, classes, and System objects appear in alphabetical order in the following table.

To find supported functions, classes, and System objects by MATLAB category or toolbox,
see “Functions and Objects Supported for C and C++ Code Generation — Category List”
on page 4-175.

Note: For more information on code generation for fixed-point algorithms, refer to “Code
Acceleration and Code Generation from MATLAB”.

Name Product Remarks and Limitations


abs MATLAB —
abs Fixed-Point —
Designer
accumneg Fixed-Point —
Designer
accumpos Fixed-Point —
Designer
acos MATLAB When the input value x is real, but the output
should be complex, generates an error during
simulation and returns NaN in generated code.
To get the complex result, make the input value
complex by passing in complex(x).
acosd MATLAB —
acosh MATLAB • Generates an error during simulation and
returns NaN in generated code when the
input value x is real, but the output should
be complex. To get the complex result,
make the input value complex by passing in
complex(x).

4-2
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


acot MATLAB —
acotd MATLAB —
acoth MATLAB —
acsc MATLAB —
acscd MATLAB —
acsch MATLAB —
adaptthresh Image Processing The ForegroundPolarity and Statistic
Toolbox arguments must be compile-time constants.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The


NeighborhoodSize argument must be a
compile-time constant.
add Fixed-Point Code generation in MATLAB does not support
Designer the syntax F.add(a,b). You must use the
syntax add(F,a,b).
affine2d Image Processing When generating code, you can only specify
Toolbox single objects—arrays of objects are not
supported.

MATLAB Function Block support: Yes.


aictest Phased Array Does not support variable-size inputs.
System Toolbox
airy MATLAB Always returns a complex result.
albersheim Phased Array Does not support variable-size inputs.
System Toolbox
all MATLAB “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35

4-3
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


all Fixed-Point —
Designer
ambgfun Phased Array Does not support variable-size inputs.
System Toolbox
and MATLAB —
angdiff Robotics System Supports MATLAB Function block: Yes
Toolbox™
any MATLAB “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
any Fixed-Point —
Designer
aperture2gain Phased Array Does not support variable-size inputs.
System Toolbox
asec MATLAB —
asecd MATLAB —
asech MATLAB —
asin MATLAB • Generates an error during simulation and
returns NaN in generated code when the
input value x is real, but the output should
be complex. To get the complex result,
make the input value complex by passing in
complex(x).
asind MATLAB —
asinh MATLAB —

4-4
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


assert MATLAB • Generates specified error messages at
compile time only if all input arguments are
constants or depend on constants. Otherwise,
generates specified error messages at run
time.
• If called with more than 1 argument, has no
effect in standalone code even when run-time
error detection is enabled. See “Run-Time
Error Detection and Reporting in Standalone
C/C++ Code” on page 22-29.
• See “Rules for Using assert Function” on
page 21-72.
assignDetections- Computer Vision Supports MATLAB Function block: Yes
ToTracks System Toolbox
atan MATLAB —
atan2 MATLAB —
atan2 Fixed-Point —
Designer
atan2d MATLAB —
atand MATLAB —
atanh MATLAB • Generates an error during simulation and
returns NaN in generated code when the
input value x is real, but the output should
be complex. To get the complex result,
make the input value complex by passing in
complex(x).
audioDeviceReader Audio System “System Objects in MATLAB Code Generation”
Toolbox™
Supports MATLAB Function Block: Yes
audioDeviceWriter Audio System “System Objects in MATLAB Code Generation”
Toolbox
Supports MATLAB Function Block: Yes
audioDeviceWriter DSP System “System Objects in MATLAB Code Generation”
Toolbox

4-5
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


audioOscillator Audio System “System Objects in MATLAB Code Generation”
Toolbox
Supports MATLAB Function Block: Yes
audioPluginInterface Audio System Supports MATLAB Function Block: Yes
Toolbox
audioPluginParameter Audio System Supports MATLAB Function Block: Yes
Toolbox
audioPlugin Audio System Supports MATLAB Function Block: Yes
Toolbox
audioPluginSource Audio System Supports MATLAB Function Block: Yes
Toolbox
axang2quat Robotics System Supports MATLAB Function block: Yes
Toolbox
axang2rotm Robotics System Supports MATLAB Function block: Yes
Toolbox
axang2tform Robotics System Supports MATLAB Function block: Yes
Toolbox
az2broadside Phased Array Does not support variable-size inputs.
System Toolbox
azel2phitheta Phased Array Does not support variable-size inputs.
System Toolbox
azel2phithetapat Phased Array Does not support variable-size inputs.
System Toolbox
azel2uv Phased Array Does not support variable-size inputs.
System Toolbox
azel2uvpat Phased Array Does not support variable-size inputs.
System Toolbox
azelaxes Phased Array Does not support variable-size inputs.
System Toolbox
bandwidth MATLAB —

4-6
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


barthannwin Signal Processing Window length 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
bartlett Signal Processing Window length 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
bboxOverlapRatio Computer Vision SupportsMATLAB Function block: No
System Toolbox
bbox2points Computer Vision Supports MATLAB Function block: Yes
System Toolbox
beat2range Phased Array Does not support variable-size inputs.
System Toolbox
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
“Specify Constant Inputs at the Command Line”
on page 21-52.

4-7
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


besseli MATLAB • If the order nu is less than 0, it must be an
integer.
• Always returns a complex result.
besselj MATLAB • If the order nu is less than 0, it must be an
integer.
• Always returns a complex result.
beta MATLAB —
betacdf Statistics —
and Machine
Learning Toolbox
betafit Statistics —
and Machine
Learning Toolbox
betainc MATLAB Always returns a complex result.
betaincinv MATLAB Always returns a complex result.
betainv Statistics —
and Machine
Learning Toolbox
betalike Statistics —
and Machine
Learning Toolbox
betaln MATLAB —
betapdf Statistics —
and Machine
Learning Toolbox
betarnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.

4-8
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


betastat Statistics —
and Machine
Learning Toolbox
bi2de Communications —
System Toolbox
billingsleyicm Phased Array Does not support variable-size inputs.
System Toolbox
bin2dec MATLAB • Does not support cell arrays.
• Does not match MATLAB when the input is
empty.
binocdf Statistics —
and Machine
Learning Toolbox
binoinv Statistics —
and Machine
Learning Toolbox
binopdf Statistics —
and Machine
Learning Toolbox
binornd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
binostat Statistics —
and Machine
Learning Toolbox
bitand MATLAB —
bitand Fixed-Point • Not supported for slope-bias scaled fi
Designer objects.
bitandreduce Fixed-Point —
Designer

4-9
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


bitcmp MATLAB —
bitcmp Fixed-Point —
Designer
bitconcat Fixed-Point —
Designer
bitget MATLAB —
bitget Fixed-Point —
Designer
bitor MATLAB —
bitor Fixed-Point • Not supported for slope-bias scaled fi
Designer objects.
bitorreduce Fixed-Point —
Designer
bitreplicate Fixed-Point —
Designer
bitrevorder Signal Processing —
Toolbox
bitrol Fixed-Point —
Designer
bitror Fixed-Point —
Designer
bitset MATLAB —
bitset Fixed-Point —
Designer
bitshift MATLAB —
bitshift Fixed-Point —
Designer
bitsliceget Fixed-Point —
Designer
bitsll Fixed-Point • Generated code may not handle out of range
Designer shifting.

4-10
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


bitsra Fixed-Point • Generated code may not handle out of range
Designer shifting.
bitsrl Fixed-Point • Generated code may not handle out of range
Designer shifting.
bitxor MATLAB —
bitxor Fixed-Point • Not supported for slope-bias scaled fi
Designer objects.
bitxorreduce Fixed-Point —
Designer
blackman Signal Processing Window length 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
blackmanharris Signal Processing Window length 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
blanks MATLAB —
blkdiag MATLAB —

4-11
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


bohmanwin Signal Processing Window length 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
boundarymask Image Processing The conn argument must be a compile-time
Toolbox constant.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


break MATLAB —
BRISKPoints Computer Vision Supports MATLAB Function block: No
System Toolbox To index locations with this object, use
the syntax: points.Location(idx,:),
for points object. See
visionRecovertformCodeGeneration_kernel.m,
which is used in the “Introduction to Code
Generation with Feature Matching and
Registration” example.
broadside2az Phased Array Does not support variable-size inputs.
System Toolbox
bsxfun MATLAB “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35

4-12
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


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
“Specify Constant Inputs at the Command Line”
on page 21-52.
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
“Specify Constant Inputs at the Command Line”
on page 21-52.
buttord 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
“Specify Constant Inputs at the Command Line”
on page 21-52.

4-13
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


bwareaopen Image Processing BW must be a 2-D binary image. N-D arrays are
Toolbox not supported. conn can only be one of the two-
dimensional connectivities (4 or 8) or a 3-by-3
matrix. The 3-D connectivities (6, 18, and 26) are
not supported. Matrices of size 3-by-3-by-...-by-3
are not supported. conn must be a compile-time
constant.

MATLAB Function Block support: No.


bwboundaries Image Processing The conn and options arguments must be
Toolbox compile-time constants and the return value A
can only be a full matrix, not a sparse matrix.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: No.


bwconncomp Image Processing The input image must be 2-D.
Toolbox
The conn argument must be a compile-time
constant and the only connectivities supported
are 4 or 8. You can specify connectivity as a 3-
by-3 matrix, but it can only be [0 1 0;1 1 1;0
1 0] or ones(3).

The CC struct return value does not include the


PixelIdxList field.

MATLAB Function Block support: No.


bwdist Image Processing The method argument must be a compile-time
Toolbox constant. Input images must have fewer than 232
pixels.

Generated code for this function uses a


precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-14
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


bweuler Image Processing If you choose the generic MATLAB Host
Toolbox Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


bwlabel Image Processing When generating code, the parameter n must be
Toolbox a compile-time constant.

MATLAB Function Block support: No.


bwlookup Image Processing For best results, specify an input image of class
Toolbox logical.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


bwmorph Image Processing The text string specifying the operation must be
Toolbox a constant and, for best results, specify an input
image of class logical.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: No.


bwpack Image Processing Generated code for this function uses a
Toolbox precompiled platform-specific shared library.

MATLAB Function Block support: Yes.

4-15
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


bwperim Image Processing Supports only 2-D images. Does not support any
Toolbox no-output-argument syntaxes. The connectivity
matrix input argument, conn, must be a
compile-time constant.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


bwselect Image Processing Supports only the 3 and 4 input argument
Toolbox syntaxes: BW2 = bwselect(BW,c,r) and
BW2 = bwselect(BW,c,r,n). The optional
fourth input argument, n, must be a compile-
time constant. In addition, with code generation,
bwselect only supports only the 1 and 2 output
argument syntaxes: BW2 = bwselect(___) or
[BW2, idx] = bwselect(___).

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


bwtraceboundary Image Processing The dir, fstep, and conn arguments must be
Toolbox compile-time constants.

MATLAB Function Block support: No.


bwunpack Image Processing Generated code for this function uses a
Toolbox precompiled platform-specific shared library.

MATLAB Function Block support: Yes. The


input argument M must be a compile-time
constant.
ca2tf DSP System All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.

4-16
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


cameraMatrix Computer Vision Supports MATLAB Function block: No
System Toolbox
cameraParameters Computer Vision Supports MATLAB Function block: No
System Toolbox
cameraPose Computer Vision Supports MATLAB Function block: No
System Toolbox
cart2hom Robotics System Supports MATLAB Function block: Yes
Toolbox
cart2pol MATLAB —
cart2sph MATLAB —
cart2sphvec Phased Array Does not support variable-size inputs.
System Toolbox
cast MATLAB —
cat MATLAB • Does not support concatenation of cell arrays.
• If supplied, dim must be a constant.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
cbfweights Phased Array Does not support variable-size inputs.
System Toolbox
cdf Statistics —
and Machine
Learning Toolbox
ceil MATLAB —
ceil Fixed-Point —
Designer
cell MATLAB “Cell Array Requirements and Limitations for
Code Generation” on page 9-10

4-17
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


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
“Specify Constant Inputs at the Command Line”
on page 21-52.
char MATLAB Does not support cell arrays.
cheb1ap 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
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
“Specify Constant Inputs at the Command Line”
on page 21-52.

4-18
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


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
“Specify Constant Inputs at the Command Line”
on page 21-52.
cheb2ord 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
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
“Specify Constant Inputs at the Command Line”
on page 21-52.

4-19
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


cheby1 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
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
“Specify Constant Inputs at the Command Line”
on page 21-52.
chi2cdf Statistics —
and Machine
Learning Toolbox
chi2inv Statistics —
and Machine
Learning Toolbox
chi2pdf Statistics —
and Machine
Learning Toolbox
chi2rnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.

4-20
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


chi2stat Statistics —
and Machine
Learning Toolbox
chol MATLAB —
circpol2pol Phased Array Does not support variable-size inputs.
System Toolbox
circshift MATLAB Does not support cell arrays for the first
argument.
cl2tf DSP System All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
class MATLAB —
colon MATLAB • Does not accept complex inputs.
• The input i cannot have a logical value.
• Does not accept vector inputs.
• Inputs must be constants.
• Uses single-precision arithmetic to produce
single-precision results.
comm.ACPR Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.AGC Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.AlgebraicDeinterleaver Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.APPDecoder Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.AWGNChannel Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.BarkerCode Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.BCHDecoder Communications “System Objects in MATLAB Code Generation”
System Toolbox

4-21
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


comm.BCHEncoder Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.Binary- Communications “System Objects in MATLAB Code Generation”
SymmetricChannel System Toolbox
comm.BlockDeinterleaver Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.BlockInterleaver Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.BPSKDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.BPSKModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.CarrierSynchronizer Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.CCDF Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.CoarseFrequency- Communications “System Objects in MATLAB Code Generation”
Compensator System Toolbox
comm.ConstellationDiagram Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.Convolutional- Communications “System Objects in MATLAB Code Generation”
Deinterleaver System Toolbox
comm.ConvolutionalEncoder Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.Convolutional- Communications “System Objects in MATLAB Code Generation”
Interleaver System Toolbox
comm.CPFSKDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.CPFSKModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.CPMCarrier- Communications “System Objects in MATLAB Code Generation”
PhaseSynchronizer System Toolbox

4-22
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


comm.CPMDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.CPMModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.CRCDetector Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.CRCGenerator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.DBPSKDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.DBPSKModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.Descrambler Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.DifferentialDecoder Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.DifferentialEncoder Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.DiscreteTimeVCO Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.DPSKDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.DPSKModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.DQPSKDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.DQPSKModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.ErrorRate Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.EVM Communications “System Objects in MATLAB Code Generation”
System Toolbox

4-23
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


comm.FMBroadcast- Communications “System Objects in MATLAB Code Generation”
Demodulator System Toolbox
comm.FMBroadcast- Communications “System Objects in MATLAB Code Generation”
Modulator System Toolbox
comm.FMDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.FMModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.FSKDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.FSKModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.GeneralQAM- Communications “System Objects in MATLAB Code Generation”
Demodulator System Toolbox
comm.GeneralQAM- Communications “System Objects in MATLAB Code Generation”
Modulator System Toolbox
comm.GeneralQAMTCM- Communications “System Objects in MATLAB Code Generation”
Demodulator System Toolbox
comm.GeneralQAMTCM- Communications “System Objects in MATLAB Code Generation”
Modulator System Toolbox
comm.GMSKDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.GMSKModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.GMSKTiming- Communications “System Objects in MATLAB Code Generation”
Synchronizer System Toolbox
comm.GoldSequence Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.HadamardCode Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.HDLCRCDetector Communications “System Objects in MATLAB Code Generation”
System Toolbox

4-24
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


comm.HDLCRCGenerator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.HDLRSDecoder Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.HDLRSEncoder Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.HelicalDeinterleaver Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.HelicalInterleaver Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.IntegrateAnd- Communications “System Objects in MATLAB Code Generation”
DumpFilter System Toolbox
comm.IQImbalance- Communications “System Objects in MATLAB Code Generation”
Compensator System Toolbox
comm.KasamiSequence Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.LDPCDecoder Communications • Using default properties,
System Toolbox comm.LDPCDecoder does not support code
generation. To generate code, specify the
ParityCheckMatrix property as a non-
sparse row-column index matrix.
• “System Objects in MATLAB Code
Generation”
comm.LDPCEncoder Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.LTEMIMOChannel Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.MatrixDeinterleaver Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.MatrixHelical- Communications “System Objects in MATLAB Code Generation”
ScanDeinterleaver System Toolbox
comm.MatrixHelical- Communications “System Objects in MATLAB Code Generation”
ScanInterLeaver System Toolbox

4-25
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


comm.MatrixInterleaver Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.Memoryless- Communications “System Objects in MATLAB Code Generation”
Nonlinearity System Toolbox
comm.MER Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.MIMOChannel Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.MLSEEqualizer Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.MSKDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.MSKModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.MSKTiming- Communications “System Objects in MATLAB Code Generation”
Synchronizer System Toolbox
comm.Multiplexed- Communications “System Objects in MATLAB Code Generation”
Deinterleaver System Toolbox
comm.MultiplexedInterleaver Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.OFDMDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.OFDMModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.OSTBCCombiner Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.OSTBCEncoder Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.OQPSKDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.OQPSKModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox

4-26
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


comm.PAMDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.PAMModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.PhaseFrequencyOffset Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.PhaseNoise Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.PNSequence Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.PSKCoarseFrequency- Communications “System Objects in MATLAB Code Generation”
Estimator System Toolbox
comm.PSKDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.PSKModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.PSKTCMDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.PSKTCMModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.QAMCoarseFrequency- Communications “System Objects in MATLAB Code Generation”
Estimator System Toolbox
comm.QPSKDemodulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.QPSKModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.RaisedCosine- Communications “System Objects in MATLAB Code Generation”
ReceiveFilter System Toolbox
comm.RaisedCosine- Communications “System Objects in MATLAB Code Generation”
TransmitFilter System Toolbox
comm.RayleighChannel Communications “System Objects in MATLAB Code Generation”
System Toolbox

4-27
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


comm.RectangularQAM- Communications “System Objects in MATLAB Code Generation”
Demodulator System Toolbox
comm.RectangularModulator Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.RectangularQAMTCM- Communications “System Objects in MATLAB Code Generation”
Demodulator System Toolbox
comm.RectangularQAMTCM- Communications “System Objects in MATLAB Code Generation”
Modulator System Toolbox
comm.RicianChannel Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.RSDecoder Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.RSEncoder Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.Scrambler Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.SphereDecoder Communications Communications System Toolbox
System Toolbox
comm.SymbolSynchronizer Communications Communications System Toolbox
System Toolbox
comm.ThermalNoise Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.TurboDecoder Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.TurboEncoder Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.ViterbiDecoder Communications “System Objects in MATLAB Code Generation”
System Toolbox
comm.WalshCode Communications “System Objects in MATLAB Code Generation”
System Toolbox
compan MATLAB —
complex MATLAB —

4-28
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


complex Fixed-Point —
Designer
compressor Audio System “System Objects in MATLAB Code Generation”
Toolbox
Supports MATLAB Function Block: Yes
computer MATLAB • Information about the computer on which the
code generation software is running.
• Use only when the code generation target is
S-function (Simulation) or MEX-function.
cond MATLAB —
conj MATLAB —
conj Fixed-Point —
Designer
conndef Image Processing Input arguments must be compile-time
Toolbox constants.

MATLAB Function Block support: Yes.


continue MATLAB —
conv MATLAB “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35

4-29
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


conv Fixed-Point • Variable-sized inputs are only supported
Designer 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 MATLAB and the
generated code.

• In generated code, the output for variable-


sized signals is 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.
conv2 MATLAB —
convenc Communications —
System Toolbox
convergent Fixed-Point —
Designer
convn MATLAB —
cordicabs Fixed-Point • Variable-size signals are not supported.
Designer
cordicangle Fixed-Point • Variable-size signals are not supported.
Designer
cordicatan2 Fixed-Point • Variable-size signals are not supported.
Designer
cordiccart2pol Fixed-Point • Variable-size signals are not supported.
Designer

4-30
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


cordiccexp Fixed-Point • Variable-size signals are not supported.
Designer
cordiccos Fixed-Point • Variable-size signals are not supported.
Designer
cordicpol2cart Fixed-Point • Variable-size signals are not supported.
Designer
cordicrotate Fixed-Point • Variable-size signals are not supported.
Designer
cordicsin Fixed-Point • Variable-size signals are not supported.
Designer
cordicsincos Fixed-Point • Variable-size signals are not supported.
Designer
cordicsqrt Fixed-Point • Variable-size signals are not supported.
Designer
cornerPoints Computer Vision Supports MATLAB Function block: No
System Toolbox To index locations with this object, use
the syntax: points.Location(idx,:),
for points object. See
visionRecovertformCodeGeneration_kernel.m,
which is used in the “Introduction to Code
Generation with Feature Matching and
Registration” example.
corrcoef MATLAB • Row-vector input is only supported when the
first two inputs are vectors and nonscalar.
cos MATLAB —
cos Fixed-Point —
Designer
cosd MATLAB —
cosh MATLAB —
cot MATLAB —

4-31
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


cotd MATLAB • In some cases, returns -Inf when MATLAB
returns Inf.
• In some cases, returns Inf when MATLAB
returns -Inf.
coth MATLAB —
cov MATLAB • If the input is variable-size and is [] at run
time, returns [] not NaN.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
cross MATLAB • If supplied, dim must be a constant.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
crossoverFilter Audio System “System Objects in MATLAB Code Generation”
Toolbox
Supports MATLAB Function Block: Yes
csc MATLAB —
cscd MATLAB • In some cases, returns -Inf when MATLAB
returns Inf.
• In some cases, returns Inf when MATLAB
returns -Inf.
csch MATLAB —
ctranspose MATLAB —
ctranspose Fixed-Point —
Designer
cummin MATLAB —
cummax MATLAB —
cumprod MATLAB Does not support logical inputs. Cast input to
double first.
cumsum MATLAB Does not support logical inputs. Cast input to
double first.

4-32
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


cumtrapz MATLAB —
db2pow Signal Processing —
Toolbox
dct Signal Processing • Code generation for this function requires the
Toolbox DSP System Toolbox software.
• 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.

Specifying constants

To specify a constant input for codegen, use


coder.Constant. For more information, see
“Specify Constant Inputs at the Command
Line” on page 21-52.
de2bi Communications —
System Toolbox
deal MATLAB —
deblank MATLAB • Supports only inputs from the char class.
Does not support cell arrays.
• Input values must be in the range 0-127.
dec2bin MATLAB • If input d is double, d must be less than
2^52.
• If input d is single, d must be less than
2^23.
• Unless you specify input n to be constant and
n is large enough that the output has a fixed
number of columns regardless of the input
values, this function requires variable-sizing
support. Without variable-sizing support,
n must be at least 52 for double, 23 for
single, 16 for char, 32 for int32, 16 for
int16, and so on.

4-33
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


dec2hex MATLAB • If input d is double, d must be less than
2^52.
• If input d is single, d must be less than
2^23.
• Unless you specify input n to be constant,
and n is large enough that the output has a
fixed number of columns regardless of the
input values, this function requires variable-
sizing support. Without variable-sizing
support, n must be at least 13 for double,
6 for single, 4 for char, 8 for int32, 4 for
int16, and so on.
dechirp Phased Array Does not support variable-size inputs.
System Toolbox
deconv MATLAB “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
deg2rad MATLAB —
del2 MATLAB —
delayseq Phased Array Does not support variable-size inputs.
System Toolbox
demosaic Image Processing The sensorAlignment argument must be a
Toolbox compile-time constant.

MATLAB Function Block support: Yes.


depressionang Phased Array Does not support variable-size inputs.
System Toolbox
designMultirateFIR DSP System The inputs to the function must be constants
Toolbox
designParamEQ Audio System Supports MATLAB Function Block: Yes
Toolbox
designShelvingEQ Audio System Supports MATLAB Function Block: Yes
Toolbox

4-34
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


designVarSlopeFilter Audio System Supports MATLAB Function Block: Yes
Toolbox
det MATLAB —
detectBRISKFeatures Computer Vision Supports MATLAB Function block: No
System Toolbox Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries.
“Portable C Code Generation for Functions That
Use OpenCV Library”
detectCheckerboard- Computer Vision Supports MATLAB Function block: No
Points System Toolbox Code generation will not support specifying
images as file names or cell arrays of file names.
It supports only checkerboard detection in
a single image or stereo pair of images. For
example, these syntaxes are supported:

• detectCheckerboardPoints(I1)
• detectCheckerobarPoints(I1,I2)

I1 and I2 are single grayscale or RGB images.


detectFASTFeatures Computer Vision Supports MATLAB Function block: No
System Toolbox Supports MATLAB Function block: No
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries.
“Portable C Code Generation for Functions That
Use OpenCV Library”Generated code for this
function uses a precompiled platform-specific
shared library.
detectHarrisFeatures Computer Vision Compile-time constant input: FilterSize
System Toolbox Supports MATLAB Function block: No
Generated code for this function uses a
precompiled platform-specific shared library.
detectMinEigenFeatures Computer Vision Compile-time constant input: FilterSize
System Toolbox Supports MATLAB Function block: No
Generated code for this function uses a
precompiled platform-specific shared library.

4-35
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


detectMSERFeatures Computer Vision Supports MATLAB Function block: No
System Toolbox Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries
“Portable C Code Generation for Functions That
Use OpenCV Library”
For code generation, the function outputs
regions.PixelList as an array. The region
sizes are defined in regions.Lengths.
detectSURFFeatures Computer Vision Supports MATLAB Function block: No
System Toolbox Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries.
“Portable C Code Generation for Functions That
Use OpenCV Library”
detrend MATLAB • If supplied and not empty, the input
argument bp must satisfy the following
requirements:

• Be real.
• Be sorted in ascending order.
• Restrict elements to integers in the
interval [1, n-2]. n is the number of
elements in a column of input argument X
, or the number of elements in X when X is
a row vector.
• Contain all unique values.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35

4-36
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


diag MATLAB • If supplied, the argument representing the
order of the diagonal matrix must be a real
and scalar integer value.
• For variable-size inputs that are variable-
length vectors (1-by-: or :-by-1), diag:

• Treats the input as a vector input.


• Returns a matrix with the given vector
along the specified diagonal.

• For variable-size inputs that are not variable-


length vectors, diag:

• Treats the input as a matrix.


• Does not support inputs that are vectors
at run time.
• Returns a variable-length vector.

If the input is variable-size (:m-by-:n) and


has shape 0-by-0 at run time, the output is
0-by-1 not 0-by-0. However, if the input is a
constant size 0-by-0, the output is [].
• For variable-size inputs that are not variable-
length vectors (1-by-: or :-by-1), diag treats
the input as a matrix from which to extract
a diagonal vector. This behavior occurs even
if the input array is a vector at run time. To
force diag to build a matrix from variable-
size inputs that are not 1-by-: or :-by-1, use:

• diag(x(:)) instead of diag(x)


• diag(x(:),k) instead of diag(x,k)
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35

4-37
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


diag Fixed-Point • If supplied, the index, k, must be a real and
Designer scalar integer value that is not a fi object.
diff MATLAB • If supplied, the arguments representing
the number of times to apply diff and
the dimension along which to calculate the
difference must be constants.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
disparity Computer Vision Compile-time constant input restriction:
System Toolbox 'Method'.
Supports MATLAB Function block: No
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries.
“Portable C Code Generation for Functions That
Use OpenCV Library”
divide Fixed-Point • Any non-fi input must be constant. Its value
Designer must be known at compile time so that it can
be cast to a fi object.
• Complex and imaginary divisors are not
supported.
• The syntax T.divide(a,b) is not
supported.
dop2speed Phased Array Does not support variable-size inputs.
System Toolbox
dopsteeringvec Phased Array Does not support variable-size inputs.
System Toolbox
dot MATLAB —
double MATLAB —
double Fixed-Point —
Designer
downsample Signal Processing —
Toolbox

4-38
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


dpskdemod Communications —
System Toolbox
dpskmod Communications —
System Toolbox
dpss 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
dsp.AdaptiveLatticeFilter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.AffineProjectionFilter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.AllpassFilter DSP System “System Objects in MATLAB Code Generation”
Toolbox
The System object™ supports code generation
only when the Structure property is set to
Minimum multiplier or Lattice.
dsp.AllpoleFilter DSP System • “System Objects in MATLAB Code
Toolbox Generation”
• Only the Denominator property is tunable
for code generation.
dsp.AnalyticSignal DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.ArrayPlot DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.ArrayVectorAdder DSP System “System Objects in MATLAB Code Generation”
Toolbox

4-39
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


dsp.ArrayVectorDivider DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.ArrayVectorMultiplier DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.ArrayVectorSubtractor DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.AudioFileReader DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.AudioFileWriter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.Autocorrelator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.BiquadFilter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.BurgAREstimator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.BurgSpectrumEstimator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.CepstralToLPC DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.CICCompensation- DSP System “System Objects in MATLAB Code Generation”
Decimator Toolbox
dsp.CICCompensation- DSP System “System Objects in MATLAB Code Generation”
Interpolator Toolbox
dsp.CICDecimator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.CICInterpolator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.Convolver DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.Counter DSP System “System Objects in MATLAB Code Generation”
Toolbox

4-40
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


dsp.Crosscorrelator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.CrossSpectrumEstimator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.CumulativeProduct DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.CumulativeSum DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.DCBlocker DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.DCT DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.Delay DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.DelayLine DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.Differentiator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.DigitalDownConverter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.DigitalUpConverter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.DigitalFilter DSP System • “System Objects in MATLAB Code
Toolbox Generation”
• The SOSMatrix and Scalevalues
properties are not supported for code
generation.
dsp.FarrowRateConverter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.FastTransversalFilter DSP System “System Objects in MATLAB Code Generation”
Toolbox

4-41
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


dsp.FFT DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.FilterCascade DSP System • You cannot generate code directly from
Toolbox dsp.FilterCascade. You can use the
generateFilteringCode method to
generate a MATLAB function. You can
generate C/C++ code from this MATLAB
function.

“System Objects in MATLAB Code Generation”


dsp.FilteredXLMSFilter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.FIRDecimator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.FIRFilter DSP System • “System Objects in MATLAB Code
Toolbox Generation”
• Only the Numerator property is tunable for
code generation.
dsp.FIRHalfbandDecimator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.FIRHalfbandInterpolator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.FIRInterpolator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.FIRRateConverter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.FrequencyDomain- DSP System “System Objects in MATLAB Code Generation”
AdaptiveFilter Toolbox
dsp.HighpassFilter DSP System “System Objects in MATLAB Code Generation”
Toolbox

4-42
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


dsp.Histogram DSP System • This object has no tunable properties for code
Toolbox generation.
• “System Objects in MATLAB Code
Generation”
dsp.IDCT DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.IFFT DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.IIRFilter DSP System • Only the Numerator and Denominator
Toolbox properties are tunable for code generation.
• “System Objects in MATLAB Code
Generation”
dsp.IIRHalfbandDecimator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.IIRHalfbandInterpolator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.Interpolator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.KalmanFilter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.LDLFactor DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.LevinsonSolver DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.LMSFilter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.LowerTriangularSolver DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.LowpassFilter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.LPCToAutocorrelation DSP System “System Objects in MATLAB Code Generation”
Toolbox

4-43
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


dsp.LPCToCepstral DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.LPCToLSF DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.LPCToLSP DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.LPCToRC DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.LSFToLPC DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.LSPToLPC DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.LUFactor DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.Maximum DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.Mean DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.Median DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.Minimum DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.NCO DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.Normalizer DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.PeakFinder DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.PeakToPeak DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.PeakToRMS DSP System “System Objects in MATLAB Code Generation”
Toolbox

4-44
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


dsp.PhaseExtractor DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.PhaseUnwrapper DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.RCToAutocorrelation DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.RCToLPC DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.RMS DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.RLSFilter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.SampleRateConverter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.ScalarQuantizerDecoder DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.ScalarQuantizerEncoder DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.SignalSource DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.SineWave DSP System • This object has no tunable properties for code
Toolbox generation.
• “System Objects in MATLAB Code
Generation”
dsp.SpectrumAnalyzer DSP System This System object does not generate code. It is
Toolbox automatically declared as an extrinsic variable
using the coder.extrinsic function.
dsp.SpectrumEstimator DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.StandardDeviation DSP System “System Objects in MATLAB Code Generation”
Toolbox

4-45
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


dsp.StateLevels DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.SubbandAnalysisFilter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.SubbandSynthesisFilter DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.TimeScope DSP System This System object does not generate code. It is
Toolbox automatically declared as an extrinsic variable
using the coder.extrinsic function.
dsp.TransferFunction- DSP System “System Objects in MATLAB Code Generation”
Estimator Toolbox
dsp.UDPReceiver DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.UDPSender DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.UpperTriangularSolver DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.VariableBandwidth- DSP System “System Objects in MATLAB Code Generation”
FIRFilter Toolbox
dsp.VariableBandwidth- DSP System “System Objects in MATLAB Code Generation”
IIRFilter Toolbox
dsp.VariableFractionDelay DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.VariableIntegerDelay DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.Variance DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.VectorQuantizerDecoder DSP System “System Objects in MATLAB Code Generation”
Toolbox
dsp.VectorQuantizerEncoder DSP System “System Objects in MATLAB Code Generation”
Toolbox

4-46
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


dsp.Window DSP System • This object has no tunable properties for code
Toolbox generation.
• “System Objects in MATLAB Code
Generation”
dsp.ZeroCrossingDetector DSP System “System Objects in MATLAB Code Generation”
Toolbox
edge Image Processing The method, direction, and sigma arguments
Toolbox must be a compile-time constants. In addition,
nonprogrammatic syntaxes are not supported.
For example, the syntax edge(im), where edge
does not return a value but displays an image
instead, is not supported.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The


input arguments thresh and sigma must be
compile-time constants.
effearthradius Phased Array Does not support variable-size inputs.
System Toolbox

4-47
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


eig MATLAB • For code generation,QZ algorithm is
used in all cases. MATLAB can use
different algorithms for different inputs.
Consequently, V might represent a different
basis of eigenvectors. The eigenvalues in
D might not be in the same order as in
MATLAB.
• With one input, [V,D] = eig(A), the
results are similar to those obtained using
[V,D] = eig(A,eye(size(A)),'qz') in
MATLAB, except that the columns of V are
normalized.
• Options 'balance', and 'nobalance' are
not supported for the standard eigenvalue
problem. 'chol' is not supported for the
symmetric generalized eigenvalue problem.
• Outputs are of complex type.
• Does not support the option to calculate left
eigenvectors.
ellip Signal Processing 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
“Specify Constant Inputs at the Command Line”
on page 21-52.

4-48
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


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
“Specify Constant Inputs at the Command Line”
on page 21-52.
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
“Specify Constant Inputs at the Command Line”
on page 21-52.
end MATLAB —
end Fixed-Point —
Designer
epipolarLine Computer Vision Supports MATLAB Function block: Yes
System Toolbox
eps MATLAB —
eps Fixed-Point • Supported for scalar fixed-point signals only.
Designer • Supported for scalar, vector, and matrix, fi
single and fi double signals.
eq MATLAB —
eq Fixed-Point Not supported for fixed-point signals with
Designer different biases.
erf MATLAB —

4-49
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


erfc MATLAB —
erfcinv MATLAB —
erfcx MATLAB —
erfinv MATLAB —
error MATLAB Has no effect in standalone code even when run-
time error detection is enabled. See “Run-Time
Error Detection and Reporting in Standalone C/
C++ Code” on page 22-29.
espritdoa Phased Array Does not support variable-size inputs.
System Toolbox
estimateFundamental- Computer Vision Compile-time constant input: Method,
Matrix System Toolbox OutputClass, DistanceType, and
ReportRuntimeError.
Supports MATLAB Function block: Yes
estimateGeometric- Computer Vision Supports MATLAB Function block: No
Transform System Toolbox
estimateUncalibrated- Computer Vision Supports MATLAB Function block: Yes
Rectification System Toolbox
eul2quat Robotics System Supports MATLAB Function block: Yes
Toolbox
eul2rotm Robotics System Supports MATLAB Function block: Yes
Toolbox
eul2tform Robotics System Supports MATLAB Function block: Yes
Toolbox
evcdf Statistics —
and Machine
Learning Toolbox
evinv Statistics —
and Machine
Learning Toolbox
evpdf Statistics —
and Machine
Learning Toolbox

4-50
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


evrnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
evstat Statistics —
and Machine
Learning Toolbox
exp MATLAB —
expander Audio System “System Objects in MATLAB Code Generation”
Toolbox
Supports MATLAB Function Block: Yes
expcdf Statistics —
and Machine
Learning Toolbox
expint MATLAB —
expinv Statistics —
and Machine
Learning Toolbox
expm MATLAB —
expm1 MATLAB —
exppdf Statistics —
and Machine
Learning Toolbox
exprnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
expstat Statistics —
and Machine
Learning Toolbox

4-51
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


extractFeatures Computer Vision Compile-time constant input restrictions:
System Toolbox 'Method'
Supports MATLAB Function block: Yes for
Block method only.
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries for
BRISK, FREAK, and SURF Methods.
“Portable C Code Generation for Functions That
Use OpenCV Library”
extractHOGFeatures Computer Vision Supports MATLAB Function block: No
System Toolbox
extractLBPFeatures Computer Vision Generates platform-dependent library: No
System Toolbox Supports MATLAB Function block: Yes
extrinsics Computer Vision Supports MATLAB Function block: No
System Toolbox
eye MATLAB • classname must be a built-in MATLAB
numeric type. Does not invoke the static
eye method for other classes. For example,
eye(m, n, 'myclass’) does not invoke
myclass.eye(m,n).
• Size arguments must have a fixed size.
factor MATLAB • The maximum double precision input is
2^33.
• The maximum single precision input is 2^25.
• The input n cannot have type int64 or
uint64.
factorial MATLAB —
false MATLAB • Dimensions must be real, nonnegative,
integers.
fcdf Statistics —
and Machine
Learning Toolbox
fclose MATLAB —

4-52
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


feof MATLAB —
fft MATLAB • “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
fft2 MATLAB —
fftn MATLAB The siz argument must have a fixed size.
fftshift MATLAB —
fi Fixed-Point • Use to create a fixed-point constant or
Designer variable.
• The default constructor syntax without input
arguments is not supported.
• The rand
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...).
• If the input value is not known at
compile time, you must provide complete
numerictype information.
• All properties related to data type must be
constant for code generation.
• numerictype object information must be
available for non-fixed-point Simulink inputs.
fieldnames MATLAB Does not support objects. The input must be a
structure.
filter MATLAB • If supplied, dim must be a constant.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35

4-53
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


filter Fixed-Point • Variable-sized inputs are only supported
Designer when the SumMode property of the governing
fimath is set to Specify precision or
Keep LSB.
filter2 MATLAB —
filtfilt 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
fimath Fixed-Point • Fixed-point signals coming in to a MATLAB
Designer 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.
• If the ProductMode property of the
fimath object is set to anything other than
FullPrecision, the ProductWordLength
and ProductFractionLength properties
must be constant.
• If the SumMode property of the fimath
object is set to anything other than
FullPrecision, the SumWordLength and
SumFractionLength properties must be
constant.

4-54
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


find MATLAB • Issues an error if a variable-size input
becomes a row vector at run time.

Note: This limitation does not apply when


the input is scalar or a variable-length row
vector.
• For variable-size inputs, the shape of empty
outputs, 0-by-0, 0-by-1, or 1-by-0, depends on
the upper bounds of the size of the input. The
output might not match MATLAB when the
input array is a scalar or [] at run time. If the
input is a variable-length row vector, the size
of an empty output is 1-by-0, otherwise it is
0-by-1.
• Always returns a variable-length vector.
Even when you provide the output vector k,
the output cannot be fixed-size because the
output can contain fewer than k elements.
For example, find(x,1) returns a variable-
length vector with 1 or 0 elements.
findpeaks Signal Processing —
Toolbox
finv Statistics —
and Machine
Learning Toolbox
fir1 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
“Specify Constant Inputs at the Command Line”
on page 21-52.

4-55
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


fir2 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
firceqrip DSP System All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
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
“Specify Constant Inputs at the Command Line”
on page 21-52.
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
“Specify Constant Inputs at the Command Line”
on page 21-52.
fireqint DSP System All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.

4-56
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


firgr DSP System • All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
• Does not support syntaxes that have cell
array input.
firhalfband DSP System All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
firlpnorm DSP System • All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
• Does not support syntaxes that have cell
array input.
firls 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
firminphase DSP System All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
firnyquist DSP System All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
firpr2chfb DSP System All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.

4-57
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


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
“Specify Constant Inputs at the Command Line”
on page 21-52.
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
“Specify Constant Inputs at the Command Line”
on page 21-52.
fitgeotrans Image Processing The transformtype argument must be
Toolbox a compile-time constant. The function
supports the following transformation
types: 'nonreflectivesimilarity',
'similarity', 'affine', or 'projective'.

MATLAB Function Block support: Yes.


fix MATLAB —
fix Fixed-Point —
Designer
fixed.Quantizer Fixed-Point —
Designer

4-58
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


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
“Specify Constant Inputs at the Command Line”
on page 21-52.
flintmax MATLAB —
flip MATLAB Does not support cell arrays for the first
argument.
flip Fixed-Point The dimensions argument must be a built-in
Designer type; it cannot be a fi object.
flipdim MATLAB Does not support cell arrays for the first
argument.
fliplr MATLAB Does not support cell arrays.
fliplr Fixed-Point —
Designer
flipud MATLAB Does not support cell arrays.
flipud Fixed-Point —
Designer
floor MATLAB —
floor Fixed-Point —
Designer
fminsearch MATLAB • Ignores the Display option. Does not print
status information during execution. Test the
exitflag output for the exit condition.
• The output structure does not include the
algorithm or message fields.
• Ignores the OutputFcn and PlotFcns
options.

4-59
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


fogpl Phased Array Does not support variable-size inputs.
System Toolbox

4-60
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


fopen MATLAB • Does not support:

• machineformat, encoding, or fileID


inputs
• message output
• fopen('all')
• If you disable extrinsic calls, you cannot
return fileIDs created with fopen to
MATLAB or extrinsic functions. You can use
such fileIDs only internally.
• When generating C/C++ executables, static
libraries, or dynamic libraries, you can open
up to 20 files.
• The generated code does not report errors
from invalid file identifiers. Write your own
file open error handling in your MATLAB
code. Test whether fopen returns -1,
which indicates that the file open failed. For
example:
...
fid = fopen(filename, 'r');
if fid == -1
% fopen failed

else
% fopen successful, okay to call fread
A = fread(fid);
...
• The behavior of the generated code for fread
is compiler-dependent if you:

1 Open a file using fopen with a


permission of a+.
2 Read the file using fread before calling
an I/O function, such as fseek or

4-61
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


frewind, that sets the file position
indicator.
for MATLAB —
for Fixed-Point —
Designer
fpdf Statistics —
and Machine
Learning Toolbox

4-62
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


fprintf MATLAB • Does not support:

• b and t subtypes on %u, %o %x, and %X


formats.
• $ flag for reusing input arguments.
• printing arrays.
• There is no automatic casting. Input
arguments must match their format types for
predictable results.
• Escaped characters are limited to the decimal
range of 0–127.
• A call to fprintf with fileID equal to 1 or
2 becomes printf in the generated C/C++
code in the following cases:

• The fprintf call is inside a parfor loop.


• Extrinsic calls are disabled.
• When the MATLAB behavior differs from the
C compiler behavior, fprintf matches the C
compiler behavior in the following cases:

• The format specifier has a corresponding


C format specifier, for example, %e or %E.

• The fprintf call is inside a parfor loop.


• Extrinsic calls are disabled.
• When you call fprintf with the format
specifier %s, do not put a null character
in the middle of the input string. Use
fprintf(fid, '%c', char(0)) to write a
null character.
• When you call fprintf with an integer
format specifier, the type of the integer
argument must be a type that the target
hardware can represent as a native C type.
For example, if you call fprintf('%d',

4-63
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


int64(n)), the target hardware must
have a native C type that supports a 64-bit
integer.

4-64
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


fread MATLAB • precision must be a constant.
• The source and output that precision
specifies cannot have values long, ulong,
unsigned long, bitN, or ubitN.
• You cannot use the machineformat input.
• If the source or output that precision
specifies is a C type, for example, int, the
target and production sizes for that type
must:

• Match.
• Map directly to a MATLAB type.
• The source type that precision specifies
must map directly to a C type on the target
hardware.
• If the fread call reads the entire file, all
of the data must fit in the largest array
available for code generation.
• If sizeA is not constant or contains a
nonfinite element, then dynamic memory
allocation is required.
• Treats a char value for source or output
as a signed 8-bit integer. Use values between
0 and 127 only.
• The generated code does not report file
read errors. Write your own file read error
handling in your MATLAB code. Test that
the number of bytes read matches the
number of bytes that you requested. For
example:
...
N = 100;
[vals, numRead] = fread(fid, N, '*double');
if numRead ~= N
% fewer elements read than expected

4-65
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


end
...
freqspace MATLAB —
freqz Signal Processing • Does not support variable-size inputs.
Toolbox • When called with no output arguments,
and without a semicolon at the end, freqz
returns the complex frequency response of
the input filter, evaluated at 512 points.

If the semicolon is added, the function


produces a plot of the magnitude and phase
response of the filter.

See “freqz With No Output Arguments”.


frewind MATLAB —
frnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
fspecial Image Processing Inputs must be compile-time constants.
Toolbox Expressions or variables are allowed if their
values do not change.

MATLAB Function Block support: Yes. The


input arguments hsize, radius, len, and
theta must be compile-time constants.
fspl Phased Array Does not support variable-size inputs.
System Toolbox
fstat Statistics —
and Machine
Learning Toolbox
full MATLAB —

4-66
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


fzero MATLAB • The first argument must be a function
handle. Does not support structure, inline
function, or string inputs for the first
argument.
• Supports up to three output arguments. Does
not support the fourth output argument (the
output structure).
gain2aperture Phased Array Does not support variable-size inputs.
System Toolbox
gamcdf Statistics —
and Machine
Learning Toolbox
gaminv Statistics —
and Machine
Learning Toolbox
gamma MATLAB —
gammainc MATLAB Output is always complex.
gammaincinv MATLAB Output is always complex.
gammaln MATLAB —
gampdf Statistics —
and Machine
Learning Toolbox
gamrnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
gamstat Statistics —
and Machine
Learning Toolbox
gaspl Phased Array Does not support variable-size inputs.
System Toolbox

4-67
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


gausswin Signal Processing Allgaspl inputs must be 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
gccphat Phased Array Does not support variable-size inputs.
System Toolbox
gcd MATLAB —
ge MATLAB —
ge Fixed-Point • Not supported for fixed-point signals with
Designer different biases.
generateCheckerboard- Computer Vision Supports MATLAB Function block: No
Points System Toolbox
geocdf Statistics —
and Machine
Learning Toolbox
geoinv Statistics —
and Machine
Learning Toolbox
geomean Statistics —
and Machine
Learning Toolbox
geopdf Statistics —
and Machine
Learning Toolbox

4-68
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


geornd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
geostat Statistics —
and Machine
Learning Toolbox
get Fixed-Point • The syntax structure = get(o) is not
Designer supported.
getlsb Fixed-Point —
Designer
getmsb Fixed-Point —
Designer
getrangefromclass Image Processing MATLAB Function Block support: Yes.
Toolbox
gevcdf Statistics —
and Machine
Learning Toolbox
gevinv Statistics —
and Machine
Learning Toolbox
gevpdf Statistics —
and Machine
Learning Toolbox
gevrnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.

4-69
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


gevstat Statistics —
and Machine
Learning Toolbox
global2localcoord Phased Array Does not support variable-size inputs.
System Toolbox
gpcdf Statistics —
and Machine
Learning Toolbox
gpinv Statistics —
and Machine
Learning Toolbox
gppdf Statistics —
and Machine
Learning Toolbox
gprnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
gpstat Statistics —
and Machine
Learning Toolbox
gradient MATLAB —
grayconnected Image Processing If you choose the generic MATLAB Host
Toolbox Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


grazingang Phased Array Does not support variable-size inputs.
System Toolbox
gt MATLAB —
gt Fixed-Point • Not supported for fixed-point signals with
Designer different biases.

4-70
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


hadamard MATLAB n must be a fixed-size scalar.
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
“Specify Constant Inputs at the Command Line”
on page 21-52.
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
“Specify Constant Inputs at the Command Line”
on page 21-52.
harmmean Statistics —
and Machine
Learning Toolbox
hdl.RAM MATLAB —
hex2dec MATLAB Does not support cell arrays.
hex2num MATLAB • Does not support cell arrays.
• For n = hex2num(S), size(S,2) <=
length(num2hex(0))
hilb MATLAB —

4-71
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


hist MATLAB • Histogram bar plotting not supported. Call
with at least one output argument.
• If supplied, the second argument x must be a
scalar constant.
• Inputs must be real.

For the syntax [nout, xout] = hist(y,x):

• When y is a fixed-size vector or variable-


length vector:

• nout is always a row vector.


• If x is a vector, xout is a vector with the
same orientation as x.
• If x is a scalar (fixed-size), xout is a row
vector.
• nout and xout are column vectors when the
following conditions are true:

• y is a matrix
• size(y,1) and size(y,2) do not have
fixed length 1
• One of size(y,1) and size(y,2) has
length 1 at run time
• A variable-size x is interpreted as a vector
input even if it is a scalar at run time.
• If at least one of the inputs is empty, vector
orientations in the output can differ from
MATLAB.

4-72
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


histc MATLAB • The output of a variable-size array that
becomes a column vector at run time is a
column-vector, not a row-vector.
• If supplied, dim must be a constant.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
histeq Image Processing All the syntaxes that include indexed images are
Toolbox not supported. This includes all syntaxes that
accept map as input and return newmap.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The


input argument N must be a compile-time
constant.
hom2cart Robotics System Supports MATLAB Function block: Yes
Toolbox
horizonrange Phased Array Does not support variable-size inputs.
System Toolbox
horzcat Fixed-Point —
Designer
hough Image Processing The optional parameter names 'Theta' and
Toolbox 'RhoResolution' must be compile-time string
constants. The optional Theta vector must have
a bounded size.

MATLAB Function Block support: Yes. The


input argument BW must be fixed size, the
RhoResolution parameter must be a compile-
time constant, and the Theta vector must have
a bounded size.

4-73
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


houghlines Image Processing The optional parameter names 'FillGap'
Toolbox and 'MinLength' must be compile-time string
constants. Their associated values need not be
compile-time constants.

MATLAB Function Block support: No.


houghpeaks Image Processing The optional parameter names 'Threshold'
Toolbox and 'NHoodSize' must be compile-time string
constants. Their associated values need not be
compile-time constants.

MATLAB Function Block support: Yes.


hygecdf Statistics —
and Machine
Learning Toolbox
hygeinv Statistics —
and Machine
Learning Toolbox
hygepdf Statistics —
and Machine
Learning Toolbox
hygernd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
hygestat Statistics —
and Machine
Learning Toolbox
hypot MATLAB —
icdf Statistics —
and Machine
Learning Toolbox

4-74
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


idct Signal Processing • Code generation for this function requires the
Toolbox DSP System Toolbox software.
• 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.

Specifying constants

To specify a constant input for codegen, use


coder.Constant. For more information, see
“Specify Constant Inputs at the Command
Line” on page 21-52.
if, elseif, else MATLAB —
idivide MATLAB • For efficient generated code, MATLAB rules
for divide by zero are supported only for the
'round' option.
ifft MATLAB • Output is complex.
• Does not support the 'symmetric' option.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
ifft2 MATLAB • Does not support the 'symmetric' option.
ifftn MATLAB • Does not support the 'symmetric' option.
• The siz argument must have a fixed size.
ifftshift MATLAB —
ifir DSP System All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
iircomb DSP System All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.

4-75
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


iirgrpdelay DSP System • All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
• Does not support syntaxes that have cell
array input.
iirlpnorm DSP System • All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
• Does not support syntaxes that have cell
array input.
iirlpnormc DSP System • All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
• Does not support syntaxes that have cell
array input.
iirnotch DSP System All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
iirpeak DSP System All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
im2double MATLAB MATLAB Function Block support: Yes.
im2int16 Image Processing If you choose the generic MATLAB Host
Toolbox Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


im2single Image Processing MATLAB Function Block support: Yes.
Toolbox
im2uint8 Image Processing If you choose the generic MATLAB Host
Toolbox Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-76
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


im2uint16 Image Processing If you choose the generic MATLAB Host
Toolbox Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imabsdiff Image Processing MATLAB Function Block support: Yes.
Toolbox
imadjust Image Processing Does not support syntaxes that include indexed
Toolbox images. This includes all syntaxes that accept
map as input and return newmap.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imag MATLAB —
imag Fixed-Point —
Designer
imaq.VideoDevice Image “Code Generation with VideoDevice System
Acquisition Object”
Toolbox
imbinarize Image Processing String input arguments must be compile-time
Toolbox constants.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-77
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


imbothat Image Processing The input image IM must be either 2-D or 3-D
Toolbox image. The structuring element input argument
SE must be a compile-time constant.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imboxfilt Image Processing MATLAB Function Block support: Yes.
Toolbox
imclearborder Image Processing The optional second input argument, conn, must
Toolbox be a compile-time constant. Supports only up to
3-D inputs.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imclose Image Processing The input image IM must be either 2-D or 3-D
Toolbox image. The structuring element input argument
SE must be a compile-time constant.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imcomplement Image Processing Does not support int64 and uint64 data types.
Toolbox
MATLAB Function Block support: Yes.

4-78
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


imcrop Image Processing The interactive syntaxes, such as I2 = imcrop,
Toolbox are not supported. Indexed images are not
supported, including the noninteractive syntax
X2 = imcrop(X,map,rect);.

MATLAB Function Block support: Yes.


imdilate Image Processing The input image IM must be either 2-D or 3-
Toolbox D image. The SE, PACKOPT, and SHAPE input
arguments must be a compile-time constant.
The structuring element argument SE must be a
single element—arrays of structuring elements
are not supported. To obtain the same result
as that obtained using an array of structuring
elements, call the function sequentially.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imerode Image Processing The input image IM must be either 2-D or 3-
Toolbox D image. The SE, PACKOPT, and SHAPE input
arguments must be a compile-time constant.
The structuring element argument SE must be a
single element—arrays of structuring elements
are not supported. To obtain the same result
as that obtained using an array of structuring
elements, call the function sequentially.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-79
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


imextendedmax Image Processing The optional third input argument, conn, must
Toolbox be a compile-time constant.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imextendedmin Image Processing The optional third input argument, conn, must
Toolbox be a compile-time constant.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-80
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


imfill Image Processing The optional input connectivity, conn and the
Toolbox string 'holes' must be compile-time constants.

Supports only up to 3-D inputs.

The interactive mode to select points,


imfill(BW,0,CONN) is not supported in code
generation.

locations can be a P-by-1 vector, in which


case it contains the linear indices of the
starting locations. locations can also be a P-
by-ndims(I) matrix, in which case each row
contains the array indices of one of the starting
locations. Once you select a format at compile-
time, you cannot change it at run time. However,
the number of points in locations can be varied
at run time.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imfilter Image Processing The input image can be either 2-D or 3-D. The
Toolbox value of the input argument, options, must be
a compile-time constant.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-81
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


imfindcircles Image Processing All string input arguments and values must be
Toolbox compile-time constants.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: No.


imgaborfilt Image Processing MATLAB Function Block support: No.
Toolbox
imgaussfilt Image Processing String input arguments must be compile-time
Toolbox constants.

When FilterDomain is 'spatial’, if you


choose the generic MATLAB Host Computer
target platform, generated code uses a
precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imgradient3 Image Processing String input arguments must be compile-time
Toolbox constants.

MATLAB Function Block support: Yes.


imgradientxyz Image Processing String input arguments must be compile-time
Toolbox constants.

MATLAB Function Block support: Yes.

4-82
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


imhist Image Processing The optional second input argument, n, must
Toolbox be a compile-time constant. In addition,
nonprogrammatic syntaxes are not supported.
For example, the syntaxes where imhist
displays the histogram are not supported.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The


input argument N must be a compile-time
constant.
imhmax Image Processing The optional third input argument, conn, must
Toolbox be a compile-time constant

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imhmin Image Processing The optional third input argument, conn, must
Toolbox be a compile-time constant

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imlincomb Image Processing The output_class argument must be a
Toolbox compile-time constant. You can specify up to
four input image arguments.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-83
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


immse Image Processing MATLAB Function Block support: Yes.
Toolbox
imopen Image Processing The input image IM must be either 2-D or 3-D
Toolbox image. The structuring element input argument
SE must be a compile-time constant.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imoverlay Image Processing If you specify the 'color' argument as a string,
Toolbox it must be a compile-time constant.

MATLAB Function Block support: Yes.


impyramid Image Processing The direction argument must be a compile-
Toolbox time constant.

MATLAB Function Block support: Yes. The


input argument direction must be a compile-
time constant.
imquantize Image Processing MATLAB Function Block support: Yes.
Toolbox
imread Image Processing Supports reading of 8-bit JPEG images only.
Toolbox The file name input argument must be a valid
absolute path or relative path.

This function generates code that uses a


precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The file


name input argument must be a compile-time
constant.

4-84
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


imreconstruct Image Processing The optional third input argument, conn, must
Toolbox be a compile-time constant.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imref2d Image Processing The XWorldLimits, YWorldLimits and
Toolbox ImageSize properties can be set only during
object construction. When generating code, you
can only specify single objects—arrays of objects
are not supported.

MATLAB Function Block support: Yes.


imref3d Image Processing The XWorldLimits, YWorldLimits,
Toolbox ZWorldLimits and ImageSize properties can
be set only during object construction. When
generating code, you can only specify single
objects—arrays of objects are not supported.

MATLAB Function Block support: Yes.


imregionalmax Image Processing The optional second input argument, conn, must
Toolbox be a compile-time constant.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imregionalmin Image Processing The optional second input argument, conn, must
Toolbox be a compile-time constant.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-85
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


imresize Image Processing Does not support indexed images or custom
Toolbox interpolation kernels. All parameter-value
pair input arguments must be compile-time
constants.

MATLAB Function Block support: Yes. The


input arguments Scale and method must
be compile-time constants, and the values of
the OutputSize parameter, numrows and
numcols, must be compile-time constants.
imrotate Image Processing The method and bbox input argument values
Toolbox must be compile-time constants.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The


input argument angle must be a compile-time
constant.
imtophat Image Processing The input image IM must be either 2-D or 3-D
Toolbox image. The structuring element input argument
SE must be a compile-time constant.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-86
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


imtranslate Image Processing The supports only 2-D translation vectors. 3-D
Toolbox translations are not supported

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The


input argument translation must be a
compile-time constant.
imwarp Image Processing The geometric transformation object
Toolbox input, tform, must be either affine2d or
projective2d. Additionally, the interpolation
method and optional parameter names must be
string constants.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The


input argument tform must be a compile-time
constant.
ind2sub MATLAB • The first argument should be a valid size
vector. Size vectors for arrays with more than
intmax elements are not supported.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
inf MATLAB • Dimensions must be real, nonnegative,
integers.
insertMarker Computer Vision Compile-time constant input: 'Shape' and
System Toolbox 'Color'
Supports MATLAB Function block: Yes

4-87
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


insertObjectAnnotation Computer Vision Supports MATLAB Function block: Yes
System Toolbox Limitation: Input image must be bounded, see
“Specify Variable-Size Data Without Dynamic
Memory Allocation”
“System Objects in MATLAB Code Generation”
insertShape Computer Vision Compile-time constant input: 'Color' and
System Toolbox 'SmoothEdges'
Supports MATLAB Function block: Yes
insertText Computer Vision Compile-time constant input: Font, FontSize
System Toolbox Supports non-ASCII characters: No
Supports MATLAB Function block: Yes
int8, int16, int32, int64 MATLAB —
int8, int16, int32, int64 Fixed-Point —
Designer
integralBoxFilter Image Processing The 'NormalizationFactor' parameter must
Toolbox be a compile-time constant.

MATLAB Function Block support: Yes. The


input argument filtersize must be a compile-
time constant.
integralImage Computer Vision Supports MATLAB Function block: Yes
System Toolbox

4-88
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


interp1 MATLAB • Does not support the 'cubic' method.
Instead, use 'v5cubic' or 'spline'.
• The input argument x (sample points) must
be strictly increasing or strictly decreasing.
Indices are not reordered.
• If the input argument v (sample values) is a
variable-length vector (1-by-: or :-by-1), the
shape of the output vq matches the shape in
MATLAB.

If the input argument v is variable-size, is


not a variable-length vector, and becomes a
row vector at run time, an error occurs.
• If the input argument xq (query points) is
variable-size, is not a variable-length vector,
and becomes a row or column vector at run
time, an error occurs.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
interp1q MATLAB Might not match MATLAB when some Y values
are Inf or NaN.

4-89
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


interp2 MATLAB • Xq and Yq must be the same size. Use
meshgrid to evaluate on a grid.
• For best results, provide X and Y as vectors.
• For the 'cubic' method, reports an error if
the grid does not have uniform spacing. In
this case, use the 'spline' method.
• For best results when you use the 'spline'
method:

• Use meshgrid to create the inputs Xq


and Yq.
• Use a small number of interpolation
points relative to the dimensions of V.
Interpolating over a large set of scattered
points can be inefficient.
interp3 MATLAB • Xq, Yq, and Zq must be the same size. Use
meshgrid to evaluate on a grid.
• For best results, provide X, Y, and Z as
vectors.
• For the 'cubic' method, reports an error if
the grid does not have uniform spacing. In
this case, use the 'spline' method.
• For best results when you use the 'spline'
method:

• Use meshgrid to create the inputs Xq,


Yq, and Zq.
• Use a small number of interpolation
points relative to the dimensions of V.
Interpolating over a large set of scattered
points can be inefficient.

4-90
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


interpn MATLAB • For best results, provide X1,X2,...,Xn as
vectors.
• Does not support the 'cubic' or 'spline'
methods for 2-D and higher interpolation.
• The interpolation method must be a constant
string.

4-91
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


intersect MATLAB • Does not support cell arrays for the first or
second arguments.
• When you do not specify the 'rows' option:

• Inputs A and B must be vectors. If you


specify the 'legacy' option, inputs A and
B must be row vectors.
• The first dimension of a variable-size
row vector must have fixed length 1.
The second dimension of a variable-size
column vector must have fixed length 1.
• The input [] is not supported. Use a
1-by-0 or 0-by-1 input, for example,
zeros(1,0), to represent the empty set.
• If you specify the 'legacy' option, empty
outputs are row vectors, 1-by-0, never 0-
by-0.
• When you specify both the 'legacy' option
and the 'rows' option, the outputs ia and
ib are column vectors. If these outputs are
empty, they are 0-by-1, never 0-by-0, even if
the output C is 0-by-0.
• When the setOrder is 'sorted' or when
you specify the 'legacy' option, the inputs
must already be sorted in ascending order.
The first output, C, is sorted in ascending
order.
• Complex inputs must be single or double.
• When one input is complex and the other
input is real, do one of the following:

• Set setOrder to 'stable'.


• Sort the real input in complex
ascending order (by absolute
value). Suppose the real input

4-92
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


is x. Use sort(complex(x))or
sortrows(complex(x)).
• “Code Generation for Complex Data with
Zero-Valued Imaginary Parts” on page
6-4.
intfilt 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
intlut Image Processing If you choose the generic MATLAB Host
Toolbox Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


intmax MATLAB —
intmin MATLAB —
inv MATLAB Singular matrix inputs can produce nonfinite
values that differ from MATLAB results.
invhilb MATLAB —
ipermute MATLAB • Does not support cell arrays for the first
argument.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
ipermute Fixed-Point —
Designer

4-93
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


iptcheckconn Image Processing Input arguments must be compile-time
Toolbox constants.

MATLAB Function Block support: Yes.


iptcheckmap Image Processing MATLAB Function Block support: Yes.
Toolbox
iqcoef2imbal Communications —
System Toolbox
iqimbal2coef Communications —
System Toolbox
iqr Statistics —
and Machine
Learning Toolbox
isa MATLAB —
isbanded MATLAB —
iscell MATLAB —
iscellstr MATLAB —
ischar MATLAB —
iscolumn MATLAB —
iscolumn Fixed-Point —
Designer
isdeployed MATLAB • Returns true and false as appropriate for
Compiler MEX and SIM targets
• Returns false for other targets
isdiag MATLAB —
isempty MATLAB —
isempty Fixed-Point —
Designer
isEpipoleInImage Computer Vision Supports MATLAB Function block: Yes
System Toolbox
isequal MATLAB —

4-94
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


isequal Fixed-Point —
Designer
isequaln MATLAB —
isfi Fixed-Point —
Designer
isfield MATLAB • Does not support cell arrays for the second
argument
isfimath Fixed-Point —
Designer
isfimathlocal Fixed-Point —
Designer
isfinite MATLAB —
isfinite Fixed-Point —
Designer
isfloat MATLAB —
ishermitian MATLAB —
isinf MATLAB —
isinf Fixed-Point —
Designer
isinteger MATLAB —
isletter MATLAB • Input values from the char class must be in
the range 0-127.
islogical MATLAB —
ismac MATLAB • Returns true or false based on the MATLAB
version used for code generation.
• Use only when the code generation target is
S-function (Simulation) or MEX-function.
ismatrix MATLAB —
ismcc MATLAB • Returns true and false as appropriate for
Compiler MEX and SIM targets.
• Returns false for other targets.

4-95
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


ismember MATLAB • Does not support cell arrays for the first or
second arguments.
• Complex inputs must be single or double.
• “Code Generation for Complex Data with
Zero-Valued Imaginary Parts” on page
6-4.
isnan MATLAB —
isnan Fixed-Point —
Designer
isnumeric MATLAB —
isnumeric Fixed-Point —
Designer
isnumerictype Fixed-Point —
Designer
isobject MATLAB —
ispc MATLAB • Returns true or false based on the MATLAB
version you use for code generation.
• Use only when the code generation target is
S-function (Simulation) or MEX-function.
isprime MATLAB • The maximum double precision input is
2^33.
• The maximum single precision input is 2^25.
• The input X cannot have type int64 or
uint64.
isreal MATLAB —
isreal Fixed-Point —
Designer
isrow MATLAB —
isrow Fixed-Point —
Designer
isscalar MATLAB —

4-96
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


isscalar Fixed-Point —
Designer
issigned Fixed-Point —
Designer
issorted MATLAB • Does not support cell arrays for the first
argument.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35.
• “Code Generation for Complex Data with
Zero-Valued Imaginary Parts” on page
6-4.
isspace MATLAB • Input values from the char class must be in
the range 0–127.
issparse MATLAB —
isstrprop MATLAB • Supports only inputs from char and
integer classes.
• Input values must be in the range 0-127.
isstruct MATLAB —
issymmetric MATLAB —
istrellis Communications —
System Toolbox
istril MATLAB —
istriu MATLAB —
isunix MATLAB • Returns true or false based on the MATLAB
version used for code generation.
• Use only when the code generation target is
S-function (Simulation) or MEX-function.
isvector MATLAB —
isvector Fixed-Point —
Designer

4-97
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


kaiser 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
kaiserord Signal Processing —
Toolbox
kron MATLAB —
kmeans Statistics • If the Start method uses random selections,
and Machine the initial centroid cluster positions might
Learning Toolbox not match MATLAB.
• If the number of rows in X is fixed, does not
remove rows of X that contain a NaN.
• The cluster centroid locations in C can
have a different order than in MATLAB. In
this case, the cluster indices in idx have
corresponding differences.
• If you provide Display, its value must be
'off'.
• If you provide Streams, it must be empty
and UseSubstreams must be false.
• When you set the UseParallel option to
true, some computations can execute in
parallel even when Replicates is 1. For
large data sets, when Replicates is 1,
consider setting the UseParallel option to
true.
kurtosis Statistics —
and Machine
Learning Toolbox

4-98
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


lab2rgb Image Processing String input arguments must be compile-time
Toolbox constants.

MATLAB Function Block support: Yes.


label2idx Image Processing MATLAB Function Block support: No.
Toolbox
label2rgb Image Processing Referring to the standard syntax:
Toolbox
RGB = label2rgb(L, map, zerocolor, order)

• 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'.

MATLAB Function Block support: Yes.


lcm MATLAB —
lcmvweights Phased Array Does not support variable-size inputs.
System Toolbox
ldivide MATLAB —
le MATLAB —
le Fixed-Point • Not supported for fixed-point signals with
Designer different biases.
length MATLAB —
length Fixed-Point —
Designer

4-99
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


levinson Signal Processing • Code generation for this function requires the
Toolbox DSP System Toolbox software.
• If specified, the order of recursion must be
a constant. 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
“Specify Constant Inputs at the Command
Line” on page 21-52.
limiter Audio System “System Objects in MATLAB Code Generation”
Toolbox
Supports MATLAB Function Block: Yes
lineToBorderPoints Computer Vision Supports MATLAB Function block: Yes
System Toolbox
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

Other options are equivalent to using


mldivide.
linspace MATLAB —

4-100
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


load MATLAB • Use only when generating MEX or code for
Simulink simulation. To load compile-time
constants, use coder.load.
• Does not support use of the function without
assignment to a structure or array. For
example, use S = load(filename), not
load(filename).
• The output S must be the name of a structure
or array without any subscripting. For
example, S(i) = load('myFile.mat') is
not allowed.
• Arguments to load must be compile-time
constant strings.
• Does not support loading objects.
• If the MAT-file contains
unsupported constructs, use
load(filename,variables) to load only
the supported constructs.
• You cannot use save in a function intended
for code generation. The code generation
software does not support the save
function. Furthermore, you cannot use
coder.extrinsic with save. Prior to
generating code, you can use save to save
the workspace data to a MAT-file.

You must use coder.varsize to explicitly


declare variable-size data loaded using the
load function.
local2globalcoord Phased Array Does not support variable-size inputs.
System Toolbox

4-101
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


log MATLAB • Generates an error during simulation and
returns NaN in generated code when the
input value x is real, but the output should
be complex. To get the complex result,
make the input value complex by passing in
complex(x).
log2 MATLAB —
log10 MATLAB —
log1p MATLAB —
logical MATLAB —
logical Fixed-Point —
Designer
logncdf Statistics —
and Machine
Learning Toolbox
logninv Statistics —
and Machine
Learning Toolbox
lognpdf Statistics —
and Machine
Learning Toolbox
lognrnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
lognstat Statistics —
and Machine
Learning Toolbox
logspace MATLAB —

4-102
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


lower MATLAB • Supports only char inputs. Does not support
cell arrays.
• Input values must be in the range 0-127.
lowerbound Fixed-Point —
Designer
lsb Fixed-Point • Supported for scalar fixed-point signals only.
Designer • Supported for scalar, vector, and matrix, fi
single and double signals.
lsqnonneg MATLAB • You must enable support for variable-size
arrays.
• The message string in the output structure
output (the fifth output) is not translated.
lt MATLAB —
lteZadoffChuSeq Communications —
System Toolbox
lt Fixed-Point • Not supported for fixed-point signals with
Designer different biases.
lu MATLAB —
mad Statistics Input dim cannot be empty.
and Machine
Learning Toolbox
magic MATLAB “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35

4-103
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


matchFeatures Computer Vision Generates platform-dependent library: Yes for
System Toolbox MATLAB host only when using the Exhaustive
method.
Generates portable C code for non-host target
only when using the Exhaustive method.
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries
when not using the Exhaustive method.
“Portable C Code Generation for Functions That
Use OpenCV Library”
Compile-time constant input: 'Method‘ and
'Metric'.
Supports MATLAB Function block: No
max MATLAB • If specified, dim must be a constant.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
• “Code Generation for Complex Data with
Zero-Valued Imaginary Parts” on page
6-4..
max Fixed-Point —
Designer
maxflat Signal Processing 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
mdltest Phased Array Does not support variable-size inputs.
System Toolbox

4-104
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


mean MATLAB • If specified, dim must be a constant.
• The outtype and nanflag options must be
constant strings.
• Does not support the 'native' output data
type option for integer types.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
mean Fixed-Point N/A
Designer
mean2 Image Processing MATLAB Function Block support: Yes.
Toolbox
medfilt2 Image Processing The padopt argument must be a compile-time
Toolbox constant.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The


neighborhood size input argument must be a
compile-time constant.
median MATLAB • If specified, dim must be a constant.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
• “Code Generation for Complex Data with
Zero-Valued Imaginary Parts” on page
6-4.
median Fixed-Point —
Designer
meshgrid MATLAB —
mfilename MATLAB —

4-105
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


min MATLAB • If specified, dim must be a constant.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
• “Code Generation for Complex Data with
Zero-Valued Imaginary Parts” on page
6-4.
min Fixed-Point —
Designer
minus MATLAB —
minus Fixed-Point • Any non-fi input must be constant. Its value
Designer must be known at compile time so that it can
be cast to a fi object.

4-106
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


mkpp MATLAB • The output structure pp differs from the pp
structure in MATLAB. In MATLAB, ppval
cannot use the pp structure from the code
generation software. For code generation,
ppval cannot use a pp structure created by
MATLAB. unmkpp can use a MATLAB pp
structure for code generation.

To create a MATLAB pp structure from a


pp structure created by the code generation
software:

• In code generation, use unmkpp to return


the piecewise polynomial details to
MATLAB.
• In MATLAB, use mkpp to create the pp
structure.
• If you do not provide d, then coefs must be
two-dimensional and have a fixed number of
columns. In this case, the number of columns
is the order.
• To define a piecewise constant polynomial,
coefs must be a column vector or d must
have at least two elements.
• If you provide d and d is 1, d must be a
constant. Otherwise, if the input to ppval is
nonscalar, the shape of the output of ppval
can differ from ppval in MATLAB.
• If you provide d, it must have a fixed length.
One of the following sets of statements must
be true:

1 Suppose that m = length(d) and


npieces = length(breaks) - 1.

size(coefs,j) = d(j)
size(coefs,m+1) = npieces

4-107
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


size(coefs,m+2) = order
j = 1,2,...,m. The dimension m+2 must be
fixed length.
2 Suppose that m = length(d) and
npieces = length(breaks) - 1.

size(coefs,1) = prod(d)*npieces
size(coefs,2) = order
The second dimension must be fixed
length.
• If you do not provide d, the following
statements must be true:

Suppose that m = length(d) and npieces


= length(breaks) - 1.

size(coefs,1) = prod(d)*npieces
size(coefs,2) = order
The second dimension must be fixed length.
mldivide MATLAB —
mnpdf Statistics —
and Machine
Learning Toolbox
mod MATLAB • Performs the arithmetic using the output
class. Results might not match MATLAB due
to differences in rounding errors.

If one of the inputs has type int64 or


uint64, then both inputs must have the
same type.
mode MATLAB • Does not support third output argument C
(cell array).
• If supplied, dim must be a constant.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35

4-108
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


moment Statistics If order is nonintegral and X is real, use
and Machine moment(complex(X), order).
Learning Toolbox
mpower MATLAB If A is a 2-by-2 or larger matrix and B is Inf or -
Inf, mpower(A,B) returns a matrix of NaNs.
mpower Fixed-Point • The exponent input, k, must be constant;
Designer that is, its value must be known at compile
time.
• Variable-size inputs are supported only
when the SumMode property of the governing
fimath is set to Specify precision or
Keep LSB.
• For variable-size signals, you can see
different results between MATLAB and the
generated code.

• In generated code, the output for variable-


size signals is 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.

4-109
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


mpy Fixed-Point • Code generation in MATLAB does not
Designer support the syntax F.mpy(a,b). You must
use the syntax mpy(F,a,b).
• When you provide complex inputs to the
mpy function inside 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 MATLAB —
mrdivide Fixed-Point —
Designer
MSERRegions Computer Vision Supports MATLAB Function block: Yes
System Toolbox For code generation, you must specify both the
pixellist cell array and the length of each
array, as the second input. The object outputs,
regions.PixelList as an array. The region
sizes are defined in regions.Lengths.
Generated code for this function uses a
precompiled platform-specific shared library.
mtimes MATLAB • Multiplication of pure imaginary numbers
by non-finite numbers might not match
MATLAB. The code generation software
does not specialize multiplication by pure
imaginary numbers—it does not eliminate
calculations with the zero real part. For
example, (Inf + 1i)*1i = (Inf*0 –
1*1) + (Inf*1 + 1*0)i = NaN + Infi.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35

4-110
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


mtimes Fixed-Point • Any non-fi input must be constant; that is,
Designer 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 MATLAB and the
generated code.

• In generated code, the output for variable-


sized signals is 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.
multibandParametricEQ Audio System “System Objects in MATLAB Code Generation”
Toolbox
Supports MATLAB Function Block: Yes
multithresh Image Processing If you choose the generic MATLAB Host
Toolbox Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The


input argument N must be compile-time
constant.
mvdrweights Phased Array Does not support variable-size inputs.
System Toolbox
NaN or nan MATLAB • Dimensions must be real, nonnegative,
integers.

4-111
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


nancov Statistics If the input is variable-size and is [] at run
and Machine time, returns [] not NaN.
Learning Toolbox
nanmax Statistics —
and Machine
Learning Toolbox
nanmean Statistics —
and Machine
Learning Toolbox
nanmedian Statistics —
and Machine
Learning Toolbox
nanmin Statistics —
and Machine
Learning Toolbox
nanstd Statistics —
and Machine
Learning Toolbox
nansum Statistics —
and Machine
Learning Toolbox
nanvar Statistics —
and Machine
Learning Toolbox
nargin MATLAB —
narginchk MATLAB —
nargout MATLAB • For a function with no output arguments,
returns 1 if called without a terminating
semicolon.

Note: This behavior also affects extrinsic calls


with no terminating semicolon. nargout is 1 for
the called function in MATLAB.

4-112
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


nargoutchk MATLAB —
nbincdf Statistics —
and Machine
Learning Toolbox
nbininv Statistics —
and Machine
Learning Toolbox
nbinpdf Statistics —
and Machine
Learning Toolbox
nbinrnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
nbinstat Statistics —
and Machine
Learning Toolbox
ncfcdf Statistics —
and Machine
Learning Toolbox
ncfinv Statistics —
and Machine
Learning Toolbox
ncfpdf Statistics —
and Machine
Learning Toolbox
ncfrnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.

4-113
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


ncfstat Statistics —
and Machine
Learning Toolbox
nchoosek MATLAB • When the first input, x, is a scalar,
nchoosek returns a binomial coefficient. In
this case, x must be a nonnegative integer. It
cannot have type int64 or uint64.
• When the first input, x, is a vector,
nchoosek treats it as a set. In this case, x
can have type int64 or uint64.
• The second input, k, cannot have type int64
or uint64.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
nctcdf Statistics —
and Machine
Learning Toolbox
nctinv Statistics —
and Machine
Learning Toolbox
nctpdf Statistics —
and Machine
Learning Toolbox
nctrnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
nctstat Statistics —
and Machine
Learning Toolbox

4-114
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


ncx2cdf Statistics —
and Machine
Learning Toolbox
ncx2rnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
ncx2stat Statistics —
and Machine
Learning Toolbox
ndgrid MATLAB —
ndims MATLAB —
ndims Fixed-Point —
Designer
ne MATLAB —
ne Fixed-Point • Not supported for fixed-point signals with
Designer different biases.
nearest Fixed-Point —
Designer
nextpow2 MATLAB —
nnz MATLAB —
noiseGate Audio System “System Objects in MATLAB Code Generation”
Toolbox
Supports MATLAB Function Block: Yes
noisepow Phased Array Does not support variable-size inputs.
System Toolbox
nonzeros MATLAB —
norm MATLAB —

4-115
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


normcdf Statistics —
and Machine
Learning Toolbox
normest MATLAB —
norminv Statistics —
and Machine
Learning Toolbox
normpdf Statistics —
and Machine
Learning Toolbox
normrnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
normstat Statistics —
and Machine
Learning Toolbox
not MATLAB —
npwgnthresh Phased Array Does not support variable-size inputs.
System Toolbox
nthroot MATLAB —
null MATLAB • Might return a different basis than MATLAB
• Does not support rational basis option
(second input)
num2hex MATLAB —
numberofelements Fixed-Point numberofelements will be removed in a future
Designer release. Use numel instead.
numel MATLAB —
numel Fixed-Point —
Designer

4-116
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


numerictype Fixed-Point • Fixed-point signals coming into a MATLAB
Designer Function block from Simulink are assigned
a numerictype object that is populated
with the signal's data type and scaling
information.
• Returns the data type when the input is a
nonfixed-point signal.
• Use to create numerictype objects in the
generated code.
• All numerictype object properties related to
the data type must be constant.
nuttallwin Signal Processing 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
ocr Computer Vision Compile-time constant input: TextLayout,
System Toolbox Language, and CharacterSet.
Supports MATLAB Function block: No
Generated code for this function uses a
precompiled platform-specific shared library.
ocrText Computer Vision Supports MATLAB Function block: No
System Toolbox

4-117
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


ode23 MATLAB • All odeset option arguments must be
constant.
• Does not support a constant mass matrix in
the options structure. Provide a mass matrix
as a function .
• You must provide at least the two output
arguments T and Y.
• Input types must be homogeneous—all
double or all single.
• Variable-sizing support must be enabled.
Requires dynamic memory allocation when
tspan has two elements or you use event
functions.
ode45 MATLAB • All odeset option arguments must be
constant.
• Does not support a constant mass matrix in
the options structure. Provide a mass matrix
as a function .
• You must provide at least the two output
arguments T and Y.
• Input types must be homogeneous—all
double or all single.
• Variable-sizing support must be enabled.
Requires dynamic memory allocation when
tspan has two elements or you use event
functions.
odeget MATLAB The name argument must be constant.
odeset MATLAB All inputs must be constant.

4-118
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


offsetstrel Image Processing The 'ball’ input argument and all other input
Toolbox arguments must be compile-time constants.
None of the methods are supported for code
generation. When generating code, you can only
specify single objects—arrays of objects are not
supported.

MATLAB Function Block support: Yes.


ones MATLAB • Dimensions must be real, nonnegative
integers.
• The input optimfun must be a function
supported for code generation.
opticalFlowFarneback Computer Vision Supports MATLAB Function block: No
System Toolbox Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries.
“Portable C Code Generation for Functions That
Use OpenCV Library”
opticalFlowHS Computer Vision Supports MATLAB Function block: No
System Toolbox Generated code for this function uses a
precompiled platform-specific shared library.
opticalFlowLK Computer Vision Supports MATLAB Function block: No
System Toolbox Generated code for this function uses a
precompiled platform-specific shared library.
opticalFlowLKDoG Computer Vision Supports MATLAB Function block: No
System Toolbox Generated code for this function uses a
precompiled platform-specific shared library.
optimget MATLAB Input parameter names must be constant.

4-119
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


optimset MATLAB • Does not support the syntax that has no
input or output arguments:
optimset
• Functions specified in the options must be
supported for code generation.
• The fields of the options structure oldopts
must be fixed-size fields.
• For code generation, optimization functions
ignore the Display option.
• Does not support the additional options in an
options structure created by the Optimization
Toolbox™ optimset function. If an input
options structure includes the additional
Optimization Toolbox options, the output
structure does not include them.
ordfilt2 Image Processing The padopt argument must be a compile-time
Toolbox constant.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


or MATLAB —
orth MATLAB • Can return a different basis than MATLAB
otsuthresh Image Processing MATLAB Function Block support: Yes.
Toolbox
padarray Image Processing Support only up to 3-D inputs.
Toolbox
Input arguments, padval and direction are
expected to be compile-time constants.

MATLAB Function Block support: Yes. The


input argument padsize must be a compile-
time constant.

4-120
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


parfor MATLAB • Treated as a for-loop in a MATLAB
Function block or when used with fiaccel.
• See the parfor reference page in the
MATLAB Coder documentation.
• “Generate Code with Parallel for-Loops
(parfor)” on page 29-33.
parzenwin Signal Processing 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
pascal MATLAB —
pca Statistics • Ignores the 'Display' value for 'Options'
and Machine when 'Algorithm' is 'als'.
Learning Toolbox • If supplied, 'Weights' and
'VariableWeights' must be real.
• Always returns the fifth output explained
as a column vector.
• Always returns the sixth output mu as a row
vector.
• If mu is empty, pca returns mu as a 1-by-0
array. pca does not convert mu to a 0-by-0
empty array.
• Does not treat an input matrix X that has all
NaN values as a special case. The outputs
have the sizes that they have when some of
the inputs are finite.

4-121
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


pchip MATLAB • Input x must be strictly increasing.
• Does not remove y entries with NaN values.
• If you generate code for the pp =
pchip(x,y) syntax, you cannot input pp to
the ppval function in MATLAB. To create a
MATLAB pp structure from a pp structure
created by the code generation software:

• In code generation, use unmkpp to return


the piecewise polynomial details to
MATLAB.
• In MATLAB, use mkpp to create the pp
structure.
pdf Statistics —
and Machine
Learning Toolbox
peak2peak Signal Processing —
Toolbox
peak2rms Signal Processing —
Toolbox
pearsrnd Statistics Matches MATLAB only when generated output
and Machine r is scalar.
Learning Toolbox
permute MATLAB • Does not support cell arrays for the first
argument.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
permute Fixed-Point The dimensions argument must be a built-in
Designer type; it cannot be a fi object.
phased.ADPCACanceller Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.AngleDoppler- Phased Array “System Objects in MATLAB Code Generation”
Response System Toolbox

4-122
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


phased.ArrayGain Phased Array • Does not support arrays containing
System Toolbox polarized antenna elements, that is, the
phased.ShortDipoleAntennaElement or
phased.CrossedDipoleAntennaElement
antennas.
• “System Objects in MATLAB Code
Generation”
phased.ArrayResponse Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.Backscatter- Phased Array “System Objects in MATLAB Code Generation”
RadarTarget System Toolbox
phased.BarrageJammer Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.BeamscanEstimator Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.Beamscan- Phased Array “System Objects in MATLAB Code Generation”
Estimator2D System Toolbox

phased.Beamspace- Phased Array “System Objects in MATLAB Code Generation”


ESPRITEstimator System Toolbox
phased.CFARDetector Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.Collector Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.ConformalArray Phased Array • pattern, patternAzimuth,
System Toolbox patternElevation, plotResponse, and
viewArray methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.Constant- Phased Array “System Objects in MATLAB Code Generation”
GammaClutter System Toolbox

4-123
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


phased.Cosine- Phased Array • pattern, patternAzimuth,
AntennaElement System Toolbox patternElevation, and plotResponse
methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.Crossed- Phased Array • pattern, patternAzimuth,
DipoleAntennaElement System Toolbox patternElevation, and plotResponse
methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.Custom- Phased Array • pattern, patternAzimuth,
AntennaElement System Toolbox patternElevation, and plotResponse
methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.Custom- Phased Array • pattern, patternAzimuth,
MicrophoneElement System Toolbox patternElevation, and plotResponse
methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.DPCACanceller Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.ElementDelay Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.ESPRITEstimator Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.FMCWWaveform Phased Array • plot method is not supported.
System Toolbox • See “System Objects in MATLAB Code
Generation”.

4-124
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


phased.FreeSpace Phased Array • Requires dynamic memory allocation. See
System Toolbox “Limitations for System Objects that Require
Dynamic Memory Allocation”.
• See “System Objects in MATLAB Code
Generation”.
phased.FrostBeamformer Phased Array • Requires dynamic memory allocation. See
System Toolbox “Limitations for System Objects that Require
Dynamic Memory Allocation”.
• See “System Objects in MATLAB Code
Generation”.
phased.GCCEstimator Phased Array See “System Objects in MATLAB Code
System Toolbox Generation”.
phased.Isotropic- Phased Array • pattern, patternAzimuth,
AntennaElement System Toolbox patternElevation, and plotResponse
methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.LCMVBeamformer Phased Array See “System Objects in MATLAB Code
System Toolbox Generation”.
phased.LOSChannel Phased Array See “System Objects in MATLAB Code
System Toolbox Generation”.
phased.LinearFMWaveform Phased Array • plot method is not supported.
System Toolbox • See “System Objects in MATLAB Code
Generation”.
phased.MatchedFilter Phased Array • The CustomSpectrumWindow property is
System Toolbox not supported.
• “System Objects in MATLAB Code
Generation”
phased.MFSKWaveform Phased Array • plot method is not supported.
System Toolbox • See “System Objects in MATLAB Code
Generation”.
phased.MVDRBeamformer Phased Array “System Objects in MATLAB Code Generation”
System Toolbox

4-125
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


phased.MVDREstimator Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.MVDREstimator2D Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.Omnidirectional- Phased Array • pattern, patternAzimuth,
MicrophoneElement System Toolbox patternElevation, and plotResponse
methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.PartitionedArray Phased Array • pattern, patternAzimuth,
System Toolbox patternElevation, plotResponse, and
viewArray methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.PhaseCoded- Phased Array • plot method is not supported.
Waveform System Toolbox • See “System Objects in MATLAB Code
Generation”.
phased.PhaseShift- Phased Array “System Objects in MATLAB Code Generation”
Beamformer System Toolbox
phased.Platform Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.RadarTarget Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.Radiator Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.Range- Phased Array • The CustomRangeWindow and the
DopplerResponse System Toolbox CustomDopplerWindow properties are not
supported.
• “System Objects in MATLAB Code
Generation”

4-126
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


phased.Rectangular- Phased Array • plot method is not supported.
Waveform System Toolbox • See “System Objects in MATLAB Code
Generation”.
phased.ReceiverPreamp Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.ReplicatedSubarray Phased Array • pattern, patternAzimuth,
System Toolbox patternElevation, plotResponse, and
viewArray methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.RootMUSICEstimator Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.RootWSFEstimator Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.ShortDipole- Phased Array • pattern, patternAzimuth,
AntennaElement System Toolbox patternElevation, and plotResponse
methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.STAPSMI- Phased Array “System Objects in MATLAB Code Generation”
Beamformer System Toolbox
phased.SteeringVector Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.SteppedFMWaveform Phased Array • plot method is not supported.
System Toolbox • See “System Objects in MATLAB Code
Generation”.
phased.StretchProcessor Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.Subband- Phased Array See “System Objects in MATLAB Code
MVDRBeamformer System Toolbox Generation”.
phased.SubbandPhase- Phased Array “System Objects in MATLAB Code Generation”
ShiftBeamformer System Toolbox

4-127
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


phased.SumDifference- Phased Array See “System Objects in MATLAB Code
MonopulseTracker System Toolbox Generation”.
phased.SumDifference- Phased Array See “System Objects in MATLAB Code
MonopulseTracker2D System Toolbox Generation”.
phased.TimeDelay- Phased Array • Requires dynamic memory allocation. See
Beamformer System Toolbox “Limitations for System Objects that Require
Dynamic Memory Allocation”.
• “System Objects in MATLAB Code
Generation”
phased.TimeDelayLCMV- Phased Array • Requires dynamic memory allocation. See
Beamformer System Toolbox “Limitations for System Objects that Require
Dynamic Memory Allocation”.
• “System Objects in MATLAB Code
Generation”
phased.TimeVaryingGain Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.Transmitter Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.TwoRayChannel Phased Array “System Objects in MATLAB Code Generation”
System Toolbox
phased.UCA Phased Array • pattern, patternAzimuth,
System Toolbox patternElevation, plotResponse, and
viewArray methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.ULA Phased Array • pattern, patternAzimuth,
System Toolbox patternElevation, plotResponse, and
viewArray methods are not supported.
• See “System Objects in MATLAB Code
Generation”.

4-128
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


phased.URA Phased Array • pattern, patternAzimuth,
System Toolbox patternElevation, plotResponse, and
viewArray methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.WidebandCollector Phased Array • Requires dynamic memory allocation. See
System Toolbox “Limitations for System Objects that Require
Dynamic Memory Allocation”.
• “System Objects in MATLAB Code
Generation”.
phased.WidebandFreeSpace Phased Array See “System Objects in MATLAB Code
System Toolbox Generation”.
phased.Wideband- Phased Array See “System Objects in MATLAB Code
LOSChannel System Toolbox Generation”.
phased.WidebandRadiator Phased Array See “System Objects in MATLAB Code
System Toolbox Generation”.
phitheta2azel Phased Array Does not support variable-size inputs.
System Toolbox
phitheta2azelpat Phased Array Does not support variable-size inputs.
System Toolbox
phitheta2uv Phased Array Does not support variable-size inputs.
System Toolbox
phitheta2uvpat Phased Array Does not support variable-size inputs.
System Toolbox
physconst Phased Array Does not support variable-size inputs.
System Toolbox
pi MATLAB —
pilotcalib Phased Array Does not support variable-size inputs.
System Toolbox
pinv MATLAB —

4-129
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


planerot MATLAB “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
plus MATLAB —
plus Fixed-Point • Any non-fi input must be constant; that is,
Designer its value must be known at compile time so
that it can be cast to a fi object.
poisscdf Statistics —
and Machine
Learning Toolbox
poissinv Statistics —
and Machine
Learning Toolbox
poisspdf Statistics —
and Machine
Learning Toolbox
poissrnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
poisstat Statistics —
and Machine
Learning Toolbox
pol2cart MATLAB —
pol2circpol Phased Array Does not support variable-size inputs.
System Toolbox
polellip Phased Array Does not support variable-size inputs.
System Toolbox
polloss Phased Array Does not support variable-size inputs.
System Toolbox

4-130
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


polratio Phased Array Does not support variable-size inputs.
System Toolbox
polsignature Phased Array • Does not support variable-size inputs.
System Toolbox • Supported only when output arguments are
specified.
poly MATLAB • Does not discard nonfinite input values
• Complex input produces complex output
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
polyarea MATLAB —
poly2trellis Communications —
System Toolbox
polyder MATLAB The output can contain fewer NaNs than the
MATLAB output. However, if the input contains
a NaN, the output contains at least one NaN.
polyfit MATLAB “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
polyint MATLAB —
polyval MATLAB —
polyvalm MATLAB —
pow2 Fixed-Point —
Designer
pow2db Signal Processing —
Toolbox

4-131
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


power MATLAB • Generates an error during simulation. When
both X and Y are real, but power(X,Y) is
complex, returns NaN in the generated code.
To get the complex result, make the input
value X complex by passing in complex(X).
For example, power(complex(X),Y).
• Generates an error during simulation. When
both X and Y are real, but X .^ Y is complex,
returns NaN in generated code. To get the
complex result, make the input value X
complex by using complex(X). For example,
complex(X).^Y.
power Fixed-Point • The exponent input, k, must be constant. Its
Designer value must be known at compile time.
ppval MATLAB The size of output v does not match MATLAB
when both of the following statements are true:

• The input x is a variable-size array that is


not a variable-length vector.
• x becomes a row vector at run time.

The code generation software does not remove


the singleton dimensions. However, MATLAB
might remove singleton dimensions.

For example, suppose that x is a :4-by-:5 array


(the first dimension is variable size with an
upper bound of 4 and the second dimension is
variable size with an upper bound of 5). Suppose
that ppval(pp,0) returns a 2-by-3 fixed-size
array. v has size 2-by-3-by-:4-by-:5. At run time,
suppose that, size(x,1) =1 and size (x,2) = 5. In
the generated code, the size(v) is [2,3,1,5]. In
MATLAB, the size is [2,3,5].

4-132
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


prctile Statistics • “Automatic dimension restriction” on page
and Machine 7-35
Learning Toolbox • If the output Y is a vector, the orientation
of Y differs from MATLAB when all of the
following are true:

• You do not supply the dim input.


• X is a variable-size array.
• X is not a variable-length vector.
• X is a vector at run time.
• The orientation of the vector X does not
match the orientation of the vector p.

In this case, the output Y matches the


orientation of X not the orientation of p.
primes MATLAB • The maximum double precision input is
2^32.
• The maximum single precision input is 2^24.
• The input n cannot have type int64 or
uint64.
prod MATLAB • If supplied, dim must be a constant.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
projective2d Image Processing When generating code, you can only specify
Toolbox single objects—arrays of objects are not
supported.

MATLAB Function Block support: Yes.


psi MATLAB —
psnr Image Processing MATLAB Function Block support: Yes.
Toolbox
pulsint Phased Array Does not support variable-size inputs.
System Toolbox

4-133
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


qamdemod Communications —
System Toolbox
qammod Communications —
System Toolbox
qr MATLAB —
quad2d MATLAB • Generates a warning if the size of the
internal storage arrays is not large enough.
If a warning occurs, a possible workaround is
to divide the region of integration into pieces
and sum the integrals over each piece.
quadgk MATLAB —
quantile Statistics —
and Machine
Learning Toolbox
quantize Fixed-Point —
Designer
quat2axang Robotics System Supports MATLAB Function block: Yes
Toolbox
quat2eul Robotics System Supports MATLAB Function block: Yes
Toolbox
quat2rotm Robotics System Supports MATLAB Function block: Yes
Toolbox
quat2tform Robotics System Supports MATLAB Function block: Yes
Toolbox
quatconj Aerospace Code generation for this function requires the
Toolbox Aerospace Blockset™ software.
quatdivide Aerospace Code generation for this function requires the
Toolbox Aerospace Blockset software.
quatinv Aerospace Code generation for this function requires the
Toolbox Aerospace Blockset software.
quatmod Aerospace Code generation for this function requires the
Toolbox Aerospace Blockset software.

4-134
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


quatmultiply Aerospace Code generation for this function requires the
Toolbox Aerospace Blockset software.
quatnorm Aerospace Code generation for this function requires the
Toolbox Aerospace Blockset software.
quatnormalize Aerospace Code generation for this function requires the
Toolbox Aerospace Blockset software.
rad2deg MATLAB —
radareqpow Phased Array Does not support variable-size inputs.
System Toolbox
radareqrng Phased Array Does not support variable-size inputs.
System Toolbox
radareqsnr Phased Array Does not support variable-size inputs.
System Toolbox
radarvcd Phased Array Does not support variable-size inputs.
System Toolbox
radialspeed Phased Array Does not support variable-size inputs.
System Toolbox
rainpl Phased Array Does not support variable-size inputs.
System Toolbox
rand MATLAB • The data type (class) must be a built-in
MATLAB numeric type. Does not invoke the
static rand method for other classes. For
example, rand(sz,'myclass’) does not
invoke myclass.rand(sz).
• Size arguments must have a fixed size.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
randg Statistics —
and Machine
Learning Toolbox

4-135
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


randi MATLAB • The data type (class) must be a built-in
MATLAB numeric type. Does not invoke the
static randi method for other classes. For
example, randi(imax,sz,'myclass’)
does not invoke myclass.randi(imax,sz).
• Size arguments must have a fixed size.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
randn MATLAB • The data type (class) must be a built-in
MATLAB numeric type. Does not invoke the
static randn method for other classes. For
example, randn(sz,'myclass’) does not
invoke myclass.randn(sz).
• Size arguments must have a fixed size.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
random Statistics —
and Machine
Learning Toolbox
randperm MATLAB —
randsample Statistics When sampling without replacement, the order
and Machine of the output values might not match MATLAB.
Learning Toolbox
range Fixed-Point —
Designer
range2beat Phased Array Does not support variable-size inputs.
System Toolbox
range2bw Phased Array Does not support variable-size inputs.
System Toolbox
range2time Phased Array Does not support variable-size inputs.
System Toolbox

4-136
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


rangeangle Phased Array Does not support variable-size inputs.
System Toolbox
rank MATLAB —
raylcdf Statistics —
and Machine
Learning Toolbox
raylinv Statistics —
and Machine
Learning Toolbox
raylpdf Statistics —
and Machine
Learning Toolbox
raylrnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
raylstat Statistics —
and Machine
Learning Toolbox
rcond MATLAB —
rcosdesign 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
rdcoupling Phased Array Does not support variable-size inputs.
System Toolbox

4-137
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


rdivide MATLAB —
rdivide Fixed-Point —
Designer
real MATLAB —
real Fixed-Point —
Designer
reallog MATLAB —
realmax MATLAB —
realmax Fixed-Point —
Designer
realmin MATLAB —
realmin Fixed-Point —
Designer
realpow MATLAB —
realsqrt MATLAB —
reconstructScene Computer Vision Supports MATLAB Function block: No
System Toolbox
rectifyStereoImages Computer Vision Compile-time constant input restriction:
System Toolbox 'interp' and 'OutputView'
Supports MATLAB Function block: No
rectint MATLAB —
recursiveAR System • For Simulink-based workflows, use
Identification Recursive Polynomial Model
Toolbox Estimator.
• For limitations, see “Generate Code for
Online Parameter Estimation in MATLAB”.
recursiveARMA System • For Simulink-based workflows, use
Identification Recursive Polynomial Model
Toolbox Estimator.
• For limitations, see “Generate Code for
Online Parameter Estimation in MATLAB”.

4-138
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


recursiveARMAX System • For Simulink-based workflows, use
Identification Recursive Polynomial Model
Toolbox Estimator.
• For limitations, see “Generate Code for
Online Parameter Estimation in MATLAB”.
recursiveARX System • For Simulink-based workflows, use
Identification Recursive Polynomial Model
Toolbox Estimator.
• For limitations, see “Generate Code for
Online Parameter Estimation in MATLAB”.
recursiveBJ System • For Simulink-based workflows, use
Identification Recursive Polynomial Model
Toolbox Estimator.
• For limitations, see “Generate Code for
Online Parameter Estimation in MATLAB”.
recursiveLS System • For Simulink-based workflows, use
Identification Recursive Least Squares Estimator.
Toolbox • For limitations, see “Generate Code for
Online Parameter Estimation in MATLAB”.
recursiveOE System • For Simulink-based workflows, use
Identification Recursive Polynomial Model
Toolbox Estimator.
• For limitations, see “Generate Code for
Online Parameter Estimation in MATLAB”.
rectwin 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
“Specify Constant Inputs at the Command Line”
on page 21-52.

4-139
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


regionprops Image Processing Supports only 2-D images. Does not support the
Toolbox table output type. Does not accept cell arrays
as input—use a comma-separated list instead.
Does not support the properties ConvexArea,
ConvexHull, ConvexImage, Solidity, and
SubarrayIdx.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: No.


reinterpretcast Fixed-Point —
Designer
rem MATLAB • Performs the arithmetic using the output
class. Results might not match MATLAB due
to differences in rounding errors.
• If one of the inputs has type int64 or
uint64, then both inputs must have the
same type.
removefimath Fixed-Point —
Designer
repmat MATLAB Size arguments must have a fixed size.
repmat Fixed-Point The dimensions argument must be a built-in
Designer type; it cannot be a fi object.

4-140
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


resample Signal Processing • C and C++ code generation for resample
Toolbox requires DSP System Toolbox software.
• The upsampling and downsampling factors
must be specified as constants. 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
“Specify Constant Inputs at the Command
Line” on page 21-52.
rescale Fixed-Point —
Designer
reshape MATLAB • If the input is a compile-time empty cell
array, then the size arguments must be
constants.
• Size arguments must have a fixed size.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
reshape Fixed-Point —
Designer
return MATLAB —
reverberator Audio System “System Objects in MATLAB Code Generation”
Toolbox
Supports MATLAB Function Block: Yes
rgb2gray MATLAB MATLAB Function Block support: Yes.
rgb2lab Image Processing String input arguments must be compile-time
Toolbox constants.

MATLAB Function Block support: Yes.

4-141
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


rgb2ycbcr Image Processing If you choose the generic MATLAB Host
Toolbox Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


rms Signal Processing —
Toolbox
rng MATLAB • Supports only the 'twister', 'v5normal',
and 'v4' generators.
• Does not support the 'shuffle' input.
• For a MEX target:

• If extrinsic calls are disabled or rng


is called inside a parfor loop, the
output of rng in the MEX function is
not compatible with the rng function in
MATLAB. You cannot pass the output of
s = rng from the MEX function to rng in
MATLAB.
• If extrinsic calls are enabled and rng is
not called from inside a parfor loop, only
rng can access the data in the structure
that rng returns.
robotics.ParticleFilter Robotics System Supports MATLAB Function block: No
Toolbox
robotics.PurePursuit Robotics System Supports MATLAB Function block: No
Toolbox
robotics.VectorFieldHistogram Robotics System Supports MATLAB Function block: No
Toolbox
rocpfa Phased Array • Does not support variable-size inputs.
System Toolbox • The NonfluctuatingNoncoherent signal
type is not supported.

4-142
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


rocsnr Phased Array • Does not support variable-size inputs.
System Toolbox • Does not support the
NonfluctuatingNoncoherent signal type.
rootmusicdoa Phased Array Does not support variable-size inputs.
System Toolbox
roots MATLAB • Output is variable size.
• Output is complex.
• Roots are not always in the same order as
MATLAB.
• Roots of poorly conditioned polynomials do
not always match MATLAB.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
rosser MATLAB —
rot90 MATLAB Does not support cell arrays for the first
argument.
rot90 Fixed-Point In the syntax rot90(A,k), the argument k
Designer must be a built-in type; it cannot be a fi object.
rotationMatrixToVector Computer Vision Supports MATLAB Function block: Yes
System Toolbox
rotationVectorToMatrix Computer Vision Supports MATLAB Function block: Yes
System Toolbox
rotm2axang Robotics System Supports MATLAB Function block: Yes
Toolbox
rotm2eul Robotics System Supports MATLAB Function block: Yes
Toolbox
rotm2quat Robotics System Supports MATLAB Function block: Yes
Toolbox
rotm2tform Robotics System Supports MATLAB Function block: Yes
Toolbox

4-143
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


rotx Phased Array Does not support variable-size inputs.
System Toolbox
roty Phased Array Does not support variable-size inputs.
System Toolbox
rotz Phased Array Does not support variable-size inputs.
System Toolbox
round MATLAB Supports only the syntax Y = round(X).
round Fixed-Point —
Designer
rsf2csf MATLAB —
schur MATLAB Can return a different Schur decomposition in
generated code than in MATLAB.
sec MATLAB —
secd MATLAB • In some cases, returns -Inf when MATLAB
returns Inf.
• In some cases, returns Inf when MATLAB
returns -Inf.
sech MATLAB —
selectStrongestBbox Computer Vision Supports MATLAB Function block: No
System Toolbox
sensorcov Phased Array Does not support variable-size inputs.
System Toolbox
sensorsig Phased Array Does not support variable-size inputs.
System Toolbox

4-144
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


setdiff MATLAB • Does not support cell arrays for the first or
second arguments.
• When you do not specify the 'rows' option:

• Inputs A and B must be vectors. If you


specify the 'legacy' option, inputs A and
B must be row vectors.
• The first dimension of a variable-size
row vector must have fixed length 1.
The second dimension of a variable-size
column vector must have fixed length 1.
• Do not use [] to represent the empty set.
Use a 1-by-0 or 0-by-1 input, for example,
zeros(1,0), to represent the empty set.
• If you specify the 'legacy' option, empty
outputs are row vectors, 1-by-0, never 0-
by-0.
• When you specify both the 'legacy' and
'rows' options, the output ia is a column
vector. If ia is empty, it is 0-by-1, never 0-
by-0, even if the output C is 0-by-0.
• When the setOrder is not 'stable' or
when you specify the 'legacy' option, the
inputs must already be sorted in ascending
order. The first output, C, is sorted in
ascending order.
• Complex inputs must be single or double.
• When one input is complex and the other
input is real, do one of the following:

• Set setOrder to 'stable'.


• Sort the real input in complex
ascending order (by absolute
value). Suppose the real input

4-145
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


is x. Use sort(complex(x))or
sortrows(complex(x)).
• “Code Generation for Complex Data with
Zero-Valued Imaginary Parts” on page
6-4.
setfimath Fixed-Point —
Designer

4-146
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


setxor MATLAB • Does not support cell arrays for the first or
second arguments.
• When you do not specify the 'rows' option:

• Inputs A and B must be vectors with


the same orientation. If you specify the
'legacy' option, inputs A and B must be
row vectors.
• The first dimension of a variable-size
row vector must have fixed length 1.
The second dimension of a variable-size
column vector must have fixed length 1.
• The input [] is not supported. Use a
1-by-0 or 0-by-1 input, for example ,
zeros(1,0), to represent the empty set.
• If you specify the 'legacy' option, empty
outputs are row vectors, 1-by-0, never 0-
by-0.
• When you specify both the 'legacy' option
and the 'rows' option, the outputs ia and
ib are column vectors. If these outputs are
empty, they are 0-by-1, never 0-by-0, even if
the output C is 0-by-0.
• When the setOrder is not 'stable' or
when you specify the 'legacy' flag, the
inputs must already be sorted in ascending
order. The first output, C, is sorted in
ascending order.
• Complex inputs must be single or double.
• When one input is complex and the other
input is real, do one of the following:

• Set setOrder to 'stable'.


• Sort the real input in complex
ascending order (by absolute

4-147
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


value). Suppose the real input
is x. Use sort(complex(x))or
sortrows(complex(x)).
• “Code Generation for Complex Data with
Zero-Valued Imaginary Parts” on page
6-4.
sfi Fixed-Point • All properties related to data type must be
Designer constant for code generation.
sgolay 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
“Specify Constant Inputs at the Command Line”
on page 21-52.
shiftdim MATLAB • Does not support cell arrays for the first
argument.
• Second argument must be a constant.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
shiftdim Fixed-Point The dimensions argument must be a built-in
Designer type; it cannot be a fi object.
shnidman Phased Array Does not support variable-size inputs.
System Toolbox
sign MATLAB —
sign Fixed-Point —
Designer
sin MATLAB —
sin Fixed-Point —
Designer

4-148
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


sind MATLAB —
single MATLAB —
single Fixed-Point —
Designer
sinh MATLAB —
size MATLAB —
size Fixed-Point —
Designer
skewness Statistics —
and Machine
Learning Toolbox
sort MATLAB • Does not support cell arrays for the first
argument.
• If the input is a complex type, sort orders
the output according to absolute value.
When x is a complex type that has all zero
imaginary parts, use sort(real(x)) to
compute the sort order for real types. See
“Code Generation for Complex Data with
Zero-Valued Imaginary Parts” on page
6-4.
sort Fixed-Point The dimensions argument must be a built-in
Designer type; it cannot be a fi object.
sortrows MATLAB • Does not support cell arrays for the first
argument.
• If the input is a complex type, sortrows
orders the output according to absolute value.
When x is a complex type that has all zero
imaginary parts, use sortrows(real(x))
to compute the sort order for real types.
See “Code Generation for Complex Data
with Zero-Valued Imaginary Parts” on page
6-4.

4-149
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


sosfilt Signal Processing —
Toolbox
speed2dop Phased Array Does not support variable-size inputs.
System Toolbox
sph2cart MATLAB —
sph2cartvec Phased Array Does not support variable-size inputs.
System Toolbox
spline MATLAB • Input x must be strictly increasing.
• Does not remove Y entries with NaN values.
• Does not report an error for infinite
endslopes in Y.
• If you generate code for the pp =
spline(x,Y) syntax, you cannot input pp
to the ppval function in MATLAB. To create
a MATLAB pp structure from a pp structure
created by the code generation software:

• In code generation, use unmkpp to return


the piecewise polynomial details to
MATLAB.
• In MATLAB, use mkpp to create the pp
structure.
spsmooth Phased Array Does not support variable-size inputs.
System Toolbox
squeeze MATLAB Does not support cell arrays.
squeeze Fixed-Point —
Designer
sqrt MATLAB • Generates an error during simulation and
returns NaN in generated code when the
input value x is real, but the output should
be complex. To get the complex result,
make the input value complex by passing in
complex(x).

4-150
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


sqrt Fixed-Point • Complex and [Slope Bias] inputs error out.
Designer • Negative inputs yield a 0 result.
sqrtm MATLAB —
std MATLAB • If specified, dim must be a constant.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
steervec Phased Array Does not support variable-size inputs.
System Toolbox
stereoAnaglyph Computer Vision Supports MATLAB Function block: Yes
System Toolbox
stereoParameters Computer Vision Supports MATLAB Function block: No
System Toolbox Use the toStruct method to pass a
stereoParameters object into generated code.
See the “Code Generation for Depth Estimation
From Stereo Video” example.
stokes Phased Array • Does not support variable-size inputs.
System Toolbox • Supported only when output arguments are
specified.
storedInteger Fixed-Point —
Designer
storedIntegerToDouble Fixed-Point —
Designer
str2double MATLAB • Does not support cell arrays.
• Always returns a complex result.
str2func MATLAB String must be constant/known at compile time.
strcmp MATLAB • Does not support enumeration inputs.
• When one input is a cell array and the other
input is a character array, the character
array must be a compile-time row vector.
• When both inputs are empty character arrays
that have different sizes, returns true.

4-151
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


strcmpi MATLAB • Does not support enumeration inputs.
• Input values from the char class must be in
the range 0-127.
• When one input is a cell array and the other
input is a character array, the character
array must be a compile-time row vector.
• When both inputs are empty character arrays
that have different sizes, returns true.
strel Image Processing All of the input arguments must be compile-time
Toolbox constants. None of the methods are supported
for code generation. When generating code, you
can only specify single objects—arrays of objects
are not supported.

MATLAB Function Block support: Yes.


stretchfreq2rng Phased Array Does not support variable-size inputs.
System Toolbox
stretchlim Image Processing If you choose the generic MATLAB Host
Toolbox Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


strfind MATLAB • Does not support cell arrays.
• If pattern does not exist in str, returns
zeros(1,0) not []. To check for an empty
return, use isempty.
• Inputs must be character row vectors.
strjoin MATLAB Always returns a string that has size 1-by-n. For
empty inputs, returns a 1-by-0 string not [].
strjust MATLAB Does not support a cell array of strings for the
first argument.

4-152
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


strncmp MATLAB • Does not support enumeration inputs.
• When one input is a cell array and the other
input is a character array, the character
array must be a compile-time row vector.
strncmpi MATLAB • Does not support enumeration inputs.
• Input values from the char class must be in
the range 0-127.
• When one input is a cell array and the other
input is a character array, the character
array must be a compile-time row vector.
strrep MATLAB • Does not support cell arrays.
• If oldSubstr does not exist in origStr,
returns blanks(0). To check for an empty
return, use isempty.
• Inputs must be character row vectors.
strtok MATLAB Does not support cell arrays for the first
argument.
strtrim MATLAB • Supports only inputs from the char class.
Does not support cell arrays.
• Input values must be in the range 0-127.
struct MATLAB • You cannot create a structure that contains a
cell array. For example, you cannot generate
code for:
s = struct('a',{{1 2}})
• If the value argument is a cell array, all
elements must have the same type.

4-153
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


struct2cell MATLAB • For a variable-size structure array, the
resulting cell array must be homogeneous. If
s is a variable-size structure array, the fields
must have the same type.
• If struct2cell cannot convert s to a
homogeneous cell array, the output cell array
is heterogeneous. A heterogeneous output cell
array can have a maximum of 1024 elements.
structfun MATLAB • Does not support the ErrorHandler option.
• The number of outputs must be less than or
equal to three.
sub Fixed-Point Code generation in MATLAB does not support
Designer the syntax F.sub(a,b). You must use the
syntax sub(F,a,b).
sub2ind MATLAB • The first argument must be a valid size
vector. Size vectors for arrays with more than
intmax elements are not supported.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
subsasgn Fixed-Point —
Designer
subspace MATLAB —
subsref Fixed-Point —
Designer
sum MATLAB • If specified, dim must be a constant.
• The outtype and nanflag options must be
constant strings.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35

4-154
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


sum Fixed-Point • Variable-size inputs are only supported
Designer when the SumMode property of the governing
fimath is set to Specify precision or
Keep LSB.
superpixels Image Processing String input arguments must be compile-time
Toolbox constants. The value of 'IsInputLab' (true or
false) must be a compile-time constant.

MATLAB Function Block support: No.


surfacegamma Phased Array Does not support variable-size inputs.
System Toolbox
surfclutterrcs Phased Array Does not support variable-size inputs.
System Toolbox
SURFPoints Computer Vision Supports MATLAB Function block: No
System Toolbox To index locations with this object, use
the syntax: points.Location(idx,:),
for points object. See
visionRecovertformCodeGeneration_kernel.m,
which is used in the “Introduction to Code
Generation with Feature Matching and
Registration” example.
svd MATLAB Uses a different SVD implementation than
MATLAB. Because the singular value
decomposition is not unique, left and right
singular vectors might differ from those
computed by MATLAB.
swapbytes MATLAB Inheritance of the class of the input to
swapbytes in a MATLAB Function block is
supported only when the class of the input is
double. For non-double inputs, the input port
data types must be specified, not inherited.

4-155
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


switch, case, otherwise MATLAB • If all case expressions are scalar integer
values, generates a C switch statement.
At run time, if the switch value is not an
integer, generates an error.
• When the case expressions contain
noninteger or nonscalar values, the code
generation software generates C if
statements in place of a C switch statement.
systemp Phased Array Does not support variable-size inputs.
System Toolbox
tan MATLAB —
tand MATLAB • In some cases, returns -Inf when MATLAB
returns Inf.
• In some cases, returns Inf when MATLAB
returns -Inf.
tanh MATLAB —
taylorwin Signal Processing Inputs must be constant
Toolbox
Specifying constants

To specify a constant input for codegen, use


coder.Constant. For more information, see
“Specify Constant Inputs at the Command Line”
on page 21-52.
tcdf Statistics —
and Machine
Learning Toolbox
tf2ca DSP System All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.
tf2cl DSP System All inputs must be constant. Expressions or
Toolbox variables are allowed if their values do not
change.

4-156
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


tform2axang Robotics System Supports MATLAB Function block: Yes
Toolbox
tform2eul Robotics System Supports MATLAB Function block: Yes
Toolbox
tform2quat Robotics System Supports MATLAB Function block: Yes
Toolbox
tform2rotm Robotics System Supports MATLAB Function block: Yes
Toolbox
tform2trvec Robotics System Supports MATLAB Function block: Yes
Toolbox
time2range Phased Array Does not support variable-size inputs.
System Toolbox
times MATLAB Multiplication of pure imaginary numbers by
non-finite numbers might not match MATLAB.
The code generation software does not specialize
multiplication by pure imaginary numbers—
it does not eliminate calculations with the zero
real part. For example, (Inf + 1i)*1i =
(Inf*0 – 1*1) + (Inf*1 + 1*0)i = NaN
+ Infi.
times Fixed-Point • Any non-fi input must be constant; that is,
Designer 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 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.
tinv Statistics —
and Machine
Learning Toolbox
toeplitz MATLAB —

4-157
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


tpdf Statistics —
and Machine
Learning Toolbox
trace MATLAB —
transpose MATLAB —
transpose Fixed-Point —
Designer
trapz MATLAB • If supplied, dim must be a constant.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
triang Signal Processing Inputs must be constant
Toolbox
Specifying constants

To specify a constant input for codegen, use


coder.Constant. For more information, see
“Specify Constant Inputs at the Command Line”
on page 21-52.
triangulate Computer Vision Supports MATLAB Function block: No
System Toolbox
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
Designer 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
Designer scalar integer value that is not a fi object.

4-158
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


trnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
true MATLAB • Dimensions must be real, nonnegative,
integers.
trvec2tform Robotics System Supports MATLAB Function block: Yes
Toolbox
tstat Statistics —
and Machine
Learning Toolbox
tukeywin Signal Processing Inputs must be constant.
Toolbox
Specifying constants

To specify a constant input for codegen, use


coder.Constant. For more information, see
“Specify Constant Inputs at the Command Line”
on page 21-52.

4-159
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


typecast MATLAB • Value of string input argument type must be
lowercase.
• When you use typecast with inheritance of
input port data types in MATLAB Function
blocks, you can receive a size error. To avoid
this error, specify the block input port data
types explicitly.
• Integer input or result classes must map
directly to a C type on the target hardware.
• The input must be a variable-length vector or
a fixed-size vector. See

“Variable-Sizing Restrictions for Code


Generation of Toolbox Functions” on page
7-35
• The output vector always has the same
orientation as the input vector.
ufi Fixed-Point • All properties related to data type must be
Designer constant for code generation.
uint8, uint16, uint32, MATLAB —
uint64
uint8, uint16, uint32, Fixed-Point —
uint64 Designer
uminus MATLAB —
uminus Fixed-Point —
Designer
undistortImage Computer Vision Compile-time constant input restriction:
System Toolbox 'interp' and 'OutputView'
Supports MATLAB Function block: No
unidcdf Statistics —
and Machine
Learning Toolbox

4-160
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


unidinv Statistics —
and Machine
Learning Toolbox
unidpdf Statistics —
and Machine
Learning Toolbox
unidrnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
unidstat Statistics —
and Machine
Learning Toolbox
unifcdf Statistics —
and Machine
Learning Toolbox
unifinv Statistics —
and Machine
Learning Toolbox
unifpdf Statistics —
and Machine
Learning Toolbox
unifrnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.
unifstat Statistics —
and Machine
Learning Toolbox

4-161
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


unigrid Phased Array Does not support variable-size inputs.
System Toolbox

4-162
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


union MATLAB • Does not support cell arrays for the first or
second arguments.
• When you do not specify the 'rows' option:

• Inputs A and B must be vectors with


the same orientation. If you specify the
'legacy' option, inputs A and B must be
row vectors.
• The first dimension of a variable-size
row vector must have fixed length 1.
The second dimension of a variable-size
column vector must have fixed length 1.
• The input[] is not supported. Use a
1-by-0 or 0-by-1 input, for example ,
zeros(1,0), to represent the empty set.
• If you specify the 'legacy' option, empty
outputs are row vectors, 1-by-0, never 0-
by-0.
• When you specify both the 'legacy' option
and the 'rows' option, the outputs ia and
ib are column vectors. If these outputs are
empty, they are 0-by-1, never 0-by-0, even if
the output C is 0-by-0.
• When the setOrder is not 'stable' or
when you specify the 'legacy' option, the
inputs must already be sorted in ascending
order. The first output, C, is sorted in
ascending order.
• Complex inputs must be single or double.
• When one input is complex and the other
input is real, do one of the following:

• Set setOrder to 'stable'.


• Sort the real input in complex
ascending order (by absolute

4-163
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


value). Suppose the real input
is x. Use sort(complex(x))or
sortrows(complex(x)).
• “Code Generation for Complex Data with
Zero-Valued Imaginary Parts” on page
6-4.
unique MATLAB • Does not support cell arrays for the first
argument.
• When you do not specify the'rows' option:

• The input A must be a vector. If you


specify the 'legacy' option, the input A
must be a row vector.
• The first dimension of a variable-size
row vector must have fixed length 1.
The second dimension of a variable-size
column vector must have fixed length 1.
• The input [] is not supported. Use a
1-by-0 or 0-by-1 input, for example,
zeros(1,0), to represent the empty set.
• If you specify the 'legacy' option, empty
outputs are row vectors, 1-by-0, never 0-
by-0.
• When you specify both the 'rows' option
and the 'legacy'option, outputs ia and
ic are column vectors. If these outputs are
empty, they are 0-by-1, even if the output C is
0-by-0.
• When the setOrder is not 'stable' or
when you specify the 'legacy' option, the
input A must already be sorted in ascending
order. The first output, C, is sorted in
ascending order.
• Complex inputs must be single or double.

4-164
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


unmkpp MATLAB • pp must be a valid piecewise polynomial
structure created by mkpp, spline, or
pchip in MATLAB or by the code generation
software.
• Does not support pp structures created by
interp1 in MATLAB.
unwrap MATLAB • Row vector input is only supported when the
first two inputs are vectors and nonscalar
• Performs arithmetic in the output class.
Hence, results might not match MATLAB
due to different rounding errors
upfirdn Signal Processing • Code generation for this function requires the
Toolbox DSP System Toolbox software.
• Filter coefficients, upsampling factor, and
downsampling factor must be constants.
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
“Specify Constant Inputs at the Command
Line” on page 21-52.
uplus MATLAB —
uplus Fixed-Point —
Designer
upper MATLAB • Supports only inputs from the char class.
Does not support cell arrays.
• Input values must be in the range 0-127.
upperbound Fixed-Point —
Designer

4-165
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


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)
uv2azel Phased Array Does not support variable-size inputs.
System Toolbox
uv2azelpat Phased Array Does not support variable-size inputs.
System Toolbox
uv2phitheta Phased Array Does not support variable-size inputs.
System Toolbox
uv2phithetapat Phased Array Does not support variable-size inputs.
System Toolbox
val2ind Phased Array Does not support variable-size inputs.
System Toolbox
vander MATLAB —
var MATLAB • If specified, dim must be a constant.
• “Variable-Sizing Restrictions for Code
Generation of Toolbox Functions” on page
7-35
vertcat Fixed-Point —
Designer
vision.AlphaBlender Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.Autocorrelator Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.BlobAnalysis Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”

4-166
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


vision.CascadeObjectDetector Computer Vision Supports MATLAB Function block: No
System Toolbox Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries
“Portable C Code Generation for Functions That
Use OpenCV Library”
“System Objects in MATLAB Code Generation”
vision.ChromaResampler Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.Convolver Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.Crosscorrelator Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.DemosaicInterpolator Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.DCT Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.Deinterlacer Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.DeployableVideoPlayer Computer Vision Supports MATLAB Function block: Yes
System Toolbox Generated code for this function uses a
precompiled platform-specific shared library.
“System Objects in MATLAB Code Generation”
vision.FFT Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.ForegroundDetector Computer Vision Supports MATLAB Function block: No
System Toolbox Generates platform-dependent library: Yes for
MATLAB host.
Generates portable C code for non-host target.
Generated code for this function uses a
precompiled platform-specific shared library.
“System Objects in MATLAB Code Generation”
vision.GammaCorrector Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”

4-167
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


vision.GeometricShearer Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.Histogram- Computer Vision Supports MATLAB Function block: Yes
BasedTracker System Toolbox “System Objects in MATLAB Code Generation”
vision.HoughLines Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.IDCT Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.IFFT Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.ImageDataType- Computer Vision Supports MATLAB Function block: Yes
Converter System Toolbox “System Objects in MATLAB Code Generation”
vision.KalmanFilter Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.LocalMaximaFinder Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.MarkerInserter Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.Maximum Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.Median Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.MedianFilter Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.Mean Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.Minimum Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”

4-168
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


vision.PeopleDetector Computer Vision Supports MATLAB Function block: No
System Toolbox Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries.
“Portable C Code Generation for Functions That
Use OpenCV Library”
“System Objects in MATLAB Code Generation”
vision.PointTracker Computer Vision Supports MATLAB Function block: No
System Toolbox Supports MATLAB Function block: No
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries.
“Portable C Code Generation for Functions That
Use OpenCV Library”
“System Objects in MATLAB Code
Generation”“System Objects in MATLAB Code
Generation”
vision.Pyramid Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.ShapeInserter Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.StandardDeviation Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.TemplateMatcher Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.Variance Computer Vision Supports MATLAB Function block: Yes
System Toolbox “System Objects in MATLAB Code Generation”
vision.VideoFileReader Computer Vision Supports MATLAB Function block: Yes
System Toolbox Generated code for this function uses a
precompiled platform-specific shared library.
“System Objects in MATLAB Code Generation”

Does not generate code for reading compressed


images on the Mac.

4-169
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


vision.VideoFileWriter Computer Vision Supports MATLAB Function block: Yes
System Toolbox Generated code for this function uses a
precompiled platform-specific shared library.
“System Objects in MATLAB Code Generation”
vitdec Communications —
System Toolbox
watershed Image Processing Supports only 2-D images. Supports only 4- or 8-
Toolbox connectivity. Supports only up to 65,535 regions.
The output type is always uint16.

If you choose the generic MATLAB Host


Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: No.


wavetableSynthesizer Audio System “System Objects in MATLAB Code Generation”
Toolbox
Supports MATLAB Function Block: Yes
wblcdf Statistics —
and Machine
Learning Toolbox
wblinv Statistics —
and Machine
Learning Toolbox
wblpdf Statistics —
and Machine
Learning Toolbox
wblrnd Statistics Can return a different sequence of numbers than
and Machine MATLAB if either of the following is true:
Learning Toolbox
• The output is nonscalar.
• An input parameter is invalid for the
distribution.

4-170
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


wblstat Statistics —
and Machine
Learning Toolbox
while MATLAB —
wilkinson MATLAB n must be a fixed-size scalar.
wlanCoarseCFOEstimate WLAN System —
Toolbox
wlanFieldIndices WLAN System —
Toolbox
wlanFineCFOEstimate WLAN System —
Toolbox
wlanGeneratorConfig WLAN System —
Toolbox
wlanHTConfig WLAN System —
Toolbox
wlanHTData WLAN System Cannot be used in MATLAB Function block.
Toolbox
wlanHTDataRecover WLAN System —
Toolbox
wlanHTLTFChannel- WLAN System —
Estimate Toolbox
wlanHTLTFDemodulate WLAN System —
Toolbox
wlanHTLTF WLAN System —
Toolbox
wlanHTSIG WLAN System —
Toolbox
wlanHTSIGRecover WLAN System —
Toolbox
wlanHTSTF WLAN System —
Toolbox

4-171
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


wlanLLTF WLAN System —
Toolbox
wlanLLTFChannelEstimate WLAN System —
Toolbox
wlanLLTFDemodulate WLAN System —
Toolbox
wlanLSIG WLAN System —
Toolbox
wlanLSIGRecover WLAN System —
Toolbox
wlanLSTF WLAN System —
Toolbox
wlanNonHTConfig WLAN System —
Toolbox
wlanNonHTData WLAN System Cannot be used in MATLAB Function block.
Toolbox
wlanRecoveryConfig WLAN System —
Toolbox
wlanTGacChannel WLAN System “System Objects in MATLAB Code Generation”
Toolbox
wlanTGnChannel WLAN System “System Objects in MATLAB Code Generation”
Toolbox
wlanVHTConfig WLAN System —
Toolbox
wlanVHTData WLAN System Cannot be used in MATLAB Function block.
Toolbox
wlanVHTDataRecover WLAN System Cannot be used in MATLAB Function block
Toolbox
wlanVHTLTF WLAN System —
Toolbox
wlanVHTLTFChannel- WLAN System —
Estimate Toolbox

4-172
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List

Name Product Remarks and Limitations


wlanVHTLTFDemodulate WLAN System —
Toolbox
wlanVHTSIGA WLAN System —
Toolbox
wlanVHTSIGARecover WLAN System —
Toolbox
wlanVHTSIGBRecover WLAN System —
Toolbox
wlanVHTSIGB WLAN System —
Toolbox
wlanVHTSTF WLAN System —
Toolbox
wlanWaveformGenerator WLAN System Cannot be used in MATLAB Function block.
Toolbox
xcorr Signal Processing Leading ones in size(x) must be constant for
Toolbox every input x. If x is variable-size and is a row
vector, it must be 1-by-:. It cannot be :-by-:
with size(x,1) = 1 at run time.
xor MATLAB —
ycbcr2rgb Image Processing If you choose the generic MATLAB Host
Toolbox Computer target platform, generated code uses
a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


yulewalk Signal Processing If specified, the order of recursion must be a
Toolbox constant. 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
“Specify Constant Inputs at the Command Line”
on page 21-52.

4-173
4 Functions, Classes, and System Objects Supported for Code Generation

Name Product Remarks and Limitations


zeros MATLAB • Dimensions must be real, nonnegative,
integers.
zp2tf MATLAB —
zscore Statistics —
and Machine
Learning Toolbox

4-174
Functions and Objects Supported for C and C++ Code Generation — Category List

Functions and Objects Supported for C and C++ Code Generation


— Category List
You can generate efficient C and C++ code for a subset of MATLAB built-in functions and
toolbox functions, classes, and System objects that you call from MATLAB code. These
functions, classes, and System objects are listed by MATLAB category or toolbox category
in the following tables.

For an alphabetical list of supported functions, classes, and System objects, see
“Functions and Objects Supported for C and C++ Code Generation — Alphabetical List”
on page 4-2.

Note: For more information on code generation for fixed-point algorithms, refer to “Code
Acceleration and Code Generation from MATLAB”.

In this section...
“Aerospace Toolbox” on page 4-177
“Arithmetic Operations in MATLAB” on page 4-177
“Audio System Toolbox” on page 4-178
“Bit-Wise Operations MATLAB” on page 4-180
“Casting in MATLAB” on page 4-180
“Communications System Toolbox” on page 4-181
“Complex Numbers in MATLAB” on page 4-187
“Computer Vision System Toolbox” on page 4-187
“Control Flow in MATLAB” on page 4-197
“Data and File Management in MATLAB” on page 4-197
“Data Types in MATLAB” on page 4-201
“Desktop Environment in MATLAB” on page 4-202
“Discrete Math in MATLAB” on page 4-203
“DSP System Toolbox” on page 4-203
“Error Handling in MATLAB” on page 4-211
“Exponents in MATLAB” on page 4-211

4-175
4 Functions, Classes, and System Objects Supported for Code Generation

In this section...
“Filtering and Convolution in MATLAB” on page 4-212
“Fixed-Point Designer” on page 4-213
“HDL Coder” on page 4-223
“Histograms in MATLAB” on page 4-223
“Image Acquisition Toolbox” on page 4-224
“Image Processing in MATLAB” on page 4-224
“Image Processing Toolbox” on page 4-224
“Input and Output Arguments in MATLAB” on page 4-240
“Interpolation and Computational Geometry in MATLAB” on page 4-241
“Linear Algebra in MATLAB” on page 4-245
“Logical and Bit-Wise Operations in MATLAB” on page 4-246
“MATLAB Compiler” on page 4-247
“Matrices and Arrays in MATLAB” on page 4-247
“Neural Network Toolbox” on page 4-256
“Numerical Integration and Differentiation in MATLAB” on page 4-256
“Optimization Functions in MATLAB” on page 4-257
“Phased Array System Toolbox” on page 4-258
“Polynomials in MATLAB” on page 4-267
“Programming Utilities in MATLAB” on page 4-267
“Relational Operators in MATLAB” on page 4-268
“Robotics System Toolbox” on page 4-268
“Rounding and Remainder Functions in MATLAB” on page 4-269
“Set Operations in MATLAB” on page 4-270
“Signal Processing in MATLAB” on page 4-274
“Signal Processing Toolbox” on page 4-275
“Special Values in MATLAB” on page 4-280
“Specialized Math in MATLAB” on page 4-281
“Statistics in MATLAB” on page 4-281
“Statistics and Machine Learning Toolbox” on page 4-282

4-176
Functions and Objects Supported for C and C++ Code Generation — Category List

In this section...
“String Functions in MATLAB” on page 4-292
“System Identification Toolbox” on page 4-294
“Trigonometry in MATLAB” on page 4-296
“WLAN System Toolbox” on page 4-298

Aerospace Toolbox
C and C++ code generation for the following Aerospace Toolbox quaternion functions
requires the Aerospace Blockset software.

Function Remarks and Limitations


quatconj —
quatdivide —
quatinv —
quatmod —
quatmultiply —
quatnorm —
quatnormalize —

Arithmetic Operations in MATLAB


See “Array vs. Matrix Operations” for detailed descriptions of the following operator
equivalent functions.

Function Remarks and Limitations


ctranspose —
idivide • For efficient generated code, MATLAB rules for divide by zero are
supported only for the 'round' option.
isa —
ldivide —
minus —
mldivide —

4-177
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


mpower If A is a 2-by-2 or larger matrix and B is Inf or -Inf, mpower(A,B)
returns a matrix of NaNs.
mrdivide —
mtimes • Multiplication of pure imaginary numbers by non-finite numbers might
not match MATLAB. The code generation software does not specialize
multiplication by pure imaginary numbers—it does not eliminate
calculations with the zero real part. For example, (Inf + 1i)*1i =
(Inf*0 – 1*1) + (Inf*1 + 1*0)i = NaN + Infi.
• “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35
plus —
power • Generates an error during simulation. When both X and Y are real,
but power(X,Y) is complex, returns NaN in the generated code. To
get the complex result, make the input value X complex by passing in
complex(X). For example, power(complex(X),Y).
• Generates an error during simulation. When both X and Y are real, but
X .^ Y is complex, returns NaN in generated code. To get the complex
result, make the input value X complex by using complex(X). For
example, complex(X).^Y.
rdivide —
times Multiplication of pure imaginary numbers by non-finite numbers might
not match MATLAB. The code generation software does not specialize
multiplication by pure imaginary numbers—it does not eliminate
calculations with the zero real part. For example, (Inf + 1i)*1i =
(Inf*0 – 1*1) + (Inf*1 + 1*0)i = NaN + Infi.
transpose —
uminus —
uplus —

Audio System Toolbox


C and C++ code generation for the following functions and System objects requires the
Audio System Toolbox software.

4-178
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


Audio I/O and Waveform Generation
audioDeviceReader “System Objects in MATLAB Code Generation”

Supports MATLAB Function Block: Yes


audioDeviceWriter “System Objects in MATLAB Code Generation”

Supports MATLAB Function Block: Yes


wavetableSynthesizer “System Objects in MATLAB Code Generation”

Supports MATLAB Function Block: Yes


audioOscillator “System Objects in MATLAB Code Generation”

Supports MATLAB Function Block: Yes


Audio Processing Algorithm Design
designVarSlopeFilter Supports MATLAB Function Block: Yes
designParamEQ Supports MATLAB Function Block: Yes
designShelvingEQ Supports MATLAB Function Block: Yes
crossoverFilter “System Objects in MATLAB Code Generation”

Supports MATLAB Function Block: Yes


compressor “System Objects in MATLAB Code Generation”

Supports MATLAB Function Block: Yes


expander “System Objects in MATLAB Code Generation”

Supports MATLAB Function Block: Yes


noiseGate “System Objects in MATLAB Code Generation”

Supports MATLAB Function Block: Yes


limiter “System Objects in MATLAB Code Generation”

Supports MATLAB Function Block: Yes

4-179
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


multibandParametricEQ “System Objects in MATLAB Code Generation”

Supports MATLAB Function Block: Yes


reverberator “System Objects in MATLAB Code Generation”

Supports MATLAB Function Block: Yes


Audio Plugins
audioPluginInterface Supports MATLAB Function Block: Yes
audioPluginParameter Supports MATLAB Function Block: Yes
audioPlugin Supports MATLAB Function Block: Yes
audioPluginSource Supports MATLAB Function Block: Yes

Bit-Wise Operations MATLAB

Function Remarks and Limitations


flintmax —
swapbytes Inheritance of the class of the input to swapbytes in a MATLAB Function
block is supported only when the class of the input is double. For non-
double inputs, the input port data types must be specified, not inherited.

Casting in MATLAB

Function Remarks and Limitations


cast —
char Does not support cell arrays.
class —
double —
int8, int16, int32, —
int64
logical —
single —

4-180
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


typecast • Value of string input argument type must be lowercase.
• When you use typecast with inheritance of input port data types in
MATLAB Function blocks, you can receive a size error. To avoid this
error, specify the block input port data types explicitly.
• Integer input or result classes must map directly to a C type on the
target hardware.
• The input must be a variable-length vector or a fixed-size vector. See

“Variable-Sizing Restrictions for Code Generation of Toolbox Functions”


on page 7-35
• The output vector always has the same orientation as the input vector.
uint8, uint16, —
uint32, uint64

Communications System Toolbox


C and C++ code generation for the following functions and System objects requires the
Communications System Toolbox software.

Name Remarks and Limitations


Input and Output
comm.BarkerCode “System Objects in MATLAB Code Generation”
comm.GoldSequence “System Objects in MATLAB Code Generation”
comm.HadamardCode “System Objects in MATLAB Code Generation”
comm.KasamiSequence “System Objects in MATLAB Code Generation”
comm.WalshCode “System Objects in MATLAB Code Generation”
comm.PNSequence “System Objects in MATLAB Code Generation”
lteZadoffChuSeq —
Signal and Delay Management
bi2de —
de2bi —
Display and Visual Analysis

4-181
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


comm.ConstellationDiagram “System Objects in MATLAB Code Generation”
dsp.ArrayPlot “System Objects in MATLAB Code Generation”
dsp.SpectrumAnalyzer “System Objects in MATLAB Code Generation”
dsp.TimeScope “System Objects in MATLAB Code Generation”
Source Coding
comm.DifferentialDecoder “System Objects in MATLAB Code Generation”
comm.DifferentialEncoder “System Objects in MATLAB Code Generation”
Cyclic Redundancy Check Coding
comm.CRCDetector “System Objects in MATLAB Code Generation”
comm.CRCGenerator “System Objects in MATLAB Code Generation”
comm.HDLCRCDetector “System Objects in MATLAB Code Generation”
comm.HDLCRCGenerator “System Objects in MATLAB Code Generation”
BCH Codes
comm.BCHDecoder “System Objects in MATLAB Code Generation”
comm.BCHEncoder “System Objects in MATLAB Code Generation”
Reed-Solomon Codes
comm.RSDecoder “System Objects in MATLAB Code Generation”
comm.RSEncoder “System Objects in MATLAB Code Generation”
comm.HDLRSDecoder “System Objects in MATLAB Code Generation”
comm.HDLRSEncoder “System Objects in MATLAB Code Generation”
LDPC Codes
comm.LDPCDecoder Using default properties, comm.LDPCDecoder
does not support code generation. To generate
code, specify the ParityCheckMatrix property
as a non-sparse row-column index matrix.
comm.LDPCEncoder “System Objects in MATLAB Code Generation”
Convolutional Coding
comm.APPDecoder “System Objects in MATLAB Code Generation”
comm.ConvolutionalEncoder “System Objects in MATLAB Code Generation”

4-182
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


comm.TurboDecoder “System Objects in MATLAB Code Generation”
comm.TurboEncoder “System Objects in MATLAB Code Generation”
comm.ViterbiDecoder “System Objects in MATLAB Code Generation”
convenc —
istrellis —
poly2trellis —
vitdec —
Signal Operations
comm.Descrambler “System Objects in MATLAB Code Generation”
comm.Scrambler “System Objects in MATLAB Code Generation”
Interleaving
comm.AlgebraicDeinterleaver “System Objects in MATLAB Code Generation”
comm.AlgebraicInterleaver “System Objects in MATLAB Code Generation”
comm.BlockDeinterleaver “System Objects in MATLAB Code Generation”
comm.BlockInterleaver “System Objects in MATLAB Code Generation”
comm.ConvolutionalDeinterleaver “System Objects in MATLAB Code Generation”
comm.ConvolutionalInterleaver “System Objects in MATLAB Code Generation”
comm.HelicalDeinterleaver “System Objects in MATLAB Code Generation”
comm.HelicalInterleaver “System Objects in MATLAB Code Generation”
comm.MatrixDeinterleaver “System Objects in MATLAB Code Generation”
comm.MatrixInterleaver “System Objects in MATLAB Code Generation”
comm.MatrixHelicalScanDeinterleaver “System Objects in MATLAB Code Generation”
comm.MatrixHelicalScanInterleaver “System Objects in MATLAB Code Generation”
comm.MultiplexedDeinterleaver “System Objects in MATLAB Code Generation”
comm.MultiplexedInterleaver “System Objects in MATLAB Code Generation”
Frequency Modulation
comm.FSKDemodulator “System Objects in MATLAB Code Generation”
comm.FSKModulator “System Objects in MATLAB Code Generation”

4-183
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


Phase Modulation
comm.BPSKDemodulator “System Objects in MATLAB Code Generation”
comm.BPSKModulator “System Objects in MATLAB Code Generation”
comm.DBPSKDemodulator “System Objects in MATLAB Code Generation”
comm.DBPSKModulator “System Objects in MATLAB Code Generation”
comm.DPSKDemodulator “System Objects in MATLAB Code Generation”
comm.DPSKModulator “System Objects in MATLAB Code Generation”
comm.DQPSKDemodulator “System Objects in MATLAB Code Generation”
comm.DQPSKModulator “System Objects in MATLAB Code Generation”
comm.OQPSKDemodulator “System Objects in MATLAB Code Generation”
comm.OQPSKModulator “System Objects in MATLAB Code Generation”
comm.PSKDemodulator “System Objects in MATLAB Code Generation”
comm.PSKModulator “System Objects in MATLAB Code Generation”
comm.QPSKDemodulator “System Objects in MATLAB Code Generation”
comm.QPSKModulator “System Objects in MATLAB Code Generation”
dpskdemod —
dpskmod —
Amplitude Modulation
comm.GeneralQAMDemodulator “System Objects in MATLAB Code Generation”
comm.GeneralQAMModulator “System Objects in MATLAB Code Generation”
comm.PAMDemodulator “System Objects in MATLAB Code Generation”
comm.PAMModulator “System Objects in MATLAB Code Generation”
comm.RectangularQAMDemodulator “System Objects in MATLAB Code Generation”
comm.RectangularQAMModulator “System Objects in MATLAB Code Generation”
qammod —
qamdemod —
Continuous Phase Modulation
comm.CPFSKDemodulator “System Objects in MATLAB Code Generation”

4-184
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


comm.CPFSKModulator “System Objects in MATLAB Code Generation”
comm.CPMDemodulator “System Objects in MATLAB Code Generation”
comm.CPMModulator “System Objects in MATLAB Code Generation”
comm.GMSKDemodulator “System Objects in MATLAB Code Generation”
comm.GMSKModulator “System Objects in MATLAB Code Generation”
comm.MSKDemodulator “System Objects in MATLAB Code Generation”
comm.MSKModulator “System Objects in MATLAB Code Generation”
Trellis Coded Modulation
comm.GeneralQAMTCMDemodulator “System Objects in MATLAB Code Generation”
comm.GeneralQAMTCMModulator “System Objects in MATLAB Code Generation”
comm.PSKTCMDemodulator “System Objects in MATLAB Code Generation”
comm.PSKTCMModulator “System Objects in MATLAB Code Generation”
comm.RectangularQAMTCMDemodulator “System Objects in MATLAB Code Generation”
comm.RectangularQAMTCMModulator “System Objects in MATLAB Code Generation”
Orthogonal Frequency-Division Modulation
comm.OFDMDemodulator “System Objects in MATLAB Code Generation”
comm.OFDMModulator “System Objects in MATLAB Code Generation”
Analog Baseband Modulation
comm.FMBroadcastDemodulator “System Objects in MATLAB Code Generation”
comm.FMBroadcastModulator “System Objects in MATLAB Code Generation”
comm.FMDemodulator “System Objects in MATLAB Code Generation”
comm.FMModulator “System Objects in MATLAB Code Generation”
Filtering
comm.IntegrateAndDumpFilter “System Objects in MATLAB Code Generation”
comm.RaisedCosineReceiveFilter “System Objects in MATLAB Code Generation”
comm.RaisedCosineTransmitFilter “System Objects in MATLAB Code Generation”
Carrier Phase Synchronization
comm.CarrierSynchronizer “System Objects in MATLAB Code Generation”

4-185
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


comm.CPMCarrierPhaseSynchronizer “System Objects in MATLAB Code Generation”
comm.CoarseFrequencyCompensator “System Objects in MATLAB Code Generation”
Timing Phase Synchronization
comm.SymbolSynchronizer “System Objects in MATLAB Code Generation”
comm.GMSKTimingSynchronizer “System Objects in MATLAB Code Generation”
comm.MSKTimingSynchronizer “System Objects in MATLAB Code Generation”
Synchronization Utilities
comm.DiscreteTimeVCO “System Objects in MATLAB Code Generation”
Equalization
comm.MLSEEqualizer “System Objects in MATLAB Code Generation”
MIMO
comm.LTEMIMOChannel “System Objects in MATLAB Code Generation”
comm.MIMOChannel “System Objects in MATLAB Code Generation”
comm.OSTBCCombiner “System Objects in MATLAB Code Generation”
comm.OSTBCEncoder “System Objects in MATLAB Code Generation”
comm.SphereDecoder “System Objects in MATLAB Code Generation”
Channel Modeling and RF Impairments
comm.AGC “System Objects in MATLAB Code Generation”
comm.AWGNChannel “System Objects in MATLAB Code Generation”
comm.BinarySymmetricChannel “System Objects in MATLAB Code Generation”
comm.IQImbalanceCompensator “System Objects in MATLAB Code Generation”
comm.LTEMIMOChannel “System Objects in MATLAB Code Generation”
comm.MemorylessNonlinearity “System Objects in MATLAB Code Generation”
comm.MIMOChannel “System Objects in MATLAB Code Generation”
comm.PhaseFrequencyOffset “System Objects in MATLAB Code Generation”
comm.PhaseNoise “System Objects in MATLAB Code Generation”
comm.RayleighChannel “System Objects in MATLAB Code Generation”
comm.RicianChannel “System Objects in MATLAB Code Generation”

4-186
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


comm.ThermalNoise “System Objects in MATLAB Code Generation”
comm.PSKCoarseFrequencyEstimator “System Objects in MATLAB Code Generation”
comm.QAMCoarseFrequencyEstimator “System Objects in MATLAB Code Generation”
iqcoef2imbal —
iqimbal2coef —
Measurements and Analysis
comm.ACPR “System Objects in MATLAB Code Generation”
comm.CCDF “System Objects in MATLAB Code Generation”
comm.ErrorRate “System Objects in MATLAB Code Generation”
comm.EVM “System Objects in MATLAB Code Generation”
comm.MER “System Objects in MATLAB Code Generation”

Complex Numbers in MATLAB


Function Remarks and Limitations
complex —
conj —
imag —
isnumeric —
isreal —
isscalar —
real —
unwrap • Row vector input is only supported when the first two inputs are vectors
and nonscalar
• Performs arithmetic in the output class. Hence, results might not match
MATLAB due to different rounding errors

Computer Vision System Toolbox


C and C++ code generation for the following functions and System objects requires the
Computer Vision System Toolbox software.

4-187
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


Feature Detection, Extraction, and Matching
BRISKPoints Supports MATLAB Function block: No
To index locations with this object, use
the syntax: points.Location(idx,:),
for points object. See
visionRecovertformCodeGeneration_kernel.m,
which is used in the “Introduction to Code
Generation with Feature Matching and
Registration” example.
cornerPoints Supports MATLAB Function block: No
To index locations with this object, use
the syntax: points.Location(idx,:),
for points object. See
visionRecovertformCodeGeneration_kernel.m,
which is used in the “Introduction to Code
Generation with Feature Matching and
Registration” example.
detectBRISKFeatures Supports MATLAB Function block: No
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries.
“Portable C Code Generation for Functions That
Use OpenCV Library”
detectFASTFeatures Supports MATLAB Function block: No
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries.
“Portable C Code Generation for Functions That
Use OpenCV Library”
detectHarrisFeatures Compile-time constant input: 'FilterSize'
Supports MATLAB Function block: No
Generated code for this function uses a
precompiled platform-specific shared library.
detectMinEigenFeatures Compile-time constant input: 'FilterSize'
Supports MATLAB Function block: No
Generated code for this function uses a
precompiled platform-specific shared library.

4-188
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


detectMSERFeatures Supports MATLAB Function block: No
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries
“Portable C Code Generation for Functions That
Use OpenCV Library”
For code generation, the function outputs
regions.PixelList as an array. The region
sizes are defined in regions.Lengths.
detectSURFFeatures Supports MATLAB Function block: No
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries.
“Portable C Code Generation for Functions That
Use OpenCV Library”
extractFeatures Compile-time constant input restrictions:
'Method'
Supports MATLAB Function block: Yes for
Block method only.
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries for
BRISK, FREAK, and SURF Methods.
“Portable C Code Generation for Functions That
Use OpenCV Library”
extractHOGFeatures Supports MATLAB Function block: No
extractLBPFeatures Generates platform-dependent library: No
Supports MATLAB Function block: Yes

4-189
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


matchFeatures Generates platform-dependent library: Yes for
MATLAB host only when using the Exhaustive
method.
Generates portable C code for non-host target
only when using the Exhaustive method.
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries
when not using the Exhaustive method.
“Portable C Code Generation for Functions That
Use OpenCV Library”
Compile-time constant input: 'Method‘ and
'Metric'.
Supports MATLAB Function block: No
MSERRegions Supports MATLAB Function block: Yes
For code generation, you must specify both the
pixellist cell array and the length of each
array, as the second input. The object outputs,
regions.PixelList as an array. The region
sizes are defined in regions.Lengths.
Generated code for this function uses a
precompiled platform-specific shared library.
SURFPoints Supports MATLAB Function block: No
To index locations with this object, use
the syntax: points.Location(idx,:),
for points object. See
visionRecovertformCodeGeneration_kernel.m,
which is used in the “Introduction to Code
Generation with Feature Matching and
Registration” example.
Image Registration and Geometric Transformations
estimateGeometricTransform Supports MATLAB Function block: No
vision.GeometricShearer Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
Object Detection and Recognition

4-190
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


ocr Compile-time constant input: 'TextLayout',
'Language', and 'CharacterSet'.
Supports MATLAB Function block: No
Generated code for this function uses a
precompiled platform-specific shared library.
ocrText Supports MATLAB Function block: No
vision.PeopleDetector Supports MATLAB Function block: No
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries.
“Portable C Code Generation for Functions That
Use OpenCV Library”
“System Objects in MATLAB Code Generation”
vision.CascadeObjectDetector Supports MATLAB Function block: No
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries
“Portable C Code Generation for Functions That
Use OpenCV Library”
“System Objects in MATLAB Code Generation”
Tracking and Motion Estimation
assignDetectionsToTracks Supports MATLAB Function block: Yes
opticalFlowFarneback Supports MATLAB Function block: No
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries.
“Portable C Code Generation for Functions That
Use OpenCV Library”
opticalFlowHS Supports MATLAB Function block: No
Generated code for this function uses a
precompiled platform-specific shared library.
opticalFlowLKDoG Supports MATLAB Function block: No
Generated code for this function uses a
precompiled platform-specific shared library.
opticalFlowLK Supports MATLAB Function block: No
Generated code for this function uses a
precompiled platform-specific shared library.

4-191
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


vision.ForegroundDetector Supports MATLAB Function block: No
Generates platform-dependent library: Yes for
MATLAB host.
Generates portable C code for non-host target.
Generated code for this function uses a
precompiled platform-specific shared library.
“System Objects in MATLAB Code Generation”
vision.HistogramBasedTracker Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.KalmanFilter Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.PointTracker Supports MATLAB Function block: No
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries.
“Portable C Code Generation for Functions That
Use OpenCV Library”
“System Objects in MATLAB Code Generation”
vision.TemplateMatcher Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
Camera Calibration and Stereo Vision
bboxOverlapRatio Supports MATLAB Function block: No
bbox2points Supports MATLAB® Function block: Yes
disparity Compile-time constant input restriction:
'Method'.
Supports MATLAB Function block: No
Generates portable C code using a C++ compiler
that links to OpenCV (Version 2.4.9) libraries.
“Portable C Code Generation for Functions That
Use OpenCV Library”
cameraMatrix Supports MATLAB Function block: No
cameraPose Supports MATLAB Function block: No

4-192
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


cameraParameters Supports MATLAB Function block: No
Use the toStruct method to pass a
cameraParameters object into generated code.
See the “Code Generation for Depth Estimation
From Stereo Video” example.
detectCheckerboardPoints Supports MATLAB Function block: No
Code generation will not support specifying
images as file names or cell arrays of file names.
It supports only checkerboard detection in
a single image or stereo pair of images. For
example, these syntaxes are supported:

• detectCheckerboardPoints(I1)
• detectCheckerobarPoints(I1,I2)

I1 and I2 are single grayscale or RGB images.


generateCheckerboardPoints Supports MATLAB Function block: No
epipolarline Supports MATLAB Function block: Yes
estimateFundamentalMatrix Compile-time constant input restriction:
'Method', 'OutputClass', 'DistanceType',
and 'ReportRuntimeError'.
Supports MATLAB Function block: Yes
estimateUncalibratedRectification Supports MATLAB Function block: Yes
extrinsics Supports MATLAB Function block: No
isEpipoleInImage Supports MATLAB Function block: Yes
lineToBorderPoints Supports MATLAB Function block: Yes
reconstructScene Supports MATLAB Function block: No
rectifyStereoImages Compile-time constant input restriction:
'interp' and 'OutputView'
Supports MATLAB Function block: No
rotationMatrixToVector Supports MATLAB Function block: Yes
rotationVectorToMatrix Supports MATLAB Function block: Yes
selectStrongestBbox Supports MATLAB Function block: No

4-193
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


stereoAnaglyph Supports MATLAB Function block: Yes
stereoParameters Supports MATLAB Function block: No
Use the toStruct method to pass a
stereoParameters object into generated code.
See the “Code Generation for Depth Estimation
From Stereo Video” example.
triangulate Supports MATLAB Function block: No
undistortImage Compile-time constant input restriction:
'interp' and 'OutputView'
Supports MATLAB Function block: No
Statistics
vision.Autocorrelator Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.BlobAnalysis Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.Crosscorrelator Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.LocalMaximaFinder Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.Maximum Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.Mean Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.Median Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.Minimum Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.StandardDeviation Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.Variance Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
Filters, Transforms, and Enhancements

4-194
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


integralImage Supports MATLAB Function block: Yes
vision.Convolver Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.DCT Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.Deinterlacer Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.FFT Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.HoughLines Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.IDCT Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.IFFT Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.MedianFilter Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.Pyramid Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
Video Loading, Saving, and Streaming
vision.DeployableVideoPlayer Supports MATLAB Function block: Yes
Generated code for this function uses a
precompiled platform-specific shared library.
“System Objects in MATLAB Code Generation”
vision.VideoFileReader Supports MATLAB Function block: Yes
Generated code for this function uses a
precompiled platform-specific shared library.
“System Objects in MATLAB Code Generation”

Does not generate code for reading compressed


images on the Mac.

4-195
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


vision.VideoFileWriter Supports MATLAB Function block: Yes
Generated code for this function uses a
precompiled platform-specific shared library.
“System Objects in MATLAB Code Generation”
Color Space Formatting and Conversions
vision.ChromaResampler Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.DemosaicInterpolator Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.GammaCorrector Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
Graphics
insertMarker Compile-time constant input: 'Shape' and
'Color'
Supports MATLAB Function block: Yes
insertShape Compile-time constant input: 'Color' and
'SmoothEdges'
Supports MATLAB Function block: Yes
insertObjectAnnotation Supports MATLAB Function block: Yes
Limitation: Input image must be bounded, see
“Specify Variable-Size Data Without Dynamic
Memory Allocation”
“System Objects in MATLAB Code Generation”
insertText Compile-time constant input: Font, FontSize
Supports non-ASCII characters: No
Supports MATLAB Function block: Yes
vision.AlphaBlender Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.MarkerInserter Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”
vision.ShapeInserter Supports MATLAB Function block: Yes
“System Objects in MATLAB Code Generation”

4-196
Functions and Objects Supported for C and C++ Code Generation — Category List

Control Flow in MATLAB


Function Remarks and Limitations
break —
continue —
end —
for —
if, elseif, else —
parfor • Treated as a for-loop in a MATLAB Function block or when used with
fiaccel.
• See the parfor reference page in the MATLAB Coder documentation.
• “Generate Code with Parallel for-Loops (parfor)” on page 29-33.
return —
switch, case, • If all case expressions are scalar integer values, generates a C switch
otherwise statement. At run time, if the switch value is not an integer, generates
an error.
• When the case expressions contain noninteger or nonscalar values, the
code generation software generates C if statements in place of a C
switch statement.
while —

Data and File Management in MATLAB


Function Remarks and Limitations
computer • Information about the computer on which the code generation software
is running.
• Use only when the code generation target is S-function (Simulation) or
MEX-function.
fclose —
feof —
fopen • Does not support:

• machineformat, encoding, or fileID inputs

4-197
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


• message output
• fopen('all')
• If you disable extrinsic calls, you cannot return fileIDs created with
fopen to MATLAB or extrinsic functions. You can use such fileIDs
only internally.
• When generating C/C++ executables, static libraries, or dynamic
libraries, you can open up to 20 files.
• The generated code does not report errors from invalid file identifiers.
Write your own file open error handling in your MATLAB code. Test
whether fopen returns -1, which indicates that the file open failed. For
example:
...
fid = fopen(filename, 'r');
if fid == -1
% fopen failed

else
% fopen successful, okay to call fread
A = fread(fid);
...
• The behavior of the generated code for fread is compiler-dependent if
you:

1 Open a file using fopen with a permission of a+.


2 Read the file using fread before calling an I/O function, such as
fseek or frewind, that sets the file position indicator.

4-198
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


fprintf • Does not support:

• b and t subtypes on %u, %o %x, and %X formats.


• $ flag for reusing input arguments.
• printing arrays.
• There is no automatic casting. Input arguments must match their
format types for predictable results.
• Escaped characters are limited to the decimal range of 0–127.
• A call to fprintf with fileID equal to 1 or 2 becomes printf in the
generated C/C++ code in the following cases:

• The fprintf call is inside a parfor loop.


• Extrinsic calls are disabled.
• When the MATLAB behavior differs from the C compiler behavior,
fprintf matches the C compiler behavior in the following cases:

• The format specifier has a corresponding C format specifier, for


example, %e or %E.

• The fprintf call is inside a parfor loop.


• Extrinsic calls are disabled.
• When you call fprintf with the format specifier %s, do not put a null
character in the middle of the input string. Use fprintf(fid, '%c',
char(0)) to write a null character.
• When you call fprintf with an integer format specifier, the type of
the integer argument must be a type that the target hardware can
represent as a native C type. For example, if you call fprintf('%d',
int64(n)), the target hardware must have a native C type that
supports a 64-bit integer.

4-199
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


fread • precision must be a constant.
• The source and output that precision specifies cannot have values
long, ulong, unsigned long, bitN, or ubitN.
• You cannot use the machineformat input.
• If the source or output that precision specifies is a C type, for
example, int, the target and production sizes for that type must:

• Match.
• Map directly to a MATLAB type.
• The source type that precision specifies must map directly to a C
type on the target hardware.
• If the fread call reads the entire file, all of the data must fit in the
largest array available for code generation.
• If sizeA is not constant or contains a nonfinite element, then dynamic
memory allocation is required.
• Treats a char value for source or output as a signed 8-bit integer. Use
values between 0 and 127 only.
• The generated code does not report file read errors. Write your own
file read error handling in your MATLAB code. Test that the number
of bytes read matches the number of bytes that you requested. For
example:
...
N = 100;
[vals, numRead] = fread(fid, N, '*double');
if numRead ~= N
% fewer elements read than expected
end
...
frewind —

4-200
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


load • Use only when generating MEX or code for Simulink simulation. To load
compile-time constants, use coder.load.
• Does not support use of the function without assignment to a
structure or array. For example, use S = load(filename), not
load(filename).
• The output S must be the name of a structure or array without any
subscripting. For example, S(i) = load('myFile.mat') is not
allowed.
• Arguments to load must be compile-time constant strings.
• Does not support loading objects.
• If the MAT-file contains unsupported constructs, use
load(filename,variables) to load only the supported constructs.
• You cannot use save in a function intended for code generation.
The code generation software does not support the save function.
Furthermore, you cannot use coder.extrinsic with save. Prior to
generating code, you can use save to save the workspace data to a MAT-
file.

You must use coder.varsize to explicitly declare variable-size data


loaded using the load function.

Data Types in MATLAB

Function Remarks and Limitations


cell “Cell Array Requirements and Limitations for Code Generation” on page
9-10
deal —
fieldnames Does not support objects. The input must be a structure.
iscell —
isfield Does not support cell arrays for the second argument.
isobject —
isstruct —

4-201
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


narginchk —
nargoutchk —
str2func • String must be constant/known at compile time
struct • You cannot create a structure that contains a cell array. For example,
you cannot generate code for:
s = struct('a',{{1 2}})
• If the value argument is a cell array, all elements must have the same
type.
struct2cell • For a variable-size structure array, the resulting cell array must be
homogeneous. If s is a variable-size structure array, the fields must
have the same type.
• If struct2cell cannot convert s to a homogeneous cell array, the
output cell array is heterogeneous. A heterogeneous output cell array
can have a maximum of 1024 elements.
structfun • Does not support the ErrorHandler option.
• The number of outputs must be less than or equal to three.

Desktop Environment in MATLAB


Function Remarks and Limitations
ismac • Returns true or false based on the MATLAB version used for code
generation.
• Use only when the code generation target is S-function (Simulation)
or MEX-function.
ispc • Returns true or false based on the MATLAB version you use for code
generation.
• Use only when the code generation target is S-function (Simulation)
or MEX-function.
isunix • Returns true or false based on the MATLAB version used for code
generation.
• Use only when the code generation target is S-function (Simulation)
or MEX-function.

4-202
Functions and Objects Supported for C and C++ Code Generation — Category List

Discrete Math in MATLAB


Function Remarks and Limitations
factor • The maximum double precision input is 2^33.
• The maximum single precision input is 2^25.
• The input n cannot have type int64 or uint64.
gcd —
isprime • The maximum double precision input is 2^33.
• The maximum single precision input is 2^25.
• The input X cannot have type int64 or uint64.
lcm —
nchoosek • When the first input, x, is a scalar, nchoosek returns a binomial
coefficient. In this case, x must be a nonnegative integer. It cannot have
type int64 or uint64.
• When the first input, x, is a vector, nchoosek treats it as a set. In this
case, x can have type int64 or uint64.
• The second input, k, cannot have type int64 or uint64.
• “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35
primes • The maximum double precision input is 2^32.
• The maximum single precision input is 2^24.
• The input n cannot have type int64 or uint64.

DSP System Toolbox


C code generation for the following functions and System objects requires the DSP
System Toolbox license. Many DSP System Toolbox functions require constant inputs
for code generation. See “Define Constant Input Parameters Using the App” on page
18-23 and“Specify Constant Inputs at the Command Line” on page 21-52.

Name Remarks and Limitations


Estimation
dsp.BurgAREstimator “System Objects in MATLAB Code Generation”

4-203
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


dsp.BurgSpectrumEstimator “System Objects in MATLAB Code Generation”
dsp.CepstralToLPC “System Objects in MATLAB Code Generation”
dsp.CrossSpectrumEstimator “System Objects in MATLAB Code Generation”
dsp.LevinsonSolver “System Objects in MATLAB Code Generation”
dsp.LPCToAutocorrelation “System Objects in MATLAB Code Generation”
dsp.LPCToCepstral “System Objects in MATLAB Code Generation”
dsp.LPCToLSF “System Objects in MATLAB Code Generation”
dsp.LPCToLSP “System Objects in MATLAB Code Generation”
dsp.LPCToRC “System Objects in MATLAB Code Generation”
dsp.LSFToLPC “System Objects in MATLAB Code Generation”
dsp.LSPToLPC “System Objects in MATLAB Code Generation”
dsp.RCToAutocorrelation “System Objects in MATLAB Code Generation”
dsp.RCToLPC “System Objects in MATLAB Code Generation”
dsp.SpectrumEstimator “System Objects in MATLAB Code Generation”
dsp.TransferFunctionEstimator “System Objects in MATLAB Code Generation”
Filters
ca2tf All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
cl2tf All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
dsp.AdaptiveLatticeFilter “System Objects in MATLAB Code Generation”
dsp.AffineProjectionFilter “System Objects in MATLAB Code Generation”
dsp.AllpassFilter “System Objects in MATLAB Code Generation”

The System object supports code generation only


when the Structure property is set to Minimum
multiplier or Lattice.

4-204
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


dsp.AllpoleFilter • “System Objects in MATLAB Code
Generation”
• Only the Denominator property is tunable
for code generation.
dsp.BiquadFilter “System Objects in MATLAB Code Generation”
dsp.CICCompensationDecimator “System Objects in MATLAB Code Generation”
dsp.CICCompensationInterpolator “System Objects in MATLAB Code Generation”
dsp.CICDecimator “System Objects in MATLAB Code Generation”
dsp.CICInterpolator “System Objects in MATLAB Code Generation”
dsp.Differentiator “System Objects in MATLAB Code Generation”
dsp.FarrowRateConverter “System Objects in MATLAB Code Generation”
dsp.FastTransversalFilter “System Objects in MATLAB Code Generation”
dsp.FilterCascade • You cannot generate code directly from
dsp.FilterCascade. You can use the
generateFilteringCode method to
generate a MATLAB function. You can
generate C/C++ code from this MATLAB
function.
• “System Objects in MATLAB Code
Generation”
dsp.FilteredXLMSFilter “System Objects in MATLAB Code Generation”
dsp.FIRDecimator “System Objects in MATLAB Code Generation”
dsp.FIRFilter • “System Objects in MATLAB Code
Generation”
• Only the Numerator property is tunable for
code generation.
dsp.FIRHalfbandDecimator “System Objects in MATLAB Code Generation”
dsp.FIRHalfbandInterpolator “System Objects in MATLAB Code Generation”
dsp.FIRInterpolator “System Objects in MATLAB Code Generation”
dsp.FIRRateConverter “System Objects in MATLAB Code Generation”
dsp.FrequencyDomainAdaptiveFilter “System Objects in MATLAB Code Generation”

4-205
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


dsp.HighpassFilter “System Objects in MATLAB Code Generation”
dsp.IIRFilter • Only the Numerator and Denominator
properties are tunable for code generation.
• “System Objects in MATLAB Code
Generation”
dsp.IIRHalfbandDecimator “System Objects in MATLAB Code Generation”
dsp.IIRHalfbandInterpolator “System Objects in MATLAB Code Generation”
dsp.KalmanFilter “System Objects in MATLAB Code Generation”
dsp.LMSFilter “System Objects in MATLAB Code Generation”
dsp.LowpassFilter “System Objects in MATLAB Code Generation”
dsp.RLSFilter “System Objects in MATLAB Code Generation”
dsp.SampleRateConverter “System Objects in MATLAB Code Generation”
dsp.SubbandAnalysisFilter “System Objects in MATLAB Code Generation”
dsp.SubbandSynthesisFilter “System Objects in MATLAB Code Generation”
dsp.VariableBandwidthFIRFilter “System Objects in MATLAB Code Generation”
dsp.VariableBandwidthIIRFilter “System Objects in MATLAB Code Generation”
firceqrip All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
fireqint All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
firgr • All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
• Does not support syntaxes that have cell
array input.
firhalfband All inputs must be constant. Expressions or
variables are allowed if their values do not
change.

4-206
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


firlpnorm • All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
• Does not support syntaxes that have cell
array input.
firminphase All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
firnyquist All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
firpr2chfb All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
ifir All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
iircomb All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
iirgrpdelay • All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
• Does not support syntaxes that have cell
array input.
iirlpnorm • All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
• Does not support syntaxes that have cell
array input.

4-207
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


iirlpnormc • All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
• Does not support syntaxes that have cell
array input.
iirnotch All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
iirpeak All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
tf2ca All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
tf2cl All inputs must be constant. Expressions or
variables are allowed if their values do not
change.
Filter Design
designMultirateFIR The inputs to the function must be constants
Math Operations
dsp.ArrayVectorAdder “System Objects in MATLAB Code Generation”
dsp.ArrayVectorDivider “System Objects in MATLAB Code Generation”
dsp.ArrayVectorMultiplier “System Objects in MATLAB Code Generation”
dsp.ArrayVectorSubtractor “System Objects in MATLAB Code Generation”
dsp.CumulativeProduct “System Objects in MATLAB Code Generation”
dsp.CumulativeSum “System Objects in MATLAB Code Generation”
dsp.LDLFactor “System Objects in MATLAB Code Generation”
dsp.LevinsonSolver “System Objects in MATLAB Code Generation”
dsp.LowerTriangularSolver “System Objects in MATLAB Code Generation”
dsp.LUFactor “System Objects in MATLAB Code Generation”
dsp.Normalizer “System Objects in MATLAB Code Generation”

4-208
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


dsp.UpperTriangularSolver “System Objects in MATLAB Code Generation”
Quantizers
dsp.ScalarQuantizerDecoder “System Objects in MATLAB Code Generation”
dsp.ScalarQuantizerEncoder “System Objects in MATLAB Code Generation”
dsp.VectorQuantizerDecoder “System Objects in MATLAB Code Generation”
dsp.VectorQuantizerEncoder “System Objects in MATLAB Code Generation”
Scopes
dsp.SpectrumAnalyzer This System object does not generate code. It is
automatically declared as an extrinsic variable
using the coder.extrinsic function.
dsp.TimeScope This System object does not generate code. It is
automatically declared as an extrinsic variable
using the coder.extrinsic function.
Signal Management
dsp.Counter “System Objects in MATLAB Code Generation”
dsp.DelayLine “System Objects in MATLAB Code Generation”
Signal Operations
dsp.Convolver “System Objects in MATLAB Code Generation”
dsp.DCBlocker “System Objects in MATLAB Code Generation”
dsp.Delay “System Objects in MATLAB Code Generation”
dsp.DigitalDownConverter “System Objects in MATLAB Code Generation”
dsp.DigitalUpConverter “System Objects in MATLAB Code Generation”
dsp.Interpolator “System Objects in MATLAB Code Generation”
dsp.NCO “System Objects in MATLAB Code Generation”
dsp.PeakFinder “System Objects in MATLAB Code Generation”
dsp.PhaseExtractor “System Objects in MATLAB Code Generation”
dsp.PhaseUnwrapper “System Objects in MATLAB Code Generation”
dsp.VariableFractionalDelay “System Objects in MATLAB Code Generation”
dsp.VariableIntegerDelay “System Objects in MATLAB Code Generation”

4-209
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


dsp.Window • This object has no tunable properties for code
generation.
• “System Objects in MATLAB Code
Generation”
dsp.ZeroCrossingDetector “System Objects in MATLAB Code Generation”
Sinks
audioDeviceWriter “System Objects in MATLAB Code Generation”
dsp.AudioFileWriter “System Objects in MATLAB Code Generation”
dsp.UDPSender “System Objects in MATLAB Code Generation”
Sources
dsp.AudioFileReader “System Objects in MATLAB Code Generation”
dsp.SignalSource “System Objects in MATLAB Code Generation”
dsp.SineWave • This object has no tunable properties for code
generation.
• “System Objects in MATLAB Code
Generation”
dsp.UDPReceiver “System Objects in MATLAB Code Generation”
Statistics
dsp.Autocorrelator “System Objects in MATLAB Code Generation”
dsp.Crosscorrelator “System Objects in MATLAB Code Generation”
dsp.Histogram • This object has no tunable properties for code
generation.
• “System Objects in MATLAB Code
Generation”
dsp.Maximum “System Objects in MATLAB Code Generation”
dsp.Mean “System Objects in MATLAB Code Generation”
dsp.Median “System Objects in MATLAB Code Generation”
dsp.Minimum “System Objects in MATLAB Code Generation”
dsp.PeakToPeak “System Objects in MATLAB Code Generation”

4-210
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


dsp.PeakToRMS “System Objects in MATLAB Code Generation”
dsp.RMS “System Objects in MATLAB Code Generation”
dsp.StandardDeviation “System Objects in MATLAB Code Generation”
dsp.StateLevels “System Objects in MATLAB Code Generation”
dsp.Variance “System Objects in MATLAB Code Generation”
Transforms
dsp.AnalyticSignal “System Objects in MATLAB Code Generation”
dsp.DCT “System Objects in MATLAB Code Generation”
dsp.FFT “System Objects in MATLAB Code Generation”
dsp.IDCT “System Objects in MATLAB Code Generation”
dsp.IFFT “System Objects in MATLAB Code Generation”

Error Handling in MATLAB


Function Remarks and Limitations
assert • Generates specified error messages at compile time only if all input
arguments are constants or depend on constants. Otherwise, generates
specified error messages at run time.
• If called with more than 1 argument, has no effect in standalone code
even when run-time error detection is enabled. See “Run-Time Error
Detection and Reporting in Standalone C/C++ Code” on page 22-29.
• See “Rules for Using assert Function” on page 21-72.
error Has no effect in standalone code even when run-time error detection is
enabled. See “Run-Time Error Detection and Reporting in Standalone C/C+
+ Code” on page 22-29.

Exponents in MATLAB
Function Remarks and Limitations
exp —
expm —

4-211
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


expm1 —
factorial —
log • Generates an error during simulation and returns NaN in generated
code when the input value x is real, but the output should be complex.
To get the complex result, make the input value complex by passing in
complex(x).
log2 —
log10 —
log1p —
nextpow2 —
nthroot —
reallog —
realpow —
realsqrt —
sqrt • Generates an error during simulation and returns NaN in generated
code when the input value x is real, but the output should be complex.
To get the complex result, make the input value complex by passing in
complex(x).

Filtering and Convolution in MATLAB

Function Remarks and Limitations


conv —
conv2 —
convn —
deconv —
detrend • If supplied and not empty, the input argument bp must satisfy the
following requirements:

• Be real.
• Be sorted in ascending order.

4-212
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


• Restrict elements to integers in the interval [1, n-2]. n is the
number of elements in a column of input argument X , or the number
of elements in X when X is a row vector.
• Contain all unique values.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35

filter —
filter2 —

Fixed-Point Designer
In addition to function-specific limitations listed in the table, the following general
limitations apply to the use of Fixed-Point Designer functions in generated code, with
fiaccel:

• fipref and quantizer objects are not supported.


• Word lengths greater than 128 bits are not supported.
• You cannot change the fimath or numerictype of a given fi variable after that
variable has been created.
• The boolean value of the DataTypeMode and DataType properties are not
supported.
• For all SumMode property settings other than FullPrecision, the CastBeforeSum
property must be set to true.
• You can use parallel for (parfor) loops in code compiled with fiaccel, but those
loops are treated like regular for loops.
• When you compile code containing fi objects with nontrivial slope and bias scaling,
you may see different results in generated code than you achieve by running the same
code in MATLAB.
• The general limitations of C/C++ code generated from MATLAB apply. For
more information, see “MATLAB Language Features Supported for C/C++ Code
Generation” on page 2-13.

Function Remarks/Limitations
abs N/A

4-213
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
accumneg N/A
accumpos N/A
add • Code generation in MATLAB does not support the syntax
F.add(a,b). You must use the syntax add(F,a,b).
all N/A
any N/A
atan2 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 Generated code may not handle out of range shifting.
bitsra Generated code may not handle out of range shifting.
bitsrl Generated code may not handle out of range shifting.
bitxor Not supported for slope-bias scaled fi objects.
bitxorreduce N/A
ceil N/A
complex N/A
conj N/A

4-214
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks/Limitations
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


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.
cordicsqrt Variable-size signals are not supported.
cos N/A
ctranspose N/A
diag If supplied, the index, k, must be a real and scalar integer value that is
not a fi object.

4-215
4 Functions, Classes, and System Objects Supported for Code Generation

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 For the automated workflow, do not use explicit double or single casts
in your MATLAB algorithm to insulate functions that do not support
fixed-point data types. The automated conversion tool does not support
these casts. Instead of using casts, supply a replacement function. For
more information, see “Function Replacements”.
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 • The default constructor syntax without any input arguments is not
supported.
• If the numerictype is not fully specified, the input to fi must be a
constant, a fi, a single, or a built-in integer value. If the input is a
built-in double value, it must be a constant. This limitation allows
fi to autoscale its fraction length based on the known data type of
the input.
• All properties related to data type must be constant for code
generation.
• numerictype object information must be available for nonfixed-
point Simulink inputs.
filter • Variable-sized inputs are only supported when the SumMode
property of the governing fimath is set to Specify precision or
Keep LSB.

4-216
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks/Limitations
fimath • Fixed-point signals coming in to a MATLAB Function block from
Simulink are assigned a fimath object. You define this object in
the MATLAB Function block dialog in the Model Explorer.
• Use to create fimath objects in the generated code.
• If the ProductMode property of the fimath object is set to
anything other than FullPrecision, the ProductWordLength
and ProductFractionLength properties must be constant.
• If the SumMode property of the fimath object is set to anything
other than FullPrecision, the SumWordLength and
SumFractionLength properties must be constant.
fix N/A
fixed.Quantizer N/A
flip The dimensions argument must be a built-in type; it cannot be a fi
object.
fliplr N/A
flipud N/A
floor N/A
for N/A
ge Not supported for fixed-point signals with different biases.
get The syntax structure = get(o) is not supported.
getlsb N/A
getmsb N/A
gt Not supported for fixed-point signals with different biases.
horzcat N/A
imag N/A
int8, int16, int32, N/A
int64
ipermute N/A
iscolumn N/A
isempty N/A

4-217
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
isequal N/A
isfi Avoid using the isfi function in code that you intend to convert
using the automated workflow. The value returned by isfi in the
fixed-point code might differ from the value returned in the original
MATLAB algorithm. The behavior of the fixed-point code might differ
from the behavior of the original algorithm.
isfimath N/A
isfimathlocal N/A
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

4-218
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks/Limitations
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.
mpower • When the exponent k is a variable and the input is a scalar,
the ProductMode property of the governing fimath must be
SpecifyPrecision.
• When the exponent k is a variable and the input is not scalar,
the SumMode property of the governing fimath must be
SpecifyPrecision.
• Variable-sized inputs are only supported when the SumMode
property of the governing fimath is set to SpecifyPrecision 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


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 • Code generation in MATLAB does not support the syntax
F.mpy(a,b). You must use the syntax mpy(F,a,b).
• 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

4-219
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
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 SpecifyPrecision or
KeepLSB.
• 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


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.
ndims N/A
ne Not supported for fixed-point signals with different biases.
nearest N/A
numberofelements numberofelements will be removed in a future release. Use numel
instead.
numel N/A
numerictype • Fixed-point signals coming in to a MATLAB Function block from
Simulink are assigned a numerictype object that is populated
with the signal's data type and scaling information.
• Returns the data type when the input is a nonfixed-point signal.
• Use to create numerictype objects in generated code.
• All numerictype object properties related to the data type must be
constant.
permute The dimensions argument must be a built-in type; it cannot be a fi
object.
plus Any non-fi inputs must be constant; that is, its value must be known
at compile time so that it can be cast to a fi object.
pow2 N/A

4-220
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks/Limitations
power When the exponent k is a variable, the ProductMode property of the
governing fimath must be SpecifyPrecision.
qr N/A
quantize N/A
range N/A
rdivide N/A
real N/A
realmax N/A
realmin N/A
reinterpretcast N/A
removefimath N/A
repmat The dimensions argument must be a built-in type; it cannot be a fi
object.
rescale N/A
reshape N/A
rot90 In the syntax rot90(A,k), the argument k must be a built-in type; it
cannot be a fi object.
round N/A
setfimath N/A
sfi • All properties related to data type must be constant for code
generation.
shiftdim The dimensions argument must be a built-in type; it cannot be a fi
object.
sign N/A
sin N/A
single For the automated workflow, do not use explicit double or single casts
in your MATLAB algorithm to insulate functions that do not support
fixed-point data types. The automated conversion tool does not support
these casts. Instead of using casts, supply a replacement function. For
more information, see “Function Replacements”.

4-221
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
size N/A
sort The dimensions argument must be a built-in type; it cannot be a fi
object.
squeeze N/A
sqrt • Complex and [Slope Bias] inputs error out.
• Negative inputs yield a 0 result.
storedInteger N/A
storedIntegerToDouble N/A
sub • Code generation in MATLAB does not support the syntax
F.sub(a,b). You must use the syntax sub(F,a,b).
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.
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 • All properties related to data type must be constant for code
generation.
uint8, uint16, uint32, N/A
uint64
uminus N/A

4-222
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks/Limitations
uplus N/A
upperbound N/A
vertcat N/A

HDL Coder
Function Remarks and Limitations
hdl.RAM This System object is available with MATLAB.

Histograms in MATLAB
Function Remarks and Limitations
hist • Histogram bar plotting not supported. Call with at least one output
argument.
• If supplied, the second argument x must be a scalar constant.
• Inputs must be real.

For the syntax [nout, xout] = hist(y,x):

• When y is a fixed-size vector or variable-length vector:

• nout is always a row vector.


• If x is a vector, xout is a vector with the same orientation as x.
• If x is a scalar (fixed-size), xout is a row vector.
• nout and xout are column vectors when the following conditions are
true:

• y is a matrix
• size(y,1) and size(y,2) do not have fixed length 1
• One of size(y,1) and size(y,2) has length 1 at run time
• A variable-sizex is interpreted as a vector input even if it is a scalar at
run time.
• If at least one of the inputs is empty, vector orientations in the output
can differ from MATLAB.

4-223
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


histc • The output of a variable-size array that becomes a column vector at run
time is a column-vector, not a row-vector.
• If supplied, dim must be a constant.
• “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35

Image Acquisition Toolbox


If you install Image Acquisition Toolbox software, you can generate C and C++ code for
the VideoDevice System object. See imaq.VideoDevice and “Code Generation with
VideoDevice System Object”.

Image Processing in MATLAB


Function Remarks and Limitations
im2double —
rgb2gray —

Image Processing Toolbox


The following table lists the Image Processing Toolbox functions that have been enabled
for code generation. You must have the MATLAB Coder and Image Processing Toolbox
software installed to generate C code from MATLAB for these functions.

Image Processing Toolbox provides three types of code generation support:

• Functions that generate C code.


• Functions that generate C code that depends on a platform-specific shared library
(.dll, .so, or .dylib). Use of a shared library preserves performance optimizations
in these functions, but this limits the target platforms for which you can generate
code. For more information, see “Code Generation for Image Processing”.
• Functions that generate C code or C code that depends on a shared library, depending
on which target platform you specify in MATLAB Coder. If you specify the generic
MATLAB Host Computer target platform, these functions generate C code that
depends on a shared library. If you specify any other target platform, these functions
generate C code.

4-224
Functions and Objects Supported for C and C++ Code Generation — Category List

In generated code, each supported toolbox function has the same name, arguments, and
functionality as its Image Processing Toolbox counterpart. However, some functions have
limitations. The following table includes information about code generation limitations
that might exist for each function. In the following table, all the functions generate C
code. The table identifies those functions that generate C code that depends on a shared
library, and those functions that can do both, depending on which target platform you
choose.

Function Remarks/Limitations
adaptthresh The ForegroundPolarity and Statistic arguments must be
compile-time constants.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The NeighborhoodSize


argument must be a compile-time constant.
affine2d When generating code, you can only specify single objects—arrays of
objects are not supported.

MATLAB Function Block support: Yes.


boundarymask The conn argument must be a compile-time constant.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


bwareaopen BW must be a 2-D binary image. N-D arrays are not supported. conn
can only be one of the two-dimensional connectivities (4 or 8) or a 3-
by-3 matrix. The 3-D connectivities (6, 18, and 26) are not supported.
Matrices of size 3-by-3-by-...-by-3 are not supported. conn must be a
compile-time constant.

MATLAB Function Block support: No.


bwboundaries The conn and options arguments must be compile-time constants and
the return value A can only be a full matrix, not a sparse matrix.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

4-225
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
MATLAB Function Block support: No.
bwconncomp The input image must be 2-D.

The conn argument must be a compile-time constant and the only


connectivities supported are 4 or 8. You can specify connectivity as a 3-
by-3 matrix, but it can only be [0 1 0;1 1 1;0 1 0] or ones(3).

The CC struct return value does not include the PixelIdxList field.

MATLAB Function Block support: No.


bwdist The method argument must be a compile-time constant. Input images
must have fewer than 232 pixels.

Generated code for this function uses a precompiled, platform-specific


shared library.

MATLAB Function Block support: Yes.


bweuler If you choose the generic MATLAB Host Computer target platform,
generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


bwlabel When generating code, the parameter n must be a compile-time
constant.

MATLAB Function Block support: No.


bwlookup For best results, specify an input image of class logical.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-226
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks/Limitations
bwmorph The text string specifying the operation must be a constant and, for
best results, specify an input image of class logical.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: No.


bwpack Generated code for this function uses a precompiled platform-specific
shared library.

MATLAB Function Block support: Yes.


bwperim Supports only 2-D images. Does not support any no-output-argument
syntaxes. The connectivity matrix input argument, conn, must be a
compile-time constant.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


bwselect Supports only the 3 and 4 input argument syntaxes: BW2 =
bwselect(BW,c,r) and BW2 = bwselect(BW,c,r,n). The optional
fourth input argument, n, must be a compile-time constant. In addition,
with code generation, bwselect only supports only the 1 and 2 output
argument syntaxes: BW2 = bwselect(___) or [BW2, idx] =
bwselect(___).

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


bwtraceboundary The dir, fstep, and conn arguments must be compile-time constants.

MATLAB Function Block support: No.

4-227
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
bwunpack Generated code for this function uses a precompiled platform-specific
shared library.

MATLAB Function Block support: Yes. The input argument M must be


a compile-time constant.
conndef Input arguments must be compile-time constants.

MATLAB Function Block support: Yes.


demosaic The sensorAlignment argument must be a compile-time constant.

MATLAB Function Block support: Yes.


edge The method, direction, and sigma arguments must be a compile-
time constants. In addition, nonprogrammatic syntaxes are not
supported. For example, the syntax edge(im), where edge does not
return a value but displays an image instead, is not supported.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The input arguments thresh


and sigma must be compile-time constants.
fitgeotrans The transformtype argument must be a compile-time constant.
The function supports the following transformation types:
'nonreflectivesimilarity', 'similarity', 'affine', or
'projective'.

MATLAB Function Block support: Yes.


fspecial Inputs must be compile-time constants. Expressions or variables are
allowed if their values do not change.

MATLAB Function Block support: Yes. The input arguments hsize,


radius, len, and theta must be compile-time constants.
getrangefromclass MATLAB Function Block support: Yes.

4-228
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks/Limitations
grayconnected If you choose the generic MATLAB Host Computer target platform,
generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


histeq All the syntaxes that include indexed images are not supported. This
includes all syntaxes that accept map as input and return newmap.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The input argument N must be


a compile-time constant.
hough The optional parameter names 'Theta' and 'RhoResolution' must
be compile-time string constants. The optional Theta vector must have
a bounded size.

MATLAB Function Block support: Yes. The input argument BW must


be fixed size, the RhoResolution parameter must be a compile-time
constant, and the Theta vector must have a bounded size.
houghlines The optional parameter names 'FillGap' and 'MinLength' must
be compile-time string constants. Their associated values need not be
compile-time constants.

MATLAB Function Block support: No.


houghpeaks The optional parameter names 'Threshold' and 'NHoodSize' must
be compile-time string constants. Their associated values need not be
compile-time constants.

MATLAB Function Block support: Yes.


im2int16 If you choose the generic MATLAB Host Computer target platform,
generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


im2uint8 If you choose the generic MATLAB Host Computer target platform,
generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-229
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
im2uint16 If you choose the generic MATLAB Host Computer target platform,
generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


im2single MATLAB Function Block support: Yes.
im2double MATLAB Function Block support: Yes.
imabsdiff MATLAB Function Block support: Yes.
imadjust Does not support syntaxes that include indexed images. This includes
all syntaxes that accept map as input and return newmap.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imbinarize String input arguments must be compile-time constants.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imbothat The input image IM must be either 2-D or 3-D image. The structuring
element input argument SE must be a compile-time constant.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imboxfilt MATLAB Function Block support: Yes.
imclearborder The optional second input argument, conn, must be a compile-time
constant. Supports only up to 3-D inputs.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-230
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks/Limitations
imclose The input image IM must be either 2-D or 3-D image. The structuring
element input argument SE must be a compile-time constant.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imcomplement Does not support int64 and uint64 data types.

MATLAB Function Block support: Yes.


imcrop The interactive syntaxes, such as I2 = imcrop, are not supported.
Indexed images are not supported, including the noninteractive syntax
X2 = imcrop(X,map,rect);.

MATLAB Function Block support: Yes.


imdilate The input image IM must be either 2-D or 3-D image. The SE, PACKOPT,
and SHAPE input arguments must be a compile-time constant. The
structuring element argument SE must be a single element—arrays of
structuring elements are not supported. To obtain the same result as
that obtained using an array of structuring elements, call the function
sequentially.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imerode The input image IM must be either 2-D or 3-D image. The SE, PACKOPT,
and SHAPE input arguments must be a compile-time constant. The
structuring element argument SE must be a single element—arrays of
structuring elements are not supported. To obtain the same result as
that obtained using an array of structuring elements, call the function
sequentially.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-231
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
imextendedmax The optional third input argument, conn, must be a compile-time
constant.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imextendedmin The optional third input argument, conn, must be a compile-time
constant.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imfill The optional input connectivity, conn and the string 'holes' must be
compile-time constants.

Supports only up to 3-D inputs.

The interactive mode to select points, imfill(BW,0,CONN) is not


supported in code generation.

locations can be a P-by-1 vector, in which case it contains the


linear indices of the starting locations. locations can also be a P-
by-ndims(I) matrix, in which case each row contains the array indices
of one of the starting locations. Once you select a format at compile-
time, you cannot change it at run time. However, the number of points
in locations can be varied at run time.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-232
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks/Limitations
imfilter The input image can be either 2-D or 3-D. The value of the input
argument, options, must be a compile-time constant.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imfindcircles All string input arguments and values must be compile-time constants.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: No.


imgaborfilt MATLAB Function Block support: No.
imgaussfilt String input arguments must be compile-time constants.

When FilterDomain is 'spatial’, if you choose the generic MATLAB


Host Computer target platform, generated code uses a precompiled,
platform-specific shared library.

MATLAB Function Block support: Yes.


imgradient3 String input arguments must be compile-time constants.

MATLAB Function Block support: Yes.


imgradientxyz String input arguments must be compile-time constants.

MATLAB Function Block support: Yes.


imhist The optional second input argument, n, must be a compile-time
constant. In addition, nonprogrammatic syntaxes are not supported.
For example, the syntaxes where imhist displays the histogram are
not supported.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The input argument N must be


a compile-time constant.

4-233
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
imhmax The optional third input argument, conn, must be a compile-time
constant

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imhmin The optional third input argument, conn, must be a compile-time
constant

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imlincomb The output_class argument must be a compile-time constant. You
can specify up to four input image arguments.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


immse MATLAB Function Block support: Yes.
imopen The input image IM must be either 2-D or 3-D image. The structuring
element input argument SE must be a compile-time constant.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imoverlay If you specify the 'color' argument as a string, it must be a compile-
time constant.

MATLAB Function Block support: Yes.


impyramid The direction argument must be a compile-time constant.

MATLAB Function Block support: Yes. The input argument direction


must be a compile-time constant.

4-234
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks/Limitations
imquantize MATLAB Function Block support: Yes.
imread Supports reading of 8-bit JPEG images only. The file name input
argument must be a valid absolute path or relative path.

This function generates code that uses a precompiled, platform-specific


shared library.

MATLAB Function Block support: Yes. The file name input argument
must be a compile-time constant.
imreconstruct The optional third input argument, conn, must be a compile-time
constant.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imref2d The XWorldLimits, YWorldLimits and ImageSize properties can be
set only during object construction. When generating code, you can only
specify single objects—arrays of objects are not supported.

MATLAB Function Block support: Yes.


imref3d The XWorldLimits, YWorldLimits, ZWorldLimits and ImageSize
properties can be set only during object construction. When generating
code, you can only specify single objects—arrays of objects are not
supported.

MATLAB Function Block support: Yes.


imregionalmax The optional second input argument, conn, must be a compile-time
constant.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-235
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
imregionalmin The optional second input argument, conn, must be a compile-time
constant.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imresize Does not support indexed images or custom interpolation kernels. All
parameter-value pair input arguments must be compile-time constants.

MATLAB Function Block support: Yes. The input arguments Scale


and method must be compile-time constants, and the values of the
OutputSize parameter, numrows and numcols, must be compile-time
constants.
imrotate The method and bbox input argument values must be compile-time
constants.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The input argument angle


must be a compile-time constant.
imtophat The input image IM must be either 2-D or 3-D image. The structuring
element input argument SE must be a compile-time constant.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


imtranslate The supports only 2-D translation vectors. 3-D translations are not
supported

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The input argument


translation must be a compile-time constant.

4-236
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks/Limitations
imwarp The geometric transformation object input, tform, must be either
affine2d or projective2d. Additionally, the interpolation method
and optional parameter names must be string constants.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The input argument tform


must be a compile-time constant.
integralBoxFilter The 'NormalizationFactor' parameter must be a compile-time
constant.

MATLAB Function Block support: Yes. The input argument


filtersize must be a compile-time constant.
intlut If you choose the generic MATLAB Host Computer target platform,
generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


iptcheckconn Input arguments must be compile-time constants.

MATLAB Function Block support: Yes.


iptcheckmap MATLAB Function Block support: Yes.
lab2rgb String input arguments must be compile-time constants.

MATLAB Function Block support: Yes.


label2idx MATLAB Function Block support: No.

4-237
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
label2rgb Referring to the standard syntax:
RGB = label2rgb(L, map, zerocolor, order)

• 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'.

MATLAB Function Block support: Yes.


mean2 MATLAB Function Block support: Yes.
medfilt2 The padopt argument must be a compile-time constant.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The neighborhood size input


argument must be a compile-time constant.
multithresh If you choose the generic MATLAB Host Computer target platform,
generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes. The input argument N must be


compile-time constant.
offsetstrel The 'ball’ input argument and all other input arguments must be
compile-time constants. None of the methods are supported for code
generation. When generating code, you can only specify single objects—
arrays of objects are not supported.

MATLAB Function Block support: Yes.

4-238
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks/Limitations
ordfilt2 The padopt argument must be a compile-time constant.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


otsuthresh MATLAB Function Block support: Yes.
padarray Support only up to 3-D inputs.

Input arguments, padval and direction are expected to be compile-


time constants.

MATLAB Function Block support: Yes. The input argument padsize


must be a compile-time constant.
projective2d When generating code, you can only specify single objects—arrays of
objects are not supported.

MATLAB Function Block support: Yes.


psnr MATLAB Function Block support: Yes.
regionprops Supports only 2-D images. Does not support the table output type.
Does not accept cell arrays as input—use a comma-separated list
instead. Does not support the properties ConvexArea, ConvexHull,
ConvexImage, Solidity, and SubarrayIdx.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: No.


rgb2gray MATLAB Function Block support: Yes.
rgb2lab String input arguments must be compile-time constants.

MATLAB Function Block support: Yes.


rgb2ycbcr If you choose the generic MATLAB Host Computer target platform,
generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

4-239
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
strel All of the input arguments must be compile-time constants. None of the
methods are supported for code generation. When generating code, you
can only specify single objects—arrays of objects are not supported.

MATLAB Function Block support: Yes.


stretchlim If you choose the generic MATLAB Host Computer target platform,
generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.


superpixels String input arguments must be compile-time constants. The value of
'IsInputLab' (true or false) must be a compile-time constant.

MATLAB Function Block support: No.


watershed Supports only 2-D images. Supports only 4- or 8-connectivity. Supports
only up to 65,535 regions. The output type is always uint16.

If you choose the generic MATLAB Host Computer target platform,


generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: No.


ycbcr2rgb If you choose the generic MATLAB Host Computer target platform,
generated code uses a precompiled, platform-specific shared library.

MATLAB Function Block support: Yes.

Input and Output Arguments in MATLAB


Function Remarks and Limitations
nargin —
nargout • For a function with no output arguments,
returns 1 if called without a terminating
semicolon.

Note: This behavior also affects extrinsic calls


with no terminating semicolon. nargout is 1 for
the called function in MATLAB.

4-240
Functions and Objects Supported for C and C++ Code Generation — Category List

Interpolation and Computational Geometry in MATLAB

Function Remarks and Limitations


cart2pol —
cart2sph —
interp1 • Does not support the 'cubic' method. Instead, use 'v5cubic' or
'spline'.
• The input argument x (sample points) must be strictly increasing or
strictly decreasing. Indices are not reordered.
• If the input argument v (sample values) is a variable-length vector
(1-by-: or :-by-1), the shape of the output vq matches the shape in
MATLAB.

If the input argument v is variable-size, is not a variable-length vector,


and becomes a row vector at run time, an error occurs.
• If the input argument xq (query points) is variable-size, is not a
variable-length vector, and becomes a row or column vector at run time,
an error occurs.
• “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35
interp1q Might not match MATLAB when some Y values are Inf or NaN.
interp2 • Xq and Yq must be the same size. Use meshgrid to evaluate on a grid.
• For best results, provide X and Y as vectors.
• For the 'cubic' method, reports an error if the grid does not have
uniform spacing. In this case, use the 'spline' method.
• For best results when you use the 'spline' method:

• Use meshgrid to create the inputs Xq and Yq.


• Use a small number of interpolation points relative to the dimensions
of V. Interpolating over a large set of scattered points can be
inefficient.
interp3 • Xq, Yq, and Zq must be the same size. Use meshgrid to evaluate on a
grid.
• For best results, provide X, Y, and Z as vectors.

4-241
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


• For the 'cubic' method, reports an error if the grid does not have
uniform spacing. In this case, use the 'spline' method.
• For best results when you use the 'spline' method:

• Use meshgrid to create the inputs Xq, Yq, and Zq.


• Use a small number of interpolation points relative to the dimensions
of V. Interpolating over a large set of scattered points can be
inefficient.
interpn • For best results, provide X1,X2,...,Xn as vectors.
• Does not support the 'cubic' or 'spline' methods for 2-D and higher
interpolation.
• The interpolation method must be a constant string.
meshgrid —

4-242
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


mkpp • The output structure pp differs from the pp structure in MATLAB. In
MATLAB, ppval cannot use the pp structure from the code generation
software. For code generation, ppval cannot use a pp structure
created by MATLAB. unmkpp can use a MATLAB pp structure for code
generation.

To create a MATLAB pp structure from a pp structure created by the


code generation software:

• In code generation, use unmkpp to return the piecewise polynomial


details to MATLAB.
• In MATLAB, use mkpp to create the pp structure.
• If you do not provide d, then coefs must be two-dimensional and have
a fixed number of columns. In this case, the number of columns is the
order.
• To define a piecewise constant polynomial, coefs must be a column
vector or d must have at least two elements.
• If you provide d and d is 1, d must be a constant. Otherwise, if the input
to ppval is nonscalar, the shape of the output of ppval can differ from
ppval in MATLAB.
• If you provide d, it must have a fixed length. One of the following sets of
statements must be true:

1 Suppose that m = length(d) and npieces = length(breaks)


- 1.

size(coefs,j) = d(j)
size(coefs,m+1) = npieces
size(coefs,m+2) = order
j = 1,2,...,m. The dimension m+2 must be fixed length.
2 Suppose that m = length(d) and npieces = length(breaks)
- 1.

size(coefs,1) = prod(d)*npieces
size(coefs,2) = order
The second dimension must be fixed length.
• If you do not provide d, the following statements must be true:

4-243
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


Suppose that m = length(d) and npieces = length(breaks) - 1.

size(coefs,1) = prod(d)*npieces
size(coefs,2) = order
The second dimension must be fixed length.

pchip • Input x must be strictly increasing.


• Does not remove y entries with NaN values.
• If you generate code for the pp = pchip(x,y) syntax, you cannot
input pp to the ppval function in MATLAB. To create a MATLAB pp
structure from a pp structure created by the code generation software:

• In code generation, use unmkpp to return the piecewise polynomial


details to MATLAB.
• In MATLAB, use mkpp to create the pp structure.
pol2cart —
polyarea —
ppval The size of output v does not match MATLAB when both of the following
statements are true:

• The input x is a variable-size array that is not a variable-length vector.


• x becomes a row vector at run time.

The code generation software does not remove the singleton dimensions.
However, MATLAB might remove singleton dimensions.

For example, suppose that x is a :4-by-:5 array (the first dimension is


variable size with an upper bound of 4 and the second dimension is variable
size with an upper bound of 5). Suppose that ppval(pp,0) returns a 2-
by-3 fixed-size array. v has size 2-by-3-by-:4-by-:5. At run time, suppose
that, size(x,1) =1 and size (x,2) = 5. In the generated code, the size(v) is
[2,3,1,5]. In MATLAB, the size is [2,3,5].
rectint —
sph2cart —

4-244
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


spline • Input x must be strictly increasing.
• Does not remove Y entries with NaN values.
• Does not report an error for infinite endslopes in Y.
• If you generate code for the pp = spline(x,Y) syntax, you cannot
input pp to the ppval function in MATLAB. To create a MATLAB pp
structure from a pp structure created by the code generation software:

• In code generation, use unmkpp to return the piecewise polynomial


details to MATLAB.
• In MATLAB, use mkpp to create the pp structure.
unmkpp • pp must be a valid piecewise polynomial structure created by mkpp,
spline, or pchip in MATLAB or by the code generation software.
• Does not support pp structures created by interp1 in MATLAB.

Linear Algebra in MATLAB

Function Remarks and Limitations


bandwidth —
isbanded —
isdiag —
ishermitian —
istril —
istriu —
issymmetric —
linsolve • 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

4-245
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


• UHESS = true (the TRANSA can be either true or false)
• SYM = true and POSDEF = true

Other options are equivalent to using mldivide.

lsqnonneg • You must enable support for variable-size arrays.


• The message string in the output structure output (the fifth output) is
not translated.
null • Might return a different basis than MATLAB
• Does not support rational basis option (second input)
orth • Can return a different basis than MATLAB
rsf2csf —
schur Can return a different Schur decomposition in generated code than in
MATLAB.
sqrtm —

Logical and Bit-Wise Operations in MATLAB

Function Remarks and Limitations


and —
bitand —
bitcmp —
bitget —
bitor —
bitset —
bitshift —
bitxor —
not —
or —
xor —

4-246
Functions and Objects Supported for C and C++ Code Generation — Category List

MATLAB Compiler
C and C++ code generation for the following functions requires the MATLAB Compiler
software.

Function Remarks and Limitations


isdeployed • Returns true and false as appropriate for MEX and SIM targets
• Returns false for other targets
ismcc • Returns true and false as appropriate for MEX and SIM targets.
• Returns false for other targets.

Matrices and Arrays in MATLAB


Function Remarks and Limitations
abs —
all “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35
angle —
any “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35
blkdiag —
bsxfun “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35
cat • Does not support concatenation of cell arrays.
• If supplied, dim must be a constant.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
circshift Does not support cell arrays for the first argument.
colon • Does not accept complex inputs.
• The input i cannot have a logical value.
• Does not accept vector inputs.
• Inputs must be constants.
• Uses single-precision arithmetic to produce single-precision results.

4-247
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


compan —
cond “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35
cov • If the input is variable-size and is [] at run time, returns [] not
NaN.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
cross • If supplied, dim must be a constant.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
cumprod Does not support logical inputs. Cast input to double first.
cumsum Does not support logical inputs. Cast input to double first.
det —

4-248
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


diag • If supplied, the argument representing the order of the diagonal
matrix must be a real and scalar integer value.
• For variable-size inputs that are variable-length vectors (1-by-: or :-
by-1), diag:

• Treats the input as a vector input.


• Returns a matrix with the given vector along the specified
diagonal.

• For variable-size inputs that are not variable-length vectors, diag:

• Treats the input as a matrix.


• Does not support inputs that are vectors at run time.
• Returns a variable-length vector.

If the input is variable-size (:m-by-:n) and has shape 0-by-0 at run


time, the output is 0-by-1 not 0-by-0. However, if the input is a
constant size 0-by-0, the output is [].
• For variable-size inputs that are not variable-length vectors (1-by-:
or :-by-1), diag treats the input as a matrix from which to extract
a diagonal vector. This behavior occurs even if the input array is a
vector at run time. To force diag to build a matrix from variable-
size inputs that are not 1-by-: or :-by-1, use:

• diag(x(:)) instead of diag(x)


• diag(x(:),k) instead of diag(x,k)
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
diff • If supplied, the arguments representing the number of times
to apply diff and the dimension along which to calculate the
difference must be constants.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
dot —

4-249
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


eig • For code generation,QZ algorithm is used in all cases. MATLAB can
use different algorithms for different inputs. Consequently, V might
represent a different basis of eigenvectors. The eigenvalues in D
might not be in the same order as in MATLAB.
• With one input, [V,D] = eig(A), the results are similar to
those obtained using [V,D] = eig(A,eye(size(A)),'qz') in
MATLAB, except that the columns of V are normalized.
• Options 'balance', and 'nobalance' are not supported for the
standard eigenvalue problem. 'chol' is not supported for the
symmetric generalized eigenvalue problem.
• Outputs are of complex type.
• Does not support the option to calculate left eigenvectors.
eye • classname must be a built-in MATLAB numeric type. Does not
invoke the static eye method for other classes. For example, eye(m,
n, 'myclass’) does not invoke myclass.eye(m,n).
• Size arguments must have a fixed size.
false • Dimensions must be real, nonnegative, integers.
find • Issues an error if a variable-size input becomes a row vector at run
time.

Note: This limitation does not apply when the input is scalar or a
variable-length row vector.
• For variable-size inputs, the shape of empty outputs, 0-by-0, 0-by-1,
or 1-by-0, depends on the upper bounds of the size of the input. The
output might not match MATLAB when the input array is a scalar
or [] at run time. If the input is a variable-length row vector, the size
of an empty output is 1-by-0, otherwise it is 0-by-1.
• Always returns a variable-length vector. Even when you provide
the output vector k, the output cannot be fixed-size because the
output can contain fewer than k elements. For example, find(x,1)
returns a variable-length vector with 1 or 0 elements.
flip Does not support cell arrays for the first argument.
flipdim Does not support cell arrays for the first argument.

4-250
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


fliplr Does not support cell arrays.
flipud Does not support cell arrays.
full —
hadamard n must be a fixed-size scalar.
hankel —
hilb —
ind2sub • The first argument should be a valid size vector. Size vectors for
arrays with more than intmax elements are not supported.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
inv Singular matrix inputs can produce nonfinite values that differ from
MATLAB results.
invhilb —
ipermute • Does not support cell arrays for the first argument.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
iscolumn —
isempty —
isequal —
isequaln —
isfinite —
isfloat —
isinf —
isinteger —
islogical —
ismatrix —
isnan —
isrow —
issparse —

4-251
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


isvector —
kron —
length —
linspace —
logspace —
lu —
magic “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35.
max • If specified, dim must be a constant.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35.
• “Code Generation for Complex Data with Zero-Valued Imaginary
Parts” on page 6-4.
min • If specified, dim must be a constant.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35.
• “Code Generation for Complex Data with Zero-Valued Imaginary
Parts” on page 6-4.
ndgrid —
ndims —
nnz —
nonzeros —
norm —
normest —
numel —
ones • Dimensions must be real, nonnegative integers.
• The input optimfun must be a function supported for code
generation.
pascal —

4-252
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


permute • Does not support cell arrays for the first argument.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
pinv —
planerot “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35
prod • If supplied, dim must be a constant.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
qr —
rand • The data type (class) must be a built-in MATLAB numeric
type. Does not invoke the static rand method for other
classes. For example, rand(sz,'myclass’) does not invoke
myclass.rand(sz).
• Size arguments must have a fixed size.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
randi • The data type (class) must be a built-in MATLAB numeric type.
Does not invoke the static randi method for other classes.
For example, randi(imax,sz,'myclass’) does not invoke
myclass.randi(imax,sz).
• Size arguments must have a fixed size.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
randn • The data type (class) must be a built-in MATLAB numeric
type. Does not invoke the static randn method for other
classes. For example, randn(sz,'myclass’) does not invoke
myclass.randn(sz).
• Size arguments must have a fixed size.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
randperm —

4-253
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


rank —
rcond —
repmat Size arguments must have a fixed size.
reshape • If the input is a compile-time empty cell array, then the size
arguments must be constants.
• Size arguments must have a fixed size.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
rng • Supports only the 'twister', 'v5normal', and 'v4' generators.
• Does not support the 'shuffle' input.
• For a MEX target:

• If extrinsic calls are disabled or rng is called inside a parfor


loop, the output of rng in the MEX function is not compatible
with the rng function in MATLAB. You cannot pass the output of
s = rng from the MEX function to rng in MATLAB.
• If extrinsic calls are enabled and rng is not called from inside a
parfor loop, only rng can access the data in the structure that
rng returns.
rosser —
rot90 Does not support cell arrays for the first argument.
shiftdim • Does not support cell arrays for the first argument.
• Second argument must be a constant.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
sign —
size —

4-254
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


sort • Does not support cell arrays for the first argument.
• If the input is a complex type, sort orders the output according
to absolute value. When x is a complex type that has all zero
imaginary parts, use sort(real(x)) to compute the sort order
for real types. See “Code Generation for Complex Data with Zero-
Valued Imaginary Parts” on page 6-4.
sortrows • Does not support cell arrays for the first argument.
• If the input is a complex type, sortrows orders the output
according to absolute value. When x is a complex type that has all
zero imaginary parts, use sortrows(real(x)) to compute the sort
order for real types. See “Code Generation for Complex Data with
Zero-Valued Imaginary Parts” on page 6-4.
squeeze Does not support cell arrays.
sub2ind • The first argument must be a valid size vector. Size vectors for
arrays with more than intmax elements are not supported.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
subspace —
sum • If specified, dim must be a constant.
• The outtype and nanflag options must be constant strings.
• “Variable-Sizing Restrictions for Code Generation of Toolbox
Functions” on page 7-35
toeplitz —
trace —
tril • If supplied, the argument representing the order of the diagonal
matrix must be a real and scalar integer value.
triu • If supplied, the argument representing the order of the diagonal
matrix must be a real and scalar integer value.
true • Dimensions must be real, nonnegative, integers.
vander —
wilkinson n must be a fixed-size scalar.

4-255
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


zeros • Dimensions must be real, nonnegative, integers.

Neural Network Toolbox


You can use genFunction in the Neural Network Toolbox™ to generate a standalone
MATLAB function for a trained neural network. You can generate C/C++ code from this
standalone MATLAB function. To generate Simulink blocks, use thegenSim function. See
“Deploy Neural Network Functions”.

Numerical Integration and Differentiation in MATLAB

Function Remarks and Limitations


cumtrapz —
del2 —
diff • If supplied, the arguments representing the number of times to apply
diff and the dimension along which to calculate the difference must be
constants.
gradient —
ode23 • All odeset option arguments must be constant.
• Does not support a constant mass matrix in the options structure.
Provide a mass matrix as a function .
• You must provide at least the two output arguments T and Y.
• Input types must be homogeneous—all double or all single.
• Variable-sizing support must be enabled. Requires dynamic memory
allocation when tspan has two elements or you use event functions.
ode45 • All odeset option arguments must be constant.
• Does not support a constant mass matrix in the options structure.
Provide a mass matrix as a function .
• You must provide at least the two output arguments T and Y.
• Input types must be homogeneous—all double or all single.
• Variable-sizing support must be enabled. Requires dynamic memory
allocation when tspan has two elements or you use event functions.

4-256
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


odeget The name argument must be constant.
odeset All inputs must be constant.
quad2d • Generates a warning if the size of the internal storage arrays is not
large enough. If a warning occurs, a possible workaround is to divide the
region of integration into pieces and sum the integrals over each piece.
quadgk —
trapz • If supplied, dim must be a constant.
• “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35

Optimization Functions in MATLAB

Function Remarks and Limitations


fminsearch • Ignores the Display option. Does not print status information during
execution. Test the exitflag output for the exit condition.
• The output structure does not include the algorithm or message
fields.
• Ignores the OutputFcn and PlotFcns options.
fzero • The first argument must be a function handle. Does not support
structure, inline function, or string inputs for the first argument.
• Supports up to three output arguments. Does not support the fourth
output argument (the output structure).
optimget Input parameter names must be constant.
optimset • Does not support the syntax that has no input or output arguments:
optimset
• Functions specified in the options must be supported for code
generation.
• The fields of the options structure oldopts must be fixed-size fields.
• For code generation, optimization functions ignore the Display option.
• Does not support the additional options in an options structure created
by the Optimization Toolbox optimset function. If an input options

4-257
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


structure includes the additional Optimization Toolbox options, the
output structure does not include them.

Phased Array System Toolbox


C and C++ code generation for the following functions and System objects requires the
Phased Array System Toolbox software.

Name Remarks and Limitations


Antenna and Microphone Elements
aperture2gain Does not support variable-size inputs.
azel2phithetapat Does not support variable-size inputs.
azel2uvpat Does not support variable-size inputs.
circpol2pol Does not support variable-size inputs.
gain2aperture Does not support variable-size inputs.
phased.CosineAntennaElement • pattern, patternAzimuth,
patternElevation, and plotResponse
methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.CrossedDipoleAntennaElement • pattern, patternAzimuth,
patternElevation, and plotResponse
methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.CustomAntennaElement • pattern, patternAzimuth,
patternElevation, and plotResponse
methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.CustomMicrophoneElement • pattern, patternAzimuth,
patternElevation, and plotResponse
methods are not supported.

4-258
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


• See “System Objects in MATLAB Code
Generation”.
phased.IsotropicAntennaElement • pattern, patternAzimuth,
patternElevation, and plotResponse
methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.OmnidirectionalMicrophoneElement • pattern, patternAzimuth,
patternElevation, and plotResponse
methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.ShortDipoleAntennaElement • pattern, patternAzimuth,
patternElevation, and plotResponse
methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phitheta2azelpat Does not support variable-size inputs.
phitheta2uvpat Does not support variable-size inputs.
pol2circpol Does not support variable-size inputs.
polellip Does not support variable-size inputs.
polloss Does not support variable-size inputs.
polratio Does not support variable-size inputs.
polsignature • Does not support variable-size inputs.
• Supported only when output arguments are
specified.
stokes • Does not support variable-size inputs.
• Supported only when output arguments are
specified.
uv2azelpat Does not support variable-size inputs.
uv2phithetapat Does not support variable-size inputs.

4-259
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


Array Geometries and Analysis
az2broadside Does not support variable-size inputs.
broadside2az Does not support variable-size inputs.
pilotcalib Does not support variable-size inputs.
phased.ArrayGain • Does not support arrays containing
polarized antenna elements, that is, the
phased.ShortDipoleAntennaElement or
phased.CrossedDipoleAntennaElement
antennas.
• See “System Objects in MATLAB Code
Generation”.
phased.ArrayResponse See “System Objects in MATLAB Code
Generation”.
phased.ConformalArray • pattern, patternAzimuth,
patternElevation, plotResponse, and
viewArray methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.ElementDelay See “System Objects in MATLAB Code
Generation”.
phased.PartitionedArray • pattern, patternAzimuth,
patternElevation, plotResponse, and
viewArray methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.ReplicatedSubarray • pattern, patternAzimuth,
patternElevation, plotResponse, and
viewArray methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.SteeringVector See “System Objects in MATLAB Code
Generation”.

4-260
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


phased.UCA • pattern, patternAzimuth,
patternElevation, plotResponse, and
viewArray methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.ULA • pattern, patternAzimuth,
patternElevation, plotResponse, and
viewArray methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.URA • pattern, patternAzimuth,
patternElevation, plotResponse, and
viewArray methods are not supported.
• See “System Objects in MATLAB Code
Generation”.
Signal Radiation and Collection
phased.Collector See “System Objects in MATLAB Code
Generation”.
phased.Radiator See “System Objects in MATLAB Code
Generation”.
phased.WidebandCollector • Requires dynamic memory allocation. See
“Limitations for System Objects that Require
Dynamic Memory Allocation”.
• See “System Objects in MATLAB Code
Generation”.
phased.WidebandRadiator See “System Objects in MATLAB Code
Generation”.
sensorsig Does not support variable-size inputs.
Transmitters and Receivers
delayseq Does not support variable-size inputs.
noisepow Does not support variable-size inputs.

4-261
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


phased.ReceiverPreamp See “System Objects in MATLAB Code
Generation”.
phased.Transmitter See “System Objects in MATLAB Code
Generation”.
systemp Does not support variable-size inputs.
Waveform Design and Analysis
ambgfun Does not support variable-size inputs.
phased.FMCWWaveform • plot method is not supported.
• See “System Objects in MATLAB Code
Generation”.

.
phased.LinearFMWaveform • plot method is not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.MFSKWaveform • plot method is not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.PhaseCodedWaveform • plot method is not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.RectangularWaveform • plot method is not supported.
• See “System Objects in MATLAB Code
Generation”.
phased.SteppedFMWaveform • plot method is not supported.
• See “System Objects in MATLAB Code
Generation”.
range2bw Does not support variable-size inputs.
range2time Does not support variable-size inputs.
time2range Does not support variable-size inputs.
unigrid Does not support variable-size inputs.

4-262
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


Beamforming
cbfweights Does not support variable-size inputs.
lcmvweights Does not support variable-size inputs.
mvdrweights Does not support variable-size inputs.
phased.FrostBeamformer • Requires dynamic memory allocation. See
“Limitations for System Objects that Require
Dynamic Memory Allocation”.
• See “System Objects in MATLAB Code
Generation”.
phased.LCMVBeamformer See “System Objects in MATLAB Code
Generation”.
phased.MVDRBeamformer See “System Objects in MATLAB Code
Generation”.
phased.PhaseShiftBeamformer See “System Objects in MATLAB Code
Generation”.
phased.SteeringVector See “System Objects in MATLAB Code
Generation”.
phased.SubbandMVDRBeamformer See “System Objects in MATLAB Code
Generation”.
phased.SubbandPhaseShiftBeamformer See “System Objects in MATLAB Code
Generation”.
phased.TimeDelayBeamformer • Requires dynamic memory allocation. See
“Limitations for System Objects that Require
Dynamic Memory Allocation”.
• See “System Objects in MATLAB Code
Generation”.
phased.TimeDelayLCMVBeamformer • Requires dynamic memory allocation. See
“Limitations for System Objects that Require
Dynamic Memory Allocation”.
• See “System Objects in MATLAB Code
Generation”.
sensorcov Does not support variable-size inputs.

4-263
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


steervec Does not support variable-size inputs.
Direction of Arrival (DOA) Estimation
aictest Does not support variable-size inputs.
espritdoa Does not support variable-size inputs.
gccphat Does not support variable-size inputs.
mdltest Does not support variable-size inputs.
phased.BeamscanEstimator See “System Objects in MATLAB Code
Generation”.
phased.BeamscanEstimator2D See “System Objects in MATLAB Code
Generation”.
phased.BeamspaceESPRITEstimator See “System Objects in MATLAB Code
Generation”.
phased.ESPRITEstimator See “System Objects in MATLAB Code
Generation”.
phased.GCCEstimator See “System Objects in MATLAB Code
Generation”.
phased.MVDREstimator See “System Objects in MATLAB Code
Generation”.
phased.MVDREstimator2D See “System Objects in MATLAB Code
Generation”.
phased.RootMUSICEstimator See “System Objects in MATLAB Code
Generation”.
phased.RootWSFEstimator See “System Objects in MATLAB Code
Generation”.
phased.SumDifferenceMonopulseTracker See “System Objects in MATLAB Code
Generation”.
phased.SumDifferenceMonopulseTracker2D See “System Objects in MATLAB Code
Generation”.
rootmusicdoa Does not support variable-size inputs.
spsmooth Does not support variable-size inputs.
Space-Time Adaptive Processing (STAP)

4-264
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


dopsteeringvec Does not support variable-size inputs.
phased.ADPCACanceller See “System Objects in MATLAB Code
Generation”.
phased.AngleDopplerResponse See “System Objects in MATLAB Code
Generation”.
phased.DPCACanceller See “System Objects in MATLAB Code
Generation”.
phased.STAPSMIBeamformer See “System Objects in MATLAB Code
Generation”.
val2ind Does not support variable-size inputs.
Targets, Interference, and Signal Propagation
billingsleyicm Does not support variable-size inputs.
depressionang Does not support variable-size inputs.
effearthradius Does not support variable-size inputs.
fspl Does not support variable-size inputs.
fogpl Does not support variable-size inputs.
gaspl Does not support variable-size inputs.
grazingang Does not support variable-size inputs.
horizonrange Does not support variable-size inputs.
phased.BackscatterRadarTarget See “System Objects in MATLAB Code
Generation”
phased.BarrageJammer See “System Objects in MATLAB Code
Generation”.
phased.ConstantGammaClutter See “System Objects in MATLAB Code
Generation”.
phased.FreeSpace • Requires dynamic memory allocation. See
“Limitations for System Objects that Require
Dynamic Memory Allocation”.
• See “System Objects in MATLAB Code
Generation”.

4-265
4 Functions, Classes, and System Objects Supported for Code Generation

Name Remarks and Limitations


phased.LOSChannel See “System Objects in MATLAB Code
Generation”
phased.RadarTarget See “System Objects in MATLAB Code
Generation”.
phased.TwoRayChannel See “System Objects in MATLAB Code
Generation”.
phased.WidebandFreeSpace See “System Objects in MATLAB Code
Generation”.
phased.WidebandLOSChannel See “System Objects in MATLAB Code
Generation”
physconst Does not support variable-size inputs.
surfacegamma Does not support variable-size inputs.
surfclutterrcs Does not support variable-size inputs.
rainpl Does not support variable-size inputs.
Motion Modeling and Coordinate Systems
azel2phitheta Does not support variable-size inputs.
azel2uv Does not support variable-size inputs.
azelaxes Does not support variable-size inputs.
cart2sphvec Does not support variable-size inputs.
dop2speed Does not support variable-size inputs.
global2localcoord Does not support variable-size inputs.
local2globalcoord Does not support variable-size inputs.
phased.Platform See “System Objects in MATLAB Code
Generation”.
phitheta2azel Does not support variable-size inputs.
phitheta2uv Does not support variable-size inputs.
radialspeed Does not support variable-size inputs.
rangeangle Does not support variable-size inputs.
rotx Does not support variable-size inputs.

4-266
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


roty Does not support variable-size inputs
rotz Does not support variable-size inputs.
speed2dop Does not support variable-size inputs.
sph2cartvec Does not support variable-size inputs.
uv2azel Does not support variable-size inputs.

Polynomials in MATLAB

Function Remarks and Limitations


poly • Does not discard nonfinite input values
• Complex input produces complex output
• “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35
polyder The output can contain fewer NaNs than the MATLAB output. However, if
the input contains a NaN, the output contains at least one NaN.
polyfit “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” on
page 7-35
polyint —
polyval —
polyvalm —
roots • Output is variable size.
• Output is complex.
• Roots are not always in the same order as MATLAB.
• Roots of poorly conditioned polynomials do not always match MATLAB.

Programming Utilities in MATLAB

Function Remarks and Limitations


mfilename —

4-267
4 Functions, Classes, and System Objects Supported for Code Generation

Relational Operators in MATLAB


Function Remarks and Limitations
eq —
ge —
gt —
le —
lt —
ne —

Robotics System Toolbox


C/C++ code generation for the following functions requires the Robotics System Toolbox
software.

Name Remarks and Limitations


Algorithm Design
robotics.PurePursuit Supports MATLAB Function block: No
robotics.VectorFieldHistogram Supports MATLAB Function block: No
robotics.ParticleFilter Supports MATLAB Function block: No
Coordinate System Transformations
angdiff Supports MATLAB Function block: Yes
axang2quat Supports MATLAB Function block: Yes
axang2rotm Supports MATLAB Function block: Yes
axang2tform Supports MATLAB Function block: Yes
cart2hom Supports MATLAB Function block: Yes
eul2quat Supports MATLAB Function block: Yes
eul2rotm Supports MATLAB Function block: Yes
eul2tform Supports MATLAB Function block: Yes
hom2cart Supports MATLAB Function block: Yes
quat2axang Supports MATLAB Function block: Yes

4-268
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


quat2eul Supports MATLAB Function block: Yes
quat2rotm Supports MATLAB Function block: Yes
quat2tform Supports MATLAB Function block: Yes
rotm2axang Supports MATLAB Function block: Yes
rotm2eul Supports MATLAB Function block: Yes
rotm2quat Supports MATLAB Function block: Yes
rotm2tform Supports MATLAB Function block: Yes
tform2axang Supports MATLAB Function block: Yes
tform2eul Supports MATLAB Function block: Yes
tform2quat Supports MATLAB Function block: Yes
tform2rotm Supports MATLAB Function block: Yes
tform2trvec Supports MATLAB Function block: Yes
trvec2tform Supports MATLAB Function block: Yes

Rounding and Remainder Functions in MATLAB

Function Remarks and Limitations


ceil —
fix —
floor —
mod • Performs the arithmetic using the output class. Results might not match
MATLAB due to differences in rounding errors.

If one of the inputs has type int64 or uint64, then both inputs must
have the same type.
rem • Performs the arithmetic using the output class. Results might not match
MATLAB due to differences in rounding errors.
• If one of the inputs has type int64 or uint64, then both inputs must
have the same type.
round Supports only the syntax Y = round(X).

4-269
4 Functions, Classes, and System Objects Supported for Code Generation

Set Operations in MATLAB

Function Remarks and Limitations


intersect • Does not support cell arrays for the first or second arguments.
• When you do not specify the 'rows' option:

• Inputs A and B must be vectors. If you specify the 'legacy' option,


inputs A and B must be row vectors.
• The first dimension of a variable-size row vector must have fixed
length 1. The second dimension of a variable-size column vector must
have fixed length 1.
• The input [] is not supported. Use a 1-by-0 or 0-by-1 input, for
example, zeros(1,0), to represent the empty set.
• If you specify the 'legacy' option, empty outputs are row vectors,
1-by-0, never 0-by-0.
• When you specify both the 'legacy' option and the 'rows' option, the
outputs ia and ib are column vectors. If these outputs are empty, they
are 0-by-1, never 0-by-0, even if the output C is 0-by-0.
• When the setOrder is 'sorted' or when you specify the 'legacy'
option, the inputs must already be sorted in ascending order. The first
output, C, is sorted in ascending order.
• Complex inputs must be single or double.
• When one input is complex and the other input is real, do one of the
following:

• Set setOrder to 'stable'.


• Sort the real input in complex ascending order (by absolute
value). Suppose the real input is x. Use sort(complex(x))or
sortrows(complex(x)).
• “Code Generation for Complex Data with Zero-Valued Imaginary Parts”
on page 6-4.
ismember • Does not support cell arrays for the first or second arguments.
• Complex inputs must be single or double.
• “Code Generation for Complex Data with Zero-Valued Imaginary Parts”
on page 6-4.

4-270
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


issorted • Does not support cell arrays for the first argument.
• “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35.
• “Code Generation for Complex Data with Zero-Valued Imaginary Parts”
on page 6-4.
setdiff • Does not support cell arrays for the first or second arguments.
• When you do not specify the 'rows' option:

• Inputs A and B must be vectors. If you specify the 'legacy' option,


inputs A and B must be row vectors.
• The first dimension of a variable-size row vector must have fixed
length 1. The second dimension of a variable-size column vector must
have fixed length 1.
• Do not use [] to represent the empty set. Use a 1-by-0 or 0-by-1
input, for example, zeros(1,0), to represent the empty set.
• If you specify the 'legacy' option, empty outputs are row vectors,
1-by-0, never 0-by-0.
• When you specify both the 'legacy' and 'rows' options, the output
ia is a column vector. If ia is empty, it is 0-by-1, never 0-by-0, even if
the output C is 0-by-0.
• When the setOrder is not 'stable' or when you specify the
'legacy' option, the inputs must already be sorted in ascending order.
The first output, C, is sorted in ascending order.
• Complex inputs must be single or double.
• When one input is complex and the other input is real, do one of the
following:

• Set setOrder to 'stable'.


• Sort the real input in complex ascending order (by absolute
value). Suppose the real input is x. Use sort(complex(x))or
sortrows(complex(x)).
• “Code Generation for Complex Data with Zero-Valued Imaginary Parts”
on page 6-4.

4-271
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


setxor • Does not support cell arrays for the first or second arguments.
• When you do not specify the 'rows' option:

• Inputs A and B must be vectors with the same orientation. If you


specify the 'legacy' option, inputs A and B must be row vectors.
• The first dimension of a variable-size row vector must have fixed
length 1. The second dimension of a variable-size column vector must
have fixed length 1.
• The input [] is not supported. Use a 1-by-0 or 0-by-1 input, for
example , zeros(1,0), to represent the empty set.
• If you specify the 'legacy' option, empty outputs are row vectors,
1-by-0, never 0-by-0.
• When you specify both the 'legacy' option and the 'rows' option, the
outputs ia and ib are column vectors. If these outputs are empty, they
are 0-by-1, never 0-by-0, even if the output C is 0-by-0.
• When the setOrder is not 'stable' or when you specify the
'legacy' flag, the inputs must already be sorted in ascending order.
The first output, C, is sorted in ascending order.
• Complex inputs must be single or double.
• When one input is complex and the other input is real, do one of the
following:

• Set setOrder to 'stable'.


• Sort the real input in complex ascending order (by absolute
value). Suppose the real input is x. Use sort(complex(x))or
sortrows(complex(x)).
• “Code Generation for Complex Data with Zero-Valued Imaginary Parts”
on page 6-4.

4-272
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


union • Does not support cell arrays for the first or second arguments.
• When you do not specify the 'rows' option:

• Inputs A and B must be vectors with the same orientation. If you


specify the 'legacy' option, inputs A and B must be row vectors.
• The first dimension of a variable-size row vector must have fixed
length 1. The second dimension of a variable-size column vector must
have fixed length 1.
• The input [] is not supported. Use a 1-by-0 or 0-by-1 input, for
example , zeros(1,0), to represent the empty set.
• If you specify the 'legacy' option, empty outputs are row vectors,
1-by-0, never 0-by-0.
• When you specify both the 'legacy' option and the 'rows' option, the
outputs ia and ib are column vectors. If these outputs are empty, they
are 0-by-1, never 0-by-0, even if the output C is 0-by-0.
• When the setOrder is not 'stable' or when you specify the
'legacy' option, the inputs must already be sorted in ascending order.
The first output, C, is sorted in ascending order.
• Complex inputs must be single or double.
• When one input is complex and the other input is real, do one of the
following:

• Set setOrder to 'stable'.


• Sort the real input in complex ascending order (by absolute
value). Suppose the real input is x. Use sort(complex(x))or
sortrows(complex(x)).
• “Code Generation for Complex Data with Zero-Valued Imaginary Parts”
on page 6-4.

4-273
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


unique • Does not support cell arrays for the first argument.
• When you do not specify the'rows' option:

• The input A must be a vector. If you specify the 'legacy' option, the
input A must be a row vector.
• The first dimension of a variable-size row vector must have fixed
length 1. The second dimension of a variable-size column vector must
have fixed length 1.
• The input [] is not supported. Use a 1-by-0 or 0-by-1 input, for
example, zeros(1,0), to represent the empty set.
• If you specify the 'legacy' option, empty outputs are row vectors,
1-by-0, never 0-by-0.
• When you specify both the 'rows' option and the 'legacy'option,
outputs ia and ic are column vectors. If these outputs are empty, they
are 0-by-1, even if the output C is 0-by-0.
• When the setOrder is not 'stable' or when you specify the
'legacy' option, the input A must already be sorted in ascending
order. The first output, C, is sorted in ascending order.
• Complex inputs must be single or double.

Signal Processing in MATLAB

Function Remarks and Limitations


chol —
conv —
fft • “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35
fft2 —
fftn The siz argument must have a fixed size.
fftshift —
filter • If supplied, dim must be a constant.
• v

4-274
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


freqspace —
ifft • Output is complex.
• Does not support the 'symmetric' option.
• “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35
ifft2 Does not support the 'symmetric' option.
ifftn • Does not support the 'symmetric' option.
• The siz argument must have a fixed size.
ifftshift —
svd Uses a different SVD implementation than MATLAB. Because the singular
value decomposition is not unique, left and right singular vectors might
differ from those computed by MATLAB.
zp2tf —

Signal Processing Toolbox


C and C++ code generation for the following functions requires the Signal Processing
Toolbox software. These functions do not support variable-size inputs, you must define
the size and type of the function inputs. For more information, see “Specifying Inputs in
Code Generation from MATLAB ”.

Note: Many Signal Processing Toolbox functions require constant inputs in generated
code. To specify a constant input for codegen, use coder.Constant.

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.

4-275
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
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.
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.
db2pow —

4-276
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks/Limitations
dct C and C++ code generation for dct requires DSP System Toolbox
software.

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.
findpeaks —
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.
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.

4-277
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
flattopwin All inputs must be constants. Expressions or variables are allowed if their
values do not change.
freqz • Does not support variable-size inputs.
• When called with no output arguments, and without a semicolon at
the end, freqz returns the complex frequency response of the input
filter, evaluated at 512 points.

If the semicolon is added, the function produces a plot of the


magnitude and phase response of the filter.

See “freqz With No Output Arguments”.


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 C and C++ code generation for idct requires DSP System Toolbox
software.

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 C and C++ code generation for levinson requires DSP System Toolbox
software.

If specified, the order of recursion must be a constant. Expressions or


variables are allowed if their values do not change.

4-278
Functions and Objects Supported for C and C++ Code Generation — Category List

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.
peak2peak —
peak2rms —
pow2db —
rcosdesign 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 C and C++ code generation for resample requires DSP System Toolbox
software.

The upsampling and downsampling factors must be specified as


constants. Expressions or variables are allowed if their values do not
change.
rms —
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.

4-279
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks/Limitations
upfirdn C and C++ code generation for upfirdn requires DSP System Toolbox
software.

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 Leading ones in size(x) must be constant for every input x. If x is
variable-size and is a row vector, it must be 1-by-:. It cannot be :-by-:
with size(x,1) = 1 at run time.
yulewalk If specified, the order of recursion must be a constant. Expressions or
variables are allowed if their values do not change.

Special Values in MATLAB

Function Remarks and Limitations


eps • Supported for scalar fixed-point signals only.
• Supported for scalar, vector, and matrix, fi single and fi double
signals.
inf • Dimensions must be real, nonnegative, integers.
intmax —
intmin —
NaN or nan • Dimensions must be real, nonnegative, integers.
pi —
realmax —
realmin —

4-280
Functions and Objects Supported for C and C++ Code Generation — Category List

Specialized Math in MATLAB


Function Remarks and Limitations
airy Always returns a complex result.
besseli • If the order nu is less than 0, it must be an integer.
• Always returns a complex result.
besselj • If the order nu is less than 0, it must be an integer.
• Always returns a complex result.
beta —
betainc Always returns a complex result.
betaincinv Always returns a complex result.
betaln —
ellipke —
erf —
erfc —
erfcinv —
erfcx —
erfinv —
expint —
gamma —
gammainc Output is always complex.
gammaincinv Output is always complex.
gammaln —
psi —

Statistics in MATLAB
Function Remarks and Limitations
corrcoef • Row-vector input is only supported when the first two inputs are vectors
and nonscalar.
cummin —

4-281
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


cummax —
mean • If specified, dim must be a constant.
• The outtype and nanflag options must be constant strings.
• Does not support the 'native' output data type option for integer
types.
• “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35
median • If specified, dim must be a constant.
• “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35“Variable-Sizing Restrictions for Code Generation of
Toolbox Functions” on page 7-35
• “Code Generation for Complex Data with Zero-Valued Imaginary Parts”
on page 6-4.
mode • Does not support third output argument C (cell array).
• If specified, dim must be a constant.
• “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35
std • If specified, dim must be a constant.
• “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35
var • If specified, dim must be a constant.
• “Variable-Sizing Restrictions for Code Generation of Toolbox Functions”
on page 7-35

Statistics and Machine Learning Toolbox


C and C++ code generation for the following functions requires the Statistics and
Machine Learning Toolbox software.

Function Remarks and Limitations


betacdf —
betafit —

4-282
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


betainv —
betalike —
betapdf —
betarnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
betastat —
binocdf —
binoinv —
binopdf —
binornd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
binostat —
cdf —
chi2cdf —
chi2inv —
chi2pdf —
chi2rnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
chi2stat —
evcdf —
evinv —
evpdf —

4-283
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


evrnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
evstat —
expcdf —
expinv —
exppdf —
exprnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
expstat —
fcdf —
finv —
fpdf —
frnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
fstat —
gamcdf —
gaminv —
gampdf —
gamrnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.

4-284
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


gamstat —
geocdf —
geoinv —
geomean —
geopdf —
geornd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
geostat —
gevcdf —
gevinv —
gevpdf —
gevrnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
gevstat —
gpcdf —
gpinv —
gppdf —
gprnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
gpstat —
harmmean —
hygecdf —

4-285
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


hygeinv —
hygepdf —
hygernd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
hygestat —
icdf —
iqr —
kmeans • If the Start method uses random selections, the initial centroid
cluster positions might not match MATLAB.
• If the number of rows in X is fixed, does not remove rows of X that
contain a NaN.
• The cluster centroid locations in C can have a different order than in
MATLAB. In this case, the cluster indices in idx have corresponding
differences.
• If you provide Display, its value must be 'off'.
• If you provide Streams, it must be empty and UseSubstreams must
be false.
• When you set the UseParallel option to true, some computations
can execute in parallel even when Replicates is 1. For large data
sets, when Replicates is 1, consider setting the UseParallel
option to true.
kurtosis —
logncdf —
logninv —
lognpdf —

4-286
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


lognrnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
lognstat —
mad Input dim cannot be empty.
mnpdf Input dim cannot be empty.
moment If order is nonintegral and X is real, use moment(complex(X),
order).
nancov If the input is variable-size and is [] at run time, returns [] not NaN.
nanmax —
nanmean —
nanmedian —
nanmin —
nanstd —
nansum —
nanvar —
nbincdf —
nbininv —
nbinpdf —
nbinrnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
nbinstat —
ncfcdf —
ncfinv —
ncfpdf —

4-287
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


ncfrnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
ncfstat —
nctcdf —
nctinv —
nctpdf —
nctrnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
nctstat —
ncx2cdf —
ncx2rnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
ncx2stat —
normcdf —
norminv —
normpdf —
normrnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
normstat —

4-288
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


pca • Ignores the 'Display' value for 'Options' when 'Algorithm' is
'als'.
• If supplied, 'Weights' and 'VariableWeights' must be real.
• Always returns the fifth output explained as a column vector.
• Always returns the sixth output mu as a row vector.
• If mu is empty, pca returns mu as a 1-by-0 array. pca does not
convert mu to a 0-by-0 empty array.
• Does not treat an input matrix X that has all NaN values as a special
case. The outputs have the sizes that they have when some of the
inputs are finite.
pdf —
pearsrnd Matches MATLAB only when generated output r is scalar.
poisscdf —
poissinv —
poisspdf —
poissrnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
poisstat —

4-289
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


prctile • “Automatic dimension restriction” on page 7-35
• If the output Y is a vector, the orientation of Y differs from MATLAB
when all of the following are true:

• You do not supply the dim input.


• X is a variable-size array.
• X is not a variable-length vector.
• X is a vector at run time.
• The orientation of the vector X does not match the orientation of
the vector p.

In this case, the output Y matches the orientation of X not the


orientation of p.
quantile —
randg —
random —
randsample When sampling without replacement, the order of the output values
might not match MATLAB.
raylcdf —
raylinv —
raylpdf —
raylrnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
raylstat —
skewness —
tcdf —
tinv —
tpdf —

4-290
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


trnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
tstat —
unidcdf —
unidinv —
unidpdf —
unidrnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
unidstat —
unifcdf —
unifinv —
unifpdf —
unifrnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.
unifstat —
wblcdf —
wblinv —
wblpdf —
wblrnd Can return a different sequence of numbers than MATLAB if either of
the following is true:

• The output is nonscalar.


• An input parameter is invalid for the distribution.

4-291
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


wblstat —
zscore —

String Functions in MATLAB


Function Remarks and Limitations
bin2dec • Does not support cell arrays.
• Does not match MATLAB when the input is empty.
blanks —
char Does not support cell arrays.
deblank • Supports only inputs from the char class. Does not support cell arrays.
• Input values must be in the range 0-127.
dec2bin • If input d is double, d must be less than 2^52.
• If input d is single, d must be less than 2^23.
• Unless you specify input n to be constant and n is large enough that the
output has a fixed number of columns regardless of the input values,
this function requires variable-sizing support. Without variable-sizing
support, n must be at least 52 for double, 23 for single, 16 for char,
32 for int32, 16 for int16, and so on.
dec2hex • If input d is double, d must be less than 2^52.
• If input d is single, d must be less than 2^23.
• Unless you specify input n to be constant, and n is large enough that the
output has a fixed number of columns regardless of the input values,
this function requires variable-sizing support. Without variable-sizing
support, n must be at least 13 for double, 6 for single, 4 for char, 8
for int32, 4 for int16, and so on.
hex2dec Does not support cell arrays.
hex2num • Does not support cell arrays.
• For n = hex2num(S), size(S,2) <= length(num2hex(0))
iscellstr —
ischar —

4-292
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


isletter • Input values from the char class must be in the range 0-127.
isspace • Input values from the char class must be in the range 0–127.
isstrprop • Supports only inputs from char and integer classes.
• Input values must be in the range 0-127.
lower • Supports only char inputs. Does not support cell arrays.
• Input values must be in the range 0-127.
num2hex —
str2double • Does not support cell arrays.
• Always returns a complex result.
strcmp • Does not support enumeration inputs.
• When one input is a cell array and the other input is a character array,
the character array must be a compile-time row vector.
• When both inputs are empty character arrays that have different sizes,
returns true.
strcmpi • Does not support enumeration inputs.
• Input values from the char class must be in the range 0-127.
• When one input is a cell array and the other input is a character array,
the character array must be a compile-time row vector.
• When both inputs are empty character arrays that have different sizes,
returns true.
strfind • Does not support cell arrays.
• If pattern does not exist in str, returns zeros(1,0) not []. To check
for an empty return, use isempty.
• Inputs must be character row vectors.
strjoin Always returns a string that has size 1-by-n. For empty inputs, returns a 1-
by-0 string not [].
strjust Does not support a cell array of strings for the first argument.
strncmp • Does not support enumeration inputs.
• When one input is a cell array and the other input is a character array,
the character array must be a compile-time row vector.

4-293
4 Functions, Classes, and System Objects Supported for Code Generation

Function Remarks and Limitations


strncmpi • Does not support enumeration inputs.
• Input values from the char class must be in the range 0-127.
• When one input is a cell array and the other input is a character array,
the character array must be a compile-time row vector.
strrep • Does not support cell arrays.
• If oldSubstr does not exist in origStr, returns blanks(0). To check
for an empty return, use isempty.
• Inputs must be character row vectors.
strtok Does not support a cell arrays for the first argument.
strtrim • Supports only inputs from the char class. Does not support cell arrays.
• Input values must be in the range 0-127.
upper • Supports only inputs from the char class. Does not support cell arrays.
• Input values must be in the range 0-127.

System Identification Toolbox


C and C++ code generation for the following functions and System objects requires the
System Identification Toolbox software.

Name Remarks and Limitations


recursiveAR • For Simulink-based workflows, use
Recursive Polynomial Model
Estimator.
• For limitations, see “Generate Code
for Online Parameter Estimation in
MATLAB”.
recursiveARMA • For Simulink-based workflows, use
Recursive Polynomial Model
Estimator.
• For limitations, see “Generate Code
for Online Parameter Estimation in
MATLAB”.

4-294
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


recursiveARMAX • For Simulink-based workflows, use
Recursive Polynomial Model
Estimator.
• For limitations, see “Generate Code
for Online Parameter Estimation in
MATLAB”.
recursiveARX • For Simulink-based workflows, use
Recursive Polynomial Model
Estimator.
• For limitations, see “Generate Code
for Online Parameter Estimation in
MATLAB”.
recursiveBJ • For Simulink-based workflows, use
Recursive Polynomial Model
Estimator.
• For limitations, see “Generate Code
for Online Parameter Estimation in
MATLAB”.
recursiveLS • For Simulink-based workflows,
use Recursive Least Squares
Estimator.
• For limitations, see “Generate Code
for Online Parameter Estimation in
MATLAB”.
recursiveOE • For Simulink-based workflows, use
Recursive Polynomial Model
Estimator.
• For limitations, see “Generate Code
for Online Parameter Estimation in
MATLAB”.

4-295
4 Functions, Classes, and System Objects Supported for Code Generation

Trigonometry in MATLAB

Function Remarks and Limitations


acos When the input value x is real, but the output should be complex, generates
an error during simulation and returns NaN in generated code. To get the
complex result, make the input value complex by passing in complex(x).
acosd —
acosh • Generates an error during simulation and returns NaN in generated
code when the input value x is real, but the output should be complex.
To get the complex result, make the input value complex by passing in
complex(x).
acot —
acotd —
acoth —
acsc —
acscd —
acsch —
asec —
asecd —
asech —
asin • Generates an error during simulation and returns NaN in generated
code when the input value x is real, but the output should be complex.
To get the complex result, make the input value complex by passing in
complex(x).
asind —
asinh —
atan —
atan2 —
atan2d —
atand —

4-296
Functions and Objects Supported for C and C++ Code Generation — Category List

Function Remarks and Limitations


atanh Generates an error during simulation and returns NaN in generated code
when the input value x is real, but the output should be complex. To get the
complex result, make the input value complex by passing in complex(x).
cos —
cosd —
cosh —
cot —
cotd • In some cases, returns -Inf when MATLAB returns Inf.
• In some cases, returns Inf when MATLAB returns -Inf.
coth —
csc —
cscd • In some cases, returns -Inf when MATLAB returns Inf.
• In some cases, returns Inf when MATLAB returns -Inf.
csch —
deg2rad —
hypot —
rad2deg —
sec —
secd • In some cases, returns -Inf when MATLAB returns Inf.
• In some cases, returns Inf when MATLAB returns -Inf.
sech —
sin —
sind —
sinh —
tan —
tand • In some cases, returns -Inf when MATLAB returns Inf.
• In some cases, returns Inf when MATLAB returns -Inf.
tanh —

4-297
4 Functions, Classes, and System Objects Supported for Code Generation

WLAN System Toolbox


C and C++ code generation for the following functions and System objects requires the
WLAN System Toolbox software.

Name Remarks and Limitations


WLAN Modeling
wlanHTConfig —
wlanNonHTConfig —
wlanRecoveryConfig —
wlanVHTConfig —
Signal Transmission
wlanHTData Cannot be used in MATLAB Function block
wlanHTLTF —
wlanHTSIG —
wlanHTSTF —
wlanLLTF —
wlanLSIG —
wlanLSTF —
wlanNonHTData Cannot be used in MATLAB Function block
wlanVHTData Cannot be used in MATLAB Function block
wlanVHTLTF —
wlanVHTSIGA —
wlanVHTSIGB —
wlanVHTSTF —
wlanWaveformGenerator Cannot be used in MATLAB Function block
Signal Reception
wlanCoarseCFOEstimate —
wlanFieldIndices —
wlanFineCFOEstimate —

4-298
Functions and Objects Supported for C and C++ Code Generation — Category List

Name Remarks and Limitations


wlanHTDataRecover Cannot be used in MATLAB Function block
wlanHTLTFChannelEstimate —
wlanHTLTFDemodulate —
wlanHTSIGRecover —
wlanLLTFChannelEstimate —
wlanLLTFDemodulate —
wlanLSIGRecover —
wlanNonHTDataRecover Cannot be used in MATLAB Function block
wlanVHTDataRecover Cannot be used in MATLAB Function block
wlanVHTLTFChannelEstimate —
wlanVHTLTFDemodulate —
wlanVHTSIGARecover —
wlanVHTSIGBRecover —
Propagation Channel
wlanTGacChannel “System Objects in MATLAB Code Generation”
wlanTGnChannel “System Objects in MATLAB Code Generation”

4-299
5

Defining MATLAB Variables for C/C++


Code Generation

• “Variables Definition for Code Generation” on page 5-2


• “Best Practices for Defining Variables for C/C++ Code Generation” on page 5-3
• “Eliminate Redundant Copies of Variables in Generated Code” on page 5-7
• “Reassignment of Variable Properties” on page 5-9
• “Define and Initialize Persistent Variables” on page 5-10
• “Reuse the Same Variable with Different Properties” on page 5-11
• “Avoid Overflows in for-Loops” on page 5-15
• “Supported Variable Types” on page 5-17
5 Defining MATLAB Variables for C/C++ Code Generation

Variables Definition for Code Generation


In the MATLAB language, variables can change their properties dynamically at run time
so you can use the same variable to hold a value of any class, size, or complexity. For
example, the following code works in MATLAB:
function x = foo(c) %#codegen
if(c>0)
x = 0;
else
x = [1 2 3];
end
disp(x);
end

However, statically-typed languages like C must be able to determine variable properties


at compile time. Therefore, for C/C++ code generation, you must explicitly define the
class, size, and complexity of variables in MATLAB source code before using them. For
example, rewrite the above source code with a definition for x:
function x = foo(c) %#codegen
x = zeros(1,3);
if(c>0)
x = 0;
else
x = [1 2 3];
end
disp(x);
end

For more information, see “Best Practices for Defining Variables for C/C++ Code
Generation” on page 5-3.

5-2
Best Practices for Defining Variables for C/C++ Code Generation

Best Practices for Defining Variables for C/C++ Code Generation


In this section...
“Define Variables By Assignment Before Using Them” on page 5-3
“Use Caution When Reassigning Variables” on page 5-5
“Use Type Cast Operators in Variable Definitions” on page 5-5
“Define Matrices Before Assigning Indexed Variables” on page 5-6

Define Variables By Assignment Before Using Them


For C/C++ code generation, you should explicitly and unambiguously define the class,
size, and complexity of variables before using them in operations or returning them as
outputs. Define variables by assignment, but note that the assignment copies not only
the value, but also the size, class, and complexity represented by that value to the new
variable. For example:

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 the required execution paths
during C/C++ code generation (see Defining a Variable for Multiple Execution Paths).

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 Defining Fields in
a Structure).

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 “Eliminate Redundant Copies of Variables in Generated Code” on page
5-7.

5-3
5 Defining MATLAB Variables for C/C++ Code Generation

When you define variables, they are local by default; they do not persist between function
calls. To make variables persistent, see “Define and Initialize Persistent Variables” on
page 5-10.

Defining a Variable for Multiple Execution Paths

Consider the following MATLAB code:

...
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
...

Defining Fields in a Structure

Consider the following MATLAB code:

...
if c > 0
s.a = 11;
disp(s);
else
s.a = 12;

5-4
Best Practices for Defining Variables for C/C++ Code Generation

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 “Structure Definition for Code Generation” on page 8-2.

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);
...

Use Caution When Reassigning Variables


In general, you should adhere to the "one variable/one type" rule for C/C++ code
generation; that is, each variable must have a specific class, size and complexity.
Generally, if you reassign variable properties after the initial assignment, you get a
compilation error during code generation, but there are exceptions, as described in
“Reassignment of Variable Properties” on page 5-9.

Use Type Cast Operators in Variable Definitions


By default, constants are of type double. To define variables of other types, you can
use type cast operators in variable definitions. For example, the following code defines
variable y as an integer:
...

5-5
5 Defining MATLAB Variables for C/C++ Code Generation

x = 15; % x is of type double by default.


y = uint8(x); % y has the value of x, but cast to uint8.
...

Define Matrices Before Assigning Indexed Variables


When generating C/C++ code from MATLAB, you cannot grow a variable by writing into
an element beyond its current size. Such indexing operations produce run-time errors.
You must define the matrix first before assigning values to its elements.

For example, the following initial assignment is not allowed for code generation:
g(3,2) = 14.6; % Not allowed for creating g
% OK for assigning value once created

For more information about indexing matrices, see “Incompatibility with MATLAB in
Matrix Indexing Operations for Code Generation” on page 7-32.

5-6
Eliminate Redundant Copies of Variables in Generated Code

Eliminate Redundant Copies of Variables in Generated Code


In this section...
“When Redundant Copies Occur” on page 5-7
“How to Eliminate Redundant Copies by Defining Uninitialized Variables” on page
5-7
“Defining Uninitialized Variables” on page 5-8

When Redundant Copies Occur


During C/C++ code generation, MATLAB checks for statements that attempt to access
uninitialized memory. If it detects execution paths where a variable is used but is
potentially not defined, it generates a compile-time error. To prevent these errors, define
variables by assignment before using them in operations or returning them as function
outputs.

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 5-7.

How to Eliminate Redundant Copies by Defining Uninitialized Variables


1 Define the variable with coder.nullcopy.
2 Initialize the variable before reading it.

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.

What happens if you access uninitialized data?

Uninitialized memory contains arbitrary values. Therefore, accessing uninitialized


data may lead to segmentation violations or nondeterministic program behavior
(different runs of the same program may yield inconsistent results).

5-7
5 Defining MATLAB Variables for C/C++ Code Generation

Defining Uninitialized Variables


In the following code, the assignment statement X = zeros(1,N) not only defines X to
be a 1-by-5 vector of real doubles, but also initializes each element of X to zero.

function X = fcn %#codegen

N = 5;
X = zeros(1,N);
for i = 1:N
if mod(i,2) == 0
X(i) = i;
else
X(i) = 0;
end
end

This forced initialization creates an extra copy in the generated code. To eliminate this
overhead, use coder.nullcopy in the definition of X:

function X = fcn2 %#codegen

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

5-8
Reassignment of Variable Properties

Reassignment of Variable Properties


For C/C++ code generation, there are certain variables that you can reassign after the
initial assignment with a value of different class, size, or complexity:

Dynamically sized variables

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 “Variable-Size Data”.

Variables reused in the code for different purposes

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 “Reuse the Same Variable with Different Properties” on page
5-11.

5-9
5 Defining MATLAB Variables for C/C++ Code Generation

Define and Initialize Persistent Variables


Persistent variables are local to the function in which they are defined, but they retain
their values in memory between calls to the function. To define persistent variables for C/
C++ code generation, use the persistent statement, as in this example:

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:

function findProduct(inputvalue) %#codegen


persistent PROD_X

if isempty(PROD_X)
PROD_X = 1;
end
PROD_X = PROD_X * inputvalue;
end

5-10
Reuse the Same Variable with Different Properties

Reuse the Same Variable with Different Properties


In this section...
“When You Can Reuse the Same Variable with Different Properties” on page 5-11
“When You Cannot Reuse Variables” on page 5-11
“Limitations of Variable Reuse” on page 5-14

When You Can Reuse the Same Variable with Different Properties
You can reuse (reassign) an input, output, or local variable with different class, size, or
complexity if MATLAB can unambiguously determine the properties of each occurrence
of this variable during C/C++ code generation. If so, MATLAB creates separate uniquely
named local variables in the generated code. You can view these renamed variables
in the code generation report (see “MATLAB Code Variables in a Report” on page
22-18).

A common example of variable reuse is in if-elseif-else or switch-case


statements. For example, the following function example1 first uses the variable t in an
if statement, where it holds a scalar double, then reuses t outside the if statement to
hold a vector of doubles.

function y = example1(u) %#codegen


if all(all(u>0))
% First, t is used to hold a scalar double value
t = mean(mean(u)) / numel(u);
u = u - t;
end
% t is reused to hold a vector of doubles
t = find(u > 0);
y = sum(u(t(2:end-1)));
To compile this example and see how MATLAB renames the reused variable t, see
Variable Reuse in an if Statement.

When You Cannot Reuse Variables


You cannot reuse (reassign) variables if it is not possible to determine the class, size, and
complexity of an occurrence of a variable unambiguously during code generation. In this
case, variables cannot be renamed and a compilation error occurs.

5-11
5 Defining MATLAB Variables for C/C++ Code Generation

For example, the following example2 function assigns a fixed-point value to x in the if
statement and reuses x to store a matrix of doubles in the else clause. It then uses x
after the if-else statement. This function generates a compilation error because after
the if-else statement, variable x can have different properties depending on which if-
else clause executes.
function y = example2(use_fixpoint, data) %#codegen
if use_fixpoint
% x is fixed-point
x = fi(data, 1, 12, 3);
else
% x is a matrix of doubles
x = data;
end
% When x is reused here, it is not possible to determine its
% class, size, and complexity
t = sum(sum(x));
y = t > 0;
end

Variable Reuse in an if Statement

To see how MATLAB renames a reused variable t:

1 Create a MATLAB file example1.m containing the following code.


function y = example1(u) %#codegen
if all(all(u>0))
% First, t is used to hold a scalar double value
t = mean(mean(u)) / numel(u);
u = u - t;
end
% t is reused to hold a vector of doubles
t = find(u > 0);
y = sum(u(t(2:end-1)));
end
2 Compile example1.

For example, to generate a MEX function, enter:


codegen -o example1x -report example1.m -args {ones(5,5)}

Note: codegen requires a MATLAB Coder license.

5-12
Reuse the Same Variable with Different Properties

When the compilation is complete, codegen generates a MEX function, example1x


in the current folder, and provides a link to the code generation report.
3 Open the code generation report.
4 In the MATLAB code pane of the code generation report, place your pointer over the
variable t inside the if statement.

The code generation report highlights both instances of t in the if statement


because they share the same class, size, and complexity. It displays the data type
information for t at this point in the code. Here, t is a scalar double.

5 In the MATLAB code pane of the report, place your pointer over the variable t
outside the for-loop.

This time, the report highlights both instances of t outside the if statement. The
report indicates that t might hold up to 25 doubles. The size of t is :25, that is, a
column vector containing a maximum of 25 doubles.

6 Click the Variables tab to view the list of variables used in example1.

5-13
5 Defining MATLAB Variables for C/C++ Code Generation

The report displays a list of the variables in example1. There are two uniquely
named local variables t>1 and t>2.
7 In the list of variables, place your pointer over t>1.

The code generation report highlights both instances of t in the if statement.


8 In the list of variables, place your pointer over t>2

The code generation report highlights both instances of t outside the if statement.

Limitations of Variable Reuse


The following variables cannot be renamed in generated code:

• 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.
• The block outputs of a MATLAB Function block in a Simulink model.
• Chart-owned variables of a MATLAB function in a Stateflow® chart.

5-14
Avoid Overflows in for-Loops

Avoid Overflows in for-Loops


When memory integrity checks are enabled, if the code generation software detects that a
loop variable might overflow on the last iteration of the for-loop, it reports an error.

To avoid this error, use the workarounds provided in the following table.

Loop conditions causing the error Workaround


• The loop counter increments by 1 Rewrite the loop so that the end value is
• The end value equals the maximum not equal to the maximum value of the
value of the integer type integer type. For example, replace:

• The loop is not covering the full range of N=intmax('int16')


the integer type for k=N-10:N
with:
for k=1:10
• The loop counter decrements by 1 Rewrite the loop so that the end value is
• The end value equals the minimum not equal to the minimum value of the
value of the integer type integer type. For example, replace:

• The loop is not covering the full range of N=intmin('int32')


the integer type for k=N+10:-1:N
with:
for k=10:-1:1
• The loop counter increments or Rewrite the loop casting the type of the
decrements by 1 loop counter start, step, and end values to
• The start value equals the minimum or a bigger integer or to double For example,
maximum value of the integer type rewrite:

• The end value equals the maximum or M= intmin('int16');


minimum value of the integer type N= intmax('int16');
for k=M:N
The loop covers the full range of the integer % Loop body
type. end
to
M= intmin('int16');
N= intmax('int16');
for k=int32(M):int32(N)
% Loop body

5-15
5 Defining MATLAB Variables for C/C++ Code Generation

Loop conditions causing the error Workaround


end
• The loop counter increments or Rewrite the loop so that the loop variable
decrements by a value not equal to 1 on the last loop iteration is equal to the end
• On last loop iteration, the loop variable value.
value is not equal to the end value

Note: The software error checking is


conservative. It may incorrectly report a
loop as being potentially infinite.

5-16
Supported Variable Types

Supported Variable Types


You can use the following data types for C/C++ code generation from MATLAB:

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
int64
logical Boolean true or false
single Single-precision floating point
struct Structure
uint8, uint16, Unsigned integer
uint32, uint64
Fixed-point See “Fixed-Point Data Types”.

5-17
6

Defining Data for Code Generation

• “Data Definition for Code Generation” on page 6-2


• “Code Generation for Complex Data” on page 6-4
• “Code Generation for Characters and Strings” on page 6-9
• “Array Size Restrictions for Code Generation” on page 6-10
• “Code Generation for Constants in Structures and Arrays” on page 6-11
6 Defining Data for Code Generation

Data Definition for Code Generation


To generate efficient standalone code, you must define the following types and classes
of data differently than you normally would when running your code in the MATLAB
environment:

Data What's Different More Information


Arrays Maximum number of “Array Size Restrictions for
elements is restricted Code Generation” on page
6-10
Complex numbers • Complexity of variables “Code Generation for
must be set at time of Complex Data” on page
assignment and before 6-4
first use
• Expressions containing
a complex number or
variable evaluate to a
complex result, even if
the result is zero

Note: Because MATLAB


does not support complex
integer arithmetic, you
cannot generate code for
functions that use complex
integer arithmetic
Characters Restricted to 8 bits of “Code Generation for
precision Characters and Strings” on
page 6-9
Enumerated data • Supports integer-based “Enumerated Data”
enumerated types only
• Restricted use in
switch statements and
for-loops
Function handles • Using the same bound “Function Handles”
variable to reference

6-2
Data Definition for Code Generation

Data What's Different More Information


different function
handles can cause a
compile-time error.
• Cannot pass function
handles to or from
primary or extrinsic
functions
• Cannot view function
handles from the
debugger

6-3
6 Defining Data for Code Generation

Code Generation for Complex Data


In this section...
“Restrictions When Defining Complex Variables” on page 6-4
“Code Generation for Complex Data with Zero-Valued Imaginary Parts” on page
6-4
“Results of Expressions That Have Complex Operands” on page 6-8

Restrictions When Defining Complex Variables


For code generation, you must set the complexity of variables at the time of assignment.
Assign a complex constant to the variable or use the complex function. For example:

x = 5 + 6i; % x is a complex number by assignment.


y = complex(5,6); % y is the complex number 5 + 6i.

After assignment, you cannot change the complexity of a variable. Code generation for
the following function fails because x(k) = 3 + 4i changes the complexity of x.

function x = test1( )
x = zeros(3,3); % x is real
for k = 1:numel(x)
x(k) = 3 + 4i;
end
end

To resolve this issue, assign a complex constant to x.

function x = test1( )
x = zeros(3,3)+ 0i; %x is complex
for k = 1:numel(x)
x(k) = 3 + 4i;
end
end

Code Generation for Complex Data with Zero-Valued Imaginary Parts


For code generation, complex data that has all zero-valued imaginary parts remains
complex. This data does not become real. This behavior has the following implications:

6-4
Code Generation for Complex Data

• In some cases, results from functions that sort complex data by absolute value can
differ from the MATLAB results. See “Functions That Sort Complex Values by
Absolute Value” on page 6-5.
• For functions that require that complex inputs are sorted by absolute value, complex
inputs with zero-valued imaginary parts must be sorted by absolute value. These
functions include ismember, union, intersect, setdiff, and setxor.

Functions That Sort Complex Values by Absolute Value

Functions that sort complex values by absolute value include sort, issorted,
sortrows, median, min, and max. These functions sort complex numbers by absolute
value even when the imaginary parts are zero. In general, sorting the absolute values
produces a different result than sorting the real parts. Therefore, when inputs to these
functions are complex with zero-valued imaginary parts in generated code, but real
in MATLAB, the generated code can produce different results than MATLAB. In the
following examples, the input to sort is real in MATLAB, but complex with zero-valued
imaginary parts in the generated code:

• You Pass Real Inputs to a Function Generated for Complex Inputs

1 Write this function:

function myout = mysort(A)


myout = sort(A);
end
2 Call mysort in MATLAB.

A = -2:2;
mysort(A)

ans =

-2 -1 0 1 2
3 Generate a MEX function for complex inputs.

A = -2:2;
codegen mysort -args {complex(A)} -report
4 Call the MEX Function with real inputs.

mysort_mex(A)

ans =

6-5
6 Defining Data for Code Generation

0 1 -1 2 -2

You generated the MEX function for complex inputs, therefore, it treats the
real inputs as complex numbers with zero-valued imaginary parts. It sorts the
numbers by the absolute values of the complex numbers. Because the imaginary
parts are zero, the MEX function returns the results to the MATLAB workspace
as real numbers. See “Inputs and Outputs for MEX Functions Generated for
Complex Arguments” on page 6-7.
• Input to sort Is Output from a Function That Returns Complex in Generated Code

1 Write this function:

function y = myfun(A)
x = eig(A);
y = sort(x,'descend');

The output from eig is the input to sort. In generated code, eig returns a
complex result. Therefore, in the generated code, x is complex.
2 Call myfun in MATLAB.

A = [2 3 5;0 5 5;6 7 4];


myfun(A)

ans =

12.5777
2.0000
-3.5777
The result of eig is real. Therefore, the inputs to sort are real.
3 Generate a MEX function for complex inputs.

codegen myfun -args {complex(A)}


4 Call the MEX function.

myfun_mex(A)

ans =

12.5777
-3.5777
2.0000

6-6
Code Generation for Complex Data

In the MEX function, eig returns a complex result. Therefore, the inputs to
sort are complex. The MEX function sorts the inputs in descending order of the
absolute values.

Inputs and Outputs for MEX Functions Generated for Complex Arguments

For MEX functions created by MATLAB Coder:

• Suppose that you generate the MEX function for complex inputs. If you call the MEX
function with real inputs, the MEX function transforms the real inputs to complex
values with zero-valued imaginary parts.
• If the MEX function returns complex values that have all zero-valued imaginary
parts, the MEX function returns the values to the MATLAB workspace as real values.
For example, consider this function:

function y = foo()
y = 1 + 0i; % y is complex with imaginary part equal to zero
end

If you generate a MEX function for foo and view the code generation report, you see
that y is complex.

codegen foo -report

If you run the MEX function, you see that in the MATLAB workspace, the result of
foo_mex is the real value 1.

z = foo_mex

ans =

6-7
6 Defining Data for Code Generation

Results of Expressions That Have Complex Operands


In general, expressions that contain one or more complex operands produce a complex
result in generated code, even if the value of the result is zero. Consider the following line
of code:
z = x + y;

Suppose that at run time, x has the value 2 + 3i and y has the value 2 - 3i. In
MATLAB, this code produces the real result z = 4. During code generation, the types
for x and y are known, but their values are not known. Because either or both operands
in this expression are complex, z is defined as a complex variable requiring storage for a
real and an imaginary part. z equals the complex result 4 + 0i in generated code, not 4,
as in MATLAB code.

Exceptions to this behavior are:

• When the imaginary parts of complex results are zero, MEX functions return the
results to the MATLAB workspace as real values. See “Inputs and Outputs for MEX
Functions Generated for Complex Arguments” on page 6-7.
• When the imaginary part of the argument is zero, complex arguments to extrinsic
functions are real .
function y = foo()
coder.extrinsic('sqrt')
x = 1 + 0i; % x is complex
y = sqrt(x); % x is real, y is real
end
• Functions that take complex arguments but produce real results return real values.
y = real(x); % y is the real part of the complex number x.
y = imag(x); % y is the real-valued imaginary part of x.
y = isreal(x); % y is false (0) for a complex number x.
• Functions that take real arguments but produce complex results return complex
values.
z = complex(x,y); % z is a complex number for a real x and y.

6-8
Code Generation for Characters and Strings

Code Generation for Characters and Strings


The code generation software translates the 16-bit Unicode® encoding of a character in
MATLAB to an 8-bit encoding that the locale setting determines. The code generation
software does not support characters that require more than 1 byte in MATLAB. This
restriction applies to constant strings and strings that are passed between MATLAB and
the code generation software. For example, the restriction applies to entry-point function
inputs and to outputs from extrinsic calls. For code generation, some MATLAB functions
accept only 7-bit ASCII strings. See “Functions and Objects Supported for C and C++
Code Generation — Alphabetical List” on page 4-2.

If a character is not in the 7-bit ASCII codeset, casting the character to a numeric type,
such as double, produces a different result in the generated code than in MATLAB. A
best practice for code generation is to avoid performing arithmetic with characters.

More About
• “Locale Settings for MATLAB Process”

6-9
6 Defining Data for Code Generation

Array Size Restrictions for Code Generation


For code generation, the maximum number of elements of an array is constrained by the
code generation software and the target hardware.

For fixed-size arrays and variable-size arrays that use static memory allocation, the
maximum number of elements is the smaller of:

• intmax('int32').
• The largest integer that fits in the C int data type on the target hardware.

For variable-size arrays that use dynamic memory allocation, the maximum number of
elements is the smaller of:

• intmax('int32').
• The largest power of 2 that fits in the C int data type on the target hardware.

These restrictions apply even on a 64-bit platform.

For a fixed-size array, if the number of elements exceeds the maximum, the code
generation software reports an error at compile time. For a variable-size array, if the
number of elements exceeds the maximum during execution of the generated MEX in
MATLAB, the MEX code reports an error. Generated standalone code cannot report
array size violations.

See Also
• “Variable-Size Data”
• coder.HardwareImplementation

6-10
Code Generation for Constants in Structures and Arrays

Code Generation for Constants in Structures and Arrays


The code generation software does not recognize constant structure fields or array
elements in the following cases:

Fields or elements are assigned inside control constructs

In the following code, the code generation software recognizes that the structure fields
s.a and s.b are constants.

function y = mystruct()
s.a = 3;
s.b = 5;
y = zeros(s.a,s.b);

If any structure field is assigned inside a control construct, the code generation software
does not recognize the constant fields. This limitation also applies to arrays with constant
elements. Consider the following code:

function y = mystruct(x)
s.a = 3;
if x > 1
s.b = 4;
else
s.b = 5;
end
y = zeros(s.a,s.b);

The code generation software does not recognize that s.a and s.b are constant. If
variable-sizing is enabled, y is treated as a variable-size array. If variable-sizing is
disabled, the code generation software reports an error.

Constants are assigned to array elements using non-scalar indexing

In the following code, the code generation software recognizes that a(1) is constant.

function y = myarray()
a = zeros(1,3);
a(1) = 20;
y = coder.const(a(1));

In the following code, because a(1) is assigned using non-scalar indexing, the code
generation software does not recognize that a(1) is constant.

6-11
6 Defining Data for Code Generation

function y = myarray()
a = zeros(1,3);
a(1:2) = 20;
y = coder.const(a(1));

A function returns a structure or array that has constant and nonconstant elements

For an output structure that has both constant and nonconstant fields, the code
generation software does not recognize the constant fields. This limitation also applies to
arrays that have constant and nonconstant elements. Consider the following code:
function y = mystruct_out(x)
s = create_structure(x);
y = coder.const(s.a);

function s = create_structure(x)
s.a = 10;
s.b = x;

Because create_structure returns a structure s that has one constant field and one
nonconstant field, the code generation software does not recognize that s.a is constant.
The coder.const call fails because s.a is not constant.

6-12
7

Code Generation for Variable-Size


Data

• “What Is Variable-Size Data?” on page 7-2


• “Variable-Size Data Definition for Code Generation” on page 7-3
• “Bounded Versus Unbounded Variable-Size Data” on page 7-4
• “Control Memory Allocation of Variable-Size Data” on page 7-5
• “Specify Variable-Size Data Without Dynamic Memory Allocation” on page 7-6
• “Variable-Size Data in Code Generation Reports” on page 7-9
• “Define Variable-Size Data for Code Generation” on page 7-11
• “C Code Interface for Arrays” on page 7-17
• “Diagnose and Fix Variable-Size Data Errors” on page 7-22
• “Incompatibilities with MATLAB in Variable-Size Support for Code Generation” on
page 7-26
• “Variable-Sizing Restrictions for Code Generation of Toolbox Functions” on page
7-35
7 Code Generation for Variable-Size Data

What Is Variable-Size Data?


Variable-size data is data whose size can change at run time. By contrast, fixed-size data
is data whose size is known and locked at compile time and, therefore, cannot change at
run time.

For example, in the following MATLAB function nway, B is a variable-size array; its
length is not known at compile time.
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

7-2
Variable-Size Data Definition for Code Generation

Variable-Size Data Definition for Code Generation


In the MATLAB language, data can vary in size. By contrast, the semantics of generated
code constrains the class, complexity, and shape of every expression, variable, and
structure field. Therefore, for code generation, you must use each variable consistently.
Each variable must:

• Be either complex or real (determined at first assignment)


• Have a consistent shape

For fixed-size data, the shape is the same as the size returned in MATLAB. For
example, if size(A) == [4 5], the shape of variable A is 4 x 5. For variable-size
data, the shape can be abstract. That is, one or more dimensions can be unknown
(such as 4x? or ?x?).

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.

For more information, see “Bounded Versus Unbounded Variable-Size Data” on page
7-4

7-3
7 Code Generation for Variable-Size Data

Bounded Versus Unbounded Variable-Size Data


You can generate code for bounded and unbounded variable-size data. Bounded variable-
size data has fixed upper bounds; this data can be allocated statically on the stack
or dynamically on the heap. Unbounded variable-size data does not have fixed upper
bounds; this data must be allocated on the heap. If you use unbounded data, you must
use dynamic memory allocation so that the compiler:

• Does not check for upper bounds


• Allocates memory on the heap instead of the stack

You can control the memory allocation of variable-size data. For more information, see
“Control Memory Allocation of Variable-Size Data” on page 7-5.

7-4
Control Memory Allocation of Variable-Size Data

Control Memory Allocation of Variable-Size Data


Data whose size (in bytes) is greater than or equal to the dynamic memory allocation
threshold is allocated on the heap. The default dynamic memory allocation threshold is
64 kilobytes. Data whose size is less than this threshold is allocated on the stack.

Dynamic memory allocation is an expensive operation; the performance cost might be


too high for small data sets. If you use small variable-size data sets or data that does
not change size at run time, disable dynamic memory allocation. See “Control Dynamic
Memory Allocation” on page 21-106.

You can control memory allocation globally for your application by modifying the
dynamic memory allocation threshold. See “Generate Code for a MATLAB Function
That Expands a Vector in a Loop” on page 21-109. You can control memory allocation
for individual variables by specifying upper bounds. See “Specifying Upper Bounds for
Variable-Size Data” on page 7-6.

7-5
7 Code Generation for Variable-Size Data

Specify Variable-Size Data Without Dynamic Memory Allocation


In this section...
“Fixing Upper Bounds Errors” on page 7-6
“Specifying Upper Bounds for Variable-Size Data” on page 7-6

Fixing Upper Bounds Errors


If MATLAB cannot determine or compute the upper bound, you must specify an upper
bound. See “Specifying Upper Bounds for Variable-Size Data” on page 7-6 and
“Diagnosing and Fixing Errors in Detecting Upper Bounds” on page 7-24

Specifying Upper Bounds for Variable-Size Data


• “When to Specify Upper Bounds for Variable-Size Data” on page 7-6
• “Specifying Upper Bounds on the Command Line for Variable-Size Inputs” on page
7-6
• “Specifying Unknown Upper Bounds for Variable-Size Inputs” on page 7-7
• “Specifying Upper Bounds for Local Variable-Size Data” on page 7-7
• “Using a Matrix Constructor with Nonconstant Dimensions” on page 7-8

When to Specify Upper Bounds for Variable-Size Data

When using static allocation on the stack during code generation, MATLAB must be able
to determine upper bounds for variable-size data. Specify the upper bounds explicitly for
variable-size data from external sources, such as inputs and outputs.

Specifying Upper Bounds on the Command Line for Variable-Size Inputs

Use the coder.typeof construct with the -args option on the codegen command line
(requires a MATLAB Coder license). For example:

codegen foo -args {coder.typeof(double(0),[3 100],1)}


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.

7-6
Specify Variable-Size Data Without Dynamic Memory Allocation

Specifying Unknown Upper Bounds for Variable-Size Inputs

If you use dynamic memory allocation, you can specify that you don't know the upper
bounds of inputs. To specify an unknown upper bound, use the infinity constant Inf in
place of a numeric value. For example:

codegen foo -args {coder.typeof(double(0), [1 Inf])}

In this example, the input to function foo is a vector of real doubles without an upper
bound.

Specifying Upper Bounds for Local Variable-Size Data

When using static allocation, MATLAB uses a sophisticated analysis to calculate the
upper bounds of local data at compile time. However, when the analysis fails to detect an
upper bound or calculates an upper bound that is not precise enough for your application,
you need to specify upper bounds explicitly for local variables.

You do not need to specify upper bounds when using dynamic allocation on the heap. In
this case, MATLAB assumes variable-size data is unbounded and does not attempt to
determine upper bounds.
Constraining the Value of a Variable That Specifies Dimensions of Variable-Size Data

Use the assert function with relational operators to constrain the value of variables
that specify the dimensions of variable-size data. For example:

function y = dim_need_bound(n) %#codegen


assert (n <= 5);
L= ones(n,n);
M = zeros(n,n);
M = [L; M];
y = M;

This assert statement constrains input n to a maximum size of 5, defining L and M as


variable-sized matrices with upper bounds of 5 for each dimension.
Specifying the Upper Bounds for All Instances of a Local Variable

Use the coder.varsize function to specify the upper bounds for all instances of a local
variable in a function. For example:

function Y = example_bounds1(u) %#codegen


Y = [1 2 3 4 5];

7-7
7 Code Generation for Variable-Size Data

coder.varsize('Y',[1 10]);
if (u > 0)
Y = [Y Y+u];
else
Y = [Y Y*u];
end

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:

• First dimension is fixed at size 1


• Second dimension can grow to an upper bound of 10

By default, coder.varsize assumes dimensions of 1 are fixed size. For more


information, see the coder.varsize reference page.

Using a Matrix Constructor with Nonconstant Dimensions

You can define a variable-size matrix by using a constructor with nonconstant


dimensions. For example:
function y = var_by_assign(u) %#codegen
if (u > 0)
y = ones(3,u);
else
y = zeros(3,1);
end
If you are not using dynamic memory allocation, you must also add an assert statement
to provide upper bounds for the dimensions. For example:
function y = var_by_assign(u) %#codegen
assert (u < 20);
if (u > 0)
y = ones(3,u);
else
y = zeros(3,1);
end

7-8
Variable-Size Data in Code Generation Reports

Variable-Size Data in Code Generation Reports

In this section...
“What Reports Tell You About Size” on page 7-9
“How Size Appears in Code Generation Reports” on page 7-10
“How to Generate a Code Generation Report” on page 7-10

What Reports Tell You About Size


Code generation reports:

• Differentiate fixed-size from variable-size data


• Identify variable-size data with unknown upper bounds
• Identify variable-size data with fixed dimensions

If you define a variable-size array and then subsequently fix the dimensions of this
array in the code, the report appends * to the size of the variable. In the generated C
code, this variable appears as a variable-size array, but the size of its dimensions does
not change during execution.
• Provide guidance on how to fix size mismatch and upper bounds errors.

7-9
7 Code Generation for Variable-Size Data

How Size Appears in Code Generation Reports


:? means variable size,
unknown upper bound

No colon prefix (:)


means fixed size

:100 means variable size,


upper bound = 100

* means that you declared y as variable size,


but subsequently fixed its dimensions

How to Generate a Code Generation Report


Add the -report option to your codegen command.

7-10
Define Variable-Size Data for Code Generation

Define Variable-Size Data for Code Generation


In this section...
“When to Define Variable-Size Data Explicitly” on page 7-11
“Using a Matrix Constructor with Nonconstant Dimensions” on page 7-11
“Inferring Variable Size from Multiple Assignments” on page 7-12
“Defining Variable-Size Data Explicitly Using coder.varsize” on page 7-13

When to Define Variable-Size Data Explicitly


For code generation, you must assign variables to have a specific class, size, and
complexity before using them in operations or returning them as outputs. Generally, you
cannot reassign variable properties after the initial assignment. Therefore, attempts to
grow a variable or structure field after assigning it a fixed size might cause a compilation
error. In these cases, you must explicitly define the data as variable sized using one of
these methods:

Method See
Assign the data from a variable-size matrix “Using a Matrix Constructor with
constructor such as Nonconstant Dimensions” on page 7-11

• ones
• zeros
• repmat
Assign multiple, constant sizes to the “Inferring Variable Size from Multiple
same variable before using (reading) the Assignments” on page 7-12
variable.
Define all instances of a variable to be “Defining Variable-Size Data Explicitly
variable sized Using coder.varsize” on page 7-13

Using a Matrix Constructor with Nonconstant Dimensions


You can define a variable-size matrix by using a constructor with nonconstant
dimensions. For example:

7-11
7 Code Generation for Variable-Size Data

function y = var_by_assign(u) %#codegen


if (u > 0)
y = ones(3,u);
else
y = zeros(3,1);
end
If you are not using dynamic memory allocation, you must also add an assert statement
to provide upper bounds for the dimensions. For example:

function y = var_by_assign(u) %#codegen


assert (u < 20);
if (u > 0)
y = ones(3,u);
else
y = zeros(3,1);
end

Inferring Variable Size from Multiple Assignments


You can define variable-size data by assigning multiple, constant sizes to the same
variable before you use (read) the variable in your code. When MATLAB uses static
allocation on the stack for code generation, it infers the upper bounds from the largest
size specified for each dimension. When you assign the same size to a given dimension
across all assignments, MATLAB assumes that the dimension is fixed at that size. The
assignments can specify different shapes as well as sizes.

When dynamic memory allocation is used, MATLAB does not check for upper bounds; it
assumes variable-size data is unbounded.

Inferring Upper Bounds from Multiple Definitions with Different Shapes

function y = var_by_multiassign(u) %#codegen


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:

• First dimension is fixed at size 3

7-12
Define Variable-Size Data for Code Generation

• Second dimension is variable with an upper bound of 4


• Third dimension is variable with an upper bound of 5

The code generation report represents the size of matrix y like this:

When dynamic allocation is used, the function analyzes the dimensions of y differently:

• First dimension is fixed at size 3


• Second and third dimensions are unbounded

In this case, the code generation report represents the size of matrix y like this:

Defining Variable-Size Data Explicitly Using coder.varsize


Use the function coder.varsize to define one or more variables or structure fields as
variable-size data. Optionally, you can also specify which dimensions vary along with
their upper bounds (see “Specifying Which Dimensions Vary” on page 7-14). For
example:

• Define B as a variable-size 2-by-2 matrix, where each dimension has an upper bound
of 64:

coder.varsize('B', [64 64]);


• Define B as a variable-size matrix:

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).

7-13
7 Code Generation for Variable-Size Data

For more information, see the coder.varsize reference page.

Specifying Which Dimensions Vary

You can use the function coder.varsize to specify which dimensions vary. For
example, the following statement defines B as a row vector whose first dimension is fixed
at 2, but whose second dimension can grow to an upper bound of 16:

coder.varsize('B',[2, 16],[0 1])


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 7-14).

For more information about the syntax, see the coder.varsize reference page.

Allowing a Variable to Grow After Defining Fixed Dimensions

Function var_by_if defines matrix Y with fixed 2-by-2 dimensions before first use
(where the statement Y = Y + u reads from Y). However, coder.varsize defines Y
as a variable-size matrix, allowing it to change size based on decision logic in the else
clause:

function Y = var_by_if(u) %#codegen


if (u > 0)
Y = zeros(2,2);
coder.varsize('Y');
if (u < 10)
Y = Y + u;
end
else
Y = zeros(5,5);
end

Without coder.varsize, MATLAB infers Y to be a fixed-size, 2-by-2 matrix and


generates a size mismatch error during code generation.

Defining Variable-Size Matrices with Singleton Dimensions

A singleton dimension is a dimension for which size(A,dim) = 1. Singleton dimensions


are fixed in size when:

7-14
Define Variable-Size Data for Code Generation

• You specify a dimension with an upper bound of 1 in coder.varsize expressions.

For example, in this function, Y behaves like a vector with one variable-size
dimension:
function Y = dim_singleton(u) %#codegen
Y = [1 2];
coder.varsize('Y', [1 10]);
if (u > 0)
Y = [Y 3];
else
Y = [Y u];
end
• You initialize variable-size data with singleton dimensions using matrix constructor
expressions or matrix functions.

For example, in this function, both X and Y behave like vectors where only their
second dimensions are variable sized:
function [X,Y] = dim_singleton_vects(u) %#codegen
Y = ones(1,3);
X = [1 4];
coder.varsize('Y','X');
if (u > 0)
Y = [Y u];
else
X = [X u];
end

You can override this behavior by using coder.varsize to specify explicitly that
singleton dimensions vary. For example:
function Y = dim_singleton_vary(u) %#codegen
Y = [1 2];
coder.varsize('Y', [1 10], [1 1]);
if (u > 0)
Y = [Y Y+u];
else
Y = [Y Y*u];
end

In this example, the third argument of coder.varsize is a vector of ones, indicating


that each dimension of Y varies in size. For more information, see the coder.varsize
reference page.

7-15
7 Code Generation for Variable-Size Data

Defining Variable-Size Structure Fields

To define structure fields as variable-size arrays, use colon (:) as the index expression.
The colon (:) indicates that all elements of the array are variable sized. For example:

function y=struct_example() %#codegen

d = struct('values', zeros(1,0), 'color', 0);


data = repmat(d, [3 3]);
coder.varsize('data(:).values');

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

The expression coder.varsize('data(:).values') defines the field values inside


each element of matrix data to be variable sized.

Here are other examples:

• 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.

7-16
C Code Interface for Arrays

C Code Interface for Arrays


In this section...
“C Code Interface for Statically Allocated Arrays” on page 7-17
“C Code Interface for Dynamically Allocated Arrays” on page 7-18
“Utility Functions for Creating emxArray Data Structures” on page 7-20

C Code Interface for Statically Allocated Arrays


For statically allocated arrays, the generated code contains the definition of the array
and the size of the array.

For example, consider the MATLAB function myuniquetol.

function B = myuniquetol(A, tol) %#codegen


A = sort(A);
coder.varsize('B', [1 100], [0 1]);
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

The statement coder.varsize('B', [1 100], [0 1]) specifies that B is a variable-


size array whose first dimension is fixed at 1 and second dimension can vary up to 100
elements. Without this statement, B is a dynamically allocated array.

Generate code for myuniquetol specifying that input A is a variable-size real double
vector whose first dimension is fixed at 1 and second dimension can vary up to 100
elements.

codegen -config:lib -report myuniquetol -args {coder.typeof(0,[1 100],1),coder.typeof(0)}

In the generated code, the function declaration is:

extern void myuniquetol(const double A_data[], const int A_size[2], double tol,
double B_data[], int B_size[2])

7-17
7 Code Generation for Variable-Size Data

The function signature declares the input argument A and the output argument
B. A_size contains the size of A. B_size contains the size of B after the call to
myuniquetol. Use B_size to determine the number of elements of B that you can access
after the call to myuniquetol. B_size[0] contains the size of the first dimension.
B_size[1] contains the size of the second dimension. Therefore, the number of elements
of B is B_size[0]*B_Size[1]. Even though B has 100 elements in the C code, only
B_size[0]*B_Size[1] elements contain valid data.

The following C main function shows how to call myuniquetol.

void main()
{
double A[100], B[100];
int A_size[2] = { 1, 100 };
int B_size[2];
int i;
for (i = 0; i < 100; i++) {
A[i] = (double)1/i;
}
myuniquetol(A, A_size, 0.1, B, B_size);
}

C Code Interface for Dynamically Allocated Arrays


In generated code, MATLAB represents dynamically allocated data as a structure type
called emxArray. An embeddable version of the MATLAB mxArray, the emxArray is a
family of data types, specialized for all base types.

emxArray Structure Definition

typedef struct emxArray_<baseTypedef>


{
<baseType> *data;
int *size;
int allocatedSize;
int numDimensions;
boolean_T canFreeData;
} emxArray_<baseTypedef>;

baseTypedef is the predefined type in rtwtypes.h corresponding to baseType. For


example, here is the definition for an emxArray of base type double with unknown
upper bounds:

7-18
C Code Interface for Arrays

typedef struct emxArray_real_T


{
double *data;
int *size;
int allocatedSize;
int numDimensions;
boolean_T canFreeData;
} emxArray_real_T;

The predefined type corresponding to double is real_T. For more information on the
correspondence between built-in data types and predefined types in rtwtypes.h, see
“How MATLAB Coder Infers C/C++ Data Types” on page 27-9.

To define two variables, in1 and in2, of this type, use this statement:

emxArray_real_T *in1, *in2;

C Code Interface for Structure Fields

Field Description
*data Pointer to data of type <baseType>.
*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

7-19
7 Code Generation for Variable-Size Data

Utility Functions for Creating emxArray Data Structures


When you generate code that uses variable-size data, the code generation software
exports a set of utility functions that you can use to create and interact with emxArrays
in your generated code. To call these functions in your main C function, include the
generated header file. For example, when you generate code for function foo, include
foo_emxAPI.h in your main C function. For more information, see the “Write a C Main
Function” section in “Using Dynamic Memory Allocation for an "Atoms" Simulation” on
page 21-115.

Note: The code generation software exports emxArray utility functions only for variable-
size arrays that are entry-point function arguments or that are used by functions called
by coder.ceval.

Function Arguments Description


emxArray_<baseType> *data Creates a new 2-
*emxCreateWrapper_<baseType> num_rows dimensional emxArray,
(...) num_cols but does not allocate
it on the heap. Instead
uses memory provided
by the user and sets
canFreeData to
false so it does not
inadvertently free user
memory, such as the
stack.
emxArray_<baseType> *data Same as
*emxCreateWrapperND_<baseType> numDimensions emxCreateWrapper_<baseType>,
(...) *size except it creates a
new N-dimensional
emxArray.
emxArray_<baseType> num_rows Creates a new two-
*emxCreate_<baseType> (...) num_cols dimensional emxArray
on the heap, initialized
to zero. All data
elements have the

7-20
C Code Interface for Arrays

Function Arguments Description


data type specified by
<baseType>.
emxArray_<baseType> numDimensions Same as
*emxCreateND_<baseType> (...) *size emxCreate_<baseType>,
except it creates a
new N-dimensional
emxArray on the heap.
void emxInitArray_<baseType> **emxArray Creates a new empty
(...) numDimensions emxArray on the heap.
All data elements have
the data type specified
by <baseType>.
void emxInitArray_<structType> *structure Creates empty
(...) emxArrays in a
structure.
void emxDestroyArray_<baseType> *emxArray Frees dynamic
(...) memory allocated by
emxCreate_<baseType>,
emxCreateND_<baseType>,
and
emxInitArray_baseType
functions.
void emxDestroyArray_<structType> *structure Frees dynamic
(...) memory allocated by
emxInitArray_<structType>
functions.

By default, when you generate C/C++ source code, static libraries, dynamic libraries, and
executables, MATLAB Coder generates an example C/C++ main function. The example
main function is a template that can help you to incorporate generated C/C++ code into
your application. If you generate code that uses dynamically allocated data, the example
main function includes calls to emxArray utility functions that create emxArrays
required for this data. The example main function also initializes emxArray data to zero
values. For more information, see “Incorporate Generated Code Using an Example Main
Function” on page 25-18.

7-21
7 Code Generation for Variable-Size Data

Diagnose and Fix Variable-Size Data Errors


In this section...
“Diagnosing and Fixing Size Mismatch Errors” on page 7-22
“Diagnosing and Fixing Errors in Detecting Upper Bounds” on page 7-24

Diagnosing and Fixing Size Mismatch Errors


Check your code for these issues:

Assigning Variable-Size Matrices to Fixed-Size Matrices

You cannot assign variable-size matrices to fixed-size matrices in generated code.


Consider this example:

function Y = example_mismatch1(n) %#codegen


assert(n < 10);
B = ones(n,n);
A = magic(3);
A(1) = mean(A(:));
if (n == 3)
A = B;
end
Y = A;

Compiling this function produces this error:

??? Dimension 1 is fixed on the left-hand side


but varies on the right ...

There are several ways to fix this error:

• Allow matrix A to grow by adding the coder.varsize construct:

function Y = example_mismatch1_fix1(n) %#codegen


coder.varsize('A');
assert(n < 10);
B = ones(n,n);
A = magic(3);
A(1) = mean(A(:));
if (n == 3)

7-22
Diagnose and Fix Variable-Size Data Errors

A = B;
end
Y = A;
• Explicitly restrict the size of matrix B to 3-by-3 by modifying the assert statement:

function Y = example_mismatch1_fix2(n) %#codegen


coder.varsize('A');
assert(n == 3)
B = ones(n,n);
A = magic(3);
A(1) = mean(A(:));
if (n == 3)
A = B;
end
Y = A;
• Use explicit indexing to make B the same size as A:

function Y = example_mismatch1_fix3(n) %#codegen


assert(n < 10);
B = ones(n,n);
A = magic(3);
A(1) = mean(A(:));
if (n == 3)
A = B(1:3, 1:3);
end
Y = A;

Empty Matrix Reshaped to Match Variable-Size Specification

If you assign an empty matrix [] to variable-size data, MATLAB might silently reshape
the data in generated code to match a coder.varsize specification. For example:

function Y = test(u) %#codegen


Y = [];
coder.varsize(‘Y’, [1 10]);
if u < 0
Y = [Y u];
end

In this example, coder.varsize defines Y as a column vector of up to 10 elements,


so its first dimension is fixed at size 1. The statement Y = [] designates the first
dimension of Y as 0, creating a mismatch. The right hand side of the assignment is an
empty matrix and the left hand side is a variable-size vector. In this case, MATLAB

7-23
7 Code Generation for Variable-Size Data

reshapes the empty matrix Y = [] in generated code to Y = zeros(1,0) so it matches


the coder.varsize specification.

Performing Binary Operations on Fixed and Variable-Size Operands

You cannot perform binary operations on operands of different sizes. Operands have
different sizes if one has fixed dimensions and the other has variable dimensions. For
example:

function z = mismatch_operands(n) %#codegen


assert(n >= 3 && n < 10);
x = ones(n,n);
y = magic(3);
z = x + y;

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:

function z = mismatch_operands_fix(n) %#codegen


assert(n >= 3 && n < 10);
x = ones(n,n);
y = magic(3);
z = x(1:3,1:3) + y;

Diagnosing and Fixing Errors in Detecting Upper Bounds


Check your code for these issues:

Using Nonconstant Dimensions in a Matrix Constructor

You can define variable-size data by assigning a variable to a matrix with nonconstant
dimensions. For example:

function y = dims_vary(u) %#codegen


if (u > 0)
y = ones(3,u);
else
y = zeros(3,1);
end

However, compiling this function generates an error because you did not specify an upper
bound for u.

7-24
Diagnose and Fix Variable-Size Data Errors

There are several ways to fix the problem:

• Enable dynamic memory allocation and recompile. During code generation, MATLAB
does not check for upper bounds when it uses dynamic memory allocation for variable-
size data.
• If you do not want to use dynamic memory allocation, add an assert statement
before the first use of u:

function y = dims_vary_fix(u) %#codegen


assert (u < 20);
if (u > 0)
y = ones(3,u);
else
y = zeros(3,1);
end

7-25
7 Code Generation for Variable-Size Data

Incompatibilities with MATLAB in Variable-Size Support for Code


Generation

In this section...
“Incompatibility with MATLAB for Scalar Expansion” on page 7-26
“Incompatibility with MATLAB in Determining Size of Variable-Size N-D Arrays” on
page 7-28
“Incompatibility with MATLAB in Determining Size of Empty Arrays” on page 7-29
“Incompatibility with MATLAB in Determining Class of Empty Arrays” on page 7-30
“Incompatibility with MATLAB in Vector-Vector Indexing” on page 7-31
“Incompatibility with MATLAB in Matrix Indexing Operations for Code Generation” on
page 7-32
“Incompatibility with MATLAB in Concatenating Variable-Size Matrices” on page
7-33
“Differences When Curly-Brace Indexing of Variable-Size Cell Array Inside
Concatenation Returns No Elements” on page 7-33
“Dynamic Memory Allocation Not Supported for MATLAB Function Blocks” on page
7-34

Incompatibility with MATLAB for Scalar Expansion


Scalar expansion is a method of converting scalar data to match the dimensions of vector
or matrix data. Except for some matrix operators, MATLAB arithmetic operators work
on corresponding elements of arrays with equal dimensions. For vectors and rectangular
arrays, both operands must be the same size unless one is a scalar. If one operand is a
scalar and the other is not, MATLAB applies the scalar to every element of the other
operand—this property is known as scalar expansion.

During code generation, the standard MATLAB scalar expansion rules apply except
when operating on two variable-size expressions. In this case, both operands must be
the same size. The generated code does not perform scalar expansion even if one of the
variable-size expressions turns out to be scalar at run time. Instead, it generates a size
mismatch error at run time for MEX functions. Run-time error checking does not occur
for non-MEX builds; the generated code will have unspecified behavior.

7-26
Incompatibilities with MATLAB in Variable-Size Support for Code Generation

For example, in the following function, z is scalar for the switch statement case 0 and
case 1. MATLAB applies scalar expansion when evaluating y(:) = z; for these two
cases.
function y = scalar_exp_test_err1(u) %#codegen
y = ones(3);
switch u
case 0
z = 0;
case 1
z = 1;
otherwise
z = zeros(3);
end
y(:) = z;

When you generate code for this function, the code generation software determines that z
is variable size with an upper bound of 3.

If you run the MEX function with u equal to zero or one, even though z is scalar at run
time, the generated code does not perform scalar expansion and a run-time error occurs.
scalar_exp_test_err1_mex(0)
Sizes mismatch: 9 ~= 1.

Error in scalar_exp_test_err1 (line 11)

7-27
7 Code Generation for Variable-Size Data

y(:) = z;

Workaround

Use indexing to force z to be a scalar value:


function y = scalar_exp_test_err1(u) %#codegen
y = ones(3);
switch u
case 0
z = 0;
case 1
z = 1;
otherwise
z = zeros(3);
end
y(:) = z(1);

Incompatibility with MATLAB in Determining Size of Variable-Size N-D


Arrays
For variable-size N-D arrays, the size function can return a different result in generated
code than in MATLAB. In generated code, size(A) returns a fixed-length output
because it does not drop trailing singleton dimensions of variable-size N-D arrays. By
contrast, size(A) in MATLAB returns a variable-length output because it drops trailing
singleton dimensions.

For example, if the shape of array A is :?x:?x:? and size(A,3)==1, size(A) returns:

• Three-element vector in generated code


• Two-element vector in MATLAB code

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:

• Use the two-argument form of size.

For example, size(A,n) returns the same answer in generated code and MATLAB
code.
• Rewrite size(A):

7-28
Incompatibilities with MATLAB in Variable-Size Support for Code Generation

B = size(A);
X = B(1:ndims(A));

This version returns X with a variable-length output. However, you cannot pass
a variable-size X to matrix constructors such as zeros that require a fixed-size
argument.

Incompatibility with MATLAB in Determining Size of Empty Arrays


The size of an empty array in generated code might be different from its size in MATLAB
source code. The size might be 1x0 or 0x1 in generated code, but 0x0 in MATLAB.
Therefore, you should not write code that relies on the specific size of empty matrices.

For example, consider the following code:


function y = foo(n) %#codegen
x = [];
i = 0;
while (i < 10)
x = [5 x];
i = i + 1;
end
if n > 0
x = [];
end
y = size(x);
end

Concatenation requires its operands to match on the size of the dimension that is not
being concatenated. In the preceding concatenation the scalar value has size 1x1 and x
has size 0x0. To support this use case, the code generation software determines the size
for x as [1 x :?]. Because there is another assignment x = [] after the concatenation,
the size of x in the generated code is 1x0 instead of 0x0.

For incompatibilities with MATLAB in determining the size of an empty array that
results from deleting elements of an array, see “Size of Empty Array That Results from
Deleting Elements of an Array” on page 2-10.

Workaround

If your application checks whether a matrix is empty, use one of these workarounds:

• Rewrite your code to use the isempty function instead of the size function.

7-29
7 Code Generation for Variable-Size Data

• Instead of using x=[] to create empty arrays, create empty arrays of a specific size
using zeros. For example:
function y = test_empty(n) %#codegen
x = zeros(1,0);
i=0;
while (i < 10)
x = [5 x];
i = i + 1;
end
if n > 0
x = zeros(1,0);
end
y=size(x);
end

Incompatibility with MATLAB in Determining Class of Empty Arrays


The class of an empty array in generated code can be different from its class in MATLAB
source code. Therefore, do not write code that relies on the class of empty matrices.

For example, consider the following code:


function y = fun(n)
x = [];
if n > 1
x = ['a' x];
end
y=class(x);
end
fun(0) returns double in MATLAB, but char in the generated code. When the
statement n > 1 is false, MATLAB does not execute x = ['a' x]. The class of x is
double, the class of the empty array. However, the code generation software considers
all execution paths. It determines that based on the statement x = ['a' x], the class of
x is char.

Workaround

Instead of using x=[] to create an empty array, create an empty array of a specific class.
For example, use blanks(0) to create an empty array of characters.
function y = fun(n)
x = blanks(0);
if n > 1

7-30
Incompatibilities with MATLAB in Variable-Size Support for Code Generation

x = ['a' x];
end
y=class(x);
end

Incompatibility with MATLAB in Vector-Vector Indexing


In vector-vector indexing, you use one vector as an index into another vector. When
either vector is variable sized, you might get a run-time error during code generation.
Consider the index expression A(B). The general rule for indexing is that size(A(B))
== size(B). However, when both A and B are vectors, MATLAB applies a special rule:
use the orientation of A as the orientation of the output. For example, if size(A) == [1
5] and size(B) == [3 1], then size(A(B)) == [1 3].

In this situation, if the code generation software 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, the
code generation software applies only the general indexing rule. Then, if both A and B
become vectors at run time, the code generation software reports a run-time error when
you run the MEX function. Run-time error checking does not occur for non-MEX builds;
the generated code will have unspecified behavior. It is best practice to generate and test
a MEX function before generating C code.

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 for vector-vector indexing:

...
if isvector(A) && isvector(B)
C = A(:);
D = C(B(:));
else
D = A(B);
end
...

The indexing in the first branch specifies that C and B(:) are compile-time vectors. As a
result, the code generation software applies the standard vector-vector indexing rule.

7-31
7 Code Generation for Variable-Size Data

Incompatibility with MATLAB in Matrix Indexing Operations for Code


Generation
The following limitation applies to matrix indexing operations for code generation:

• Initialization of the following style:

for i = 1:10
M(i) = 5;
end

In this case, the size of M changes as the loop is executed. Code generation does not
support increasing the size of an array over time.

For code generation, preallocate M as highlighted in this code.

M = zeros(1,10);
for i = 1:10
M(i) = 5;
end

The following limitation applies to matrix indexing operations for code generation when
dynamic memory allocation is disabled:

• M(i:j) where i and j change in a loop

During code generation, memory is not dynamically allocated for the size of the
expressions that change as the program executes. To implement this behavior, use
for-loops as shown:

...
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.

7-32
Incompatibilities with MATLAB in Variable-Size Support for Code Generation

Incompatibility with MATLAB in Concatenating Variable-Size Matrices


For code generation, when you concatenate variable-size arrays, the dimensions that are
not being concatenated must match exactly.

Differences When Curly-Brace Indexing of Variable-Size Cell Array Inside


Concatenation Returns No Elements
Suppose that:

• c is a variable-size cell array.


• You access the contents of c by using curly braces. For example, c{2:4}.
• You include the results in concatenation. For example, [a c{2:4} b].
• c{I} returns no elements. Either c is empty or the indexing inside the curly braces
produces an empty result.

For these conditions, MATLAB omits c{I} from the concatenation. For example, [a
c{I} b] becomes [a b]. The code generation software treats c{I} as the empty
array [c{I}]. The concatenation becomes [...[c{i}]...]. This concatenation then
omits the array [c{I}]. So that the properties of [c{I}] are compatible with the
concatenation [...[c{i}]...], the code generation software assigns the class, size,
and complexity of [c{I}] according to these rules:

• The class and complexity are the same as the base type of the cell array.
• The size of the second dimension is always 0.
• For the rest of the dimensions, the size of Ni depends on whether the corresponding
dimension in the base type is fixed or variable size.

• If the corresponding dimension in the base type is variable size, the dimension has
size 0 in the result.
• If the corresponding dimension in the base type is fixed size, the dimension has
that size in the result.

Suppose that c has a base type with class int8 and size:10x7x8x:?. In the generated
code, the class of [c{I}] is int8. The size of [c{I}] is 0x0x8x0. The second dimension
is 0. The first and last dimensions are 0 because those dimensions are variable size in the
base type. The third dimension is 8 because the size of the third dimension of the base
type is a fixed size 8.

7-33
7 Code Generation for Variable-Size Data

Inside concatenation, if curly-brace indexing of a variable-size cell array returns no


elements, the generated code can have the following differences from MATLAB:

• The class of [...c{i}...] in the generated code can differ from the class in
MATLAB.

When c{I} returns no elements, MATLAB removes c{I} from the concatenation.
Therefore, c{I} does not affect the class of the result. MATLAB determines the class
of the result based on the classes of the remaining arrays, according to a precedence
of classes. See “Valid Combinations of Unlike Classes”. In the generated code, the
class of [c{I}] affects the class of the result of the overall concatenation [...
[c{I}]...] because the code generation software treats c{I} as [c{I}]. The
previously described rules determine the class of [c{I}].
• In the generated code, the size of [c{I}] can differ from the size in MATLAB.

In MATLAB, the concatenation [c{I}] is a 0x0 double. In the generated code, the
previously described rules determine the size of [c{I}].

Dynamic Memory Allocation Not Supported for MATLAB Function Blocks


You cannot use dynamic memory allocation for variable-size data in MATLAB Function
blocks. Use bounded instead of unbounded variable-size data.

7-34
Variable-Sizing Restrictions for Code Generation of Toolbox Functions

Variable-Sizing Restrictions for Code Generation of Toolbox


Functions
In this section...
“Common Restrictions” on page 7-35
“Toolbox Functions with Restrictions For Variable-Size Data” on page 7-36

Common Restrictions
The following common restrictions apply to multiple toolbox functions, but only for code
generation. To determine which of these restrictions apply to specific library functions,
see the table in “Toolbox Functions with Restrictions For Variable-Size Data” on page
7-36.

Variable-length vector restriction


Inputs to the library function must be variable-length vectors or fixed-size vectors.
A variable-length vector is a variable-size array that has the shape 1x:n or :nx1
(one dimension is variable sized and the other is fixed at size 1). Other shapes are not
permitted, even if they are vectors at run time.

Automatic dimension restriction


When the function selects the working dimension automatically, it bases the selection
on the upper bounds for the dimension sizes. In the case of the sum function, sum(X)
selects its working dimension automatically, while sum(X, dim) uses dim as the explicit
working dimension.

For example, if X is a variable-size matrix with dimensions 1x:3x:5, sum(x) behaves


like sum(X,2) in generated code. In MATLAB, it behaves like sum(X,2) provided
size(X,2) is not 1. In MATLAB, when size(X,2) is 1, sum(X) behaves like
sum(X,3). Consequently, you get a run-time error if an automatically selected working
dimension assumes a length of 1 at run time.

To avoid the issue, specify the intended working dimension explicitly as a constant value.

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.

7-35
7 Code Generation for Variable-Size Data

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 scalars as fixed size.

Toolbox Functions with Restrictions For Variable-Size Data


The following table list functions that have code generation restrictions for variable-size
data. For additional restrictions for these functions, and restrictions for all functions and
objects supported for code generation, see “Functions and Objects Supported for C and C+
+ Code Generation — Alphabetical List” on page 4-2.

Function Restrictions for Variable-Size Data


all • See “Automatic dimension restriction” on page 7-35.
• An error occurs if you pass the first argument a
variable-size matrix that is 0-by-0 at run time.
any • See “Automatic dimension restriction” on page 7-35.
• An error occurs if you pass the first argument a
variable-size matrix that is 0-by-0 at run time.
bsxfun • Dimensions expand only where one input array or the
other has a fixed length of 1.
cat • Dimension argument must be a constant.
• An error occurs if variable-size inputs are empty at run
time.
conv • See “Variable-length vector restriction” on page
7-35.
• Input vectors must have the same orientation, either
both row vectors or both column vectors.
cov • For cov(X), see “Array-to-vector restriction” on page
7-35.
cross • Variable-size array inputs that become vectors at run
time must have the same orientation.
deconv • For both arguments, see “Variable-length vector
restriction” on page 7-35.

7-36
Variable-Sizing Restrictions for Code Generation of Toolbox Functions

Function Restrictions for Variable-Size Data


detrend • For first argument for row vectors only, see “Array-to-
vector restriction” on page 7-35 .
diag • See “Array-to-vector restriction” on page 7-35 .
diff • See “Automatic dimension restriction” on page 7-35.
• Length of the working dimension must be greater than
the difference order input when the input is variable
sized. For example, if the input is a variable-size matrix
that is 3-by-5 at run time, diff(x,2,1) works but
diff(x,5,1) generates a run-time error.
fft • See “Automatic dimension restriction” on page 7-35.
filter • For first and second arguments, see “Variable-length
vector restriction” on page 7-35.
• See “Automatic dimension restriction” on page 7-35.
hist • For second argument, see “Variable-length vector
restriction” on page 7-35.
• For second input argument, see “Array-to-scalar
restriction” on page 7-36.
histc • See “Automatic dimension restriction” on page 7-35.
ifft • See “Automatic dimension restriction” on page 7-35.
ind2sub • First input (the size vector input) must be fixed size.
interp1 • For the xq input, see “Array-to-vector restriction” on
page 7-35.
• If v becomes a row vector at run time, the array to
vector restriction applies. If v becomes a column vector
at run time, this restriction does not apply.
ipermute • Order input must be fixed size.
issorted • For optional rows input, see “Variable-length vector
restriction” on page 7-35.
magic • Argument must be a constant.
• Output can be fixed-size matrices only.
max • See “Automatic dimension restriction” on page 7-35.

7-37
7 Code Generation for Variable-Size Data

Function Restrictions for Variable-Size Data


mean • See “Automatic dimension restriction” on page 7-35.
• An error occurs if you pass as the first argument a
variable-size matrix that is 0-by-0 at run time.
median • See “Automatic dimension restriction” on page 7-35.
• An error occurs if you pass as the first argument a
variable-size matrix that is 0-by-0 at run time.
min • See “Automatic dimension restriction” on page 7-35.
mode • See “Automatic dimension restriction” on page 7-35.
• An error occurs if you pass as the first argument a
variable-size matrix that is 0-by-0 at run time.
mtimes • When an input is variable-size, MATLAB determines
whether to generate code for a general matrix*matrix
multiplication or a scalar*matrix multiplication, based
on whether one of the arguments is a fixed-size scalar.
If neither argument is a fixed-size scalar, the inner
dimensions of the two arguments must agree even if a
variable-size matrix input is a scalar at run time.
nchoosek • The second input, k, must be a fixed-size scalar.
• The second input, k, must be a constant for static
allocation. If you enable dynamic allocation, the second
input can be a variable.
• You cannot create a variable-size array by passing in a
variable, k, unless you enable dynamic allocation.
permute • Order input must be fixed-size.
planerot • Input must be a fixed-size, two-element column vector.
It cannot be a variable-size array that takes on the size
2-by-1 at run time.
poly • See “Variable-length vector restriction” on page
7-35.
polyfit • For first and second arguments, see “Variable-length
vector restriction” on page 7-35.

7-38
Variable-Sizing Restrictions for Code Generation of Toolbox Functions

Function Restrictions for Variable-Size Data


prod • See “Automatic dimension restriction” on page 7-35.
• An error occurs if you pass as the first argument a
variable-size matrix that is 0-by-0 at run time.
rand • For an upper-bounded variable N, rand(1,N) produces
a variable-length vector of 1x:M where M is the upper
bound on N.
• For an upper-bounded variable N, rand([1 N]) may
produce a variable-length vector of :1x:M where M is the
upper bound on N.
randi • For an upper-bounded variable N, randi(imax,1,N)
produces a variable-length vector of 1x:M where M is the
upper bound on N.
• For an upper-bounded variable N, randi(imax,[1 N])
may produce a variable-length vector of :1x:M where M
is the upper bound on N.
randn • For an upper-bounded variable N, randn(1,N) produces
a variable-length vector of 1x:M where M is the upper
bound on N.
• For an upper-bounded variable N, randn([1 N]) may
produce a variable-length vector of :1x:M where M is the
upper bound on N.
reshape • If the input is a variable-size array and the output
array has at least one fixed-length dimension, do not
specify the output dimension sizes in a size vector sz.
Instead, specify the output dimension sizes as scalar
values, sz1,...,szN. Specify fixed-size dimensions as
constants.
• When the input is a variable-size empty array, the
maximum dimension size of the output array (also
empty) cannot be larger than that of the input.
roots • See “Variable-length vector restriction” on page
7-35.

7-39
7 Code Generation for Variable-Size Data

Function Restrictions for Variable-Size Data


shiftdim • If you do not supply the second argument, the number
of shifts is determined at compilation time by the upper
bounds of the dimension sizes. Consequently, at run
time the number of shifts is constant.
• An error occurs if the dimension that is shifted to the
first dimension has length 1 at run time. To avoid the
error, supply the number of shifts as the second input
argument (must be a constant).
• First input argument must have the same number of
dimensions when you supply a positive number of shifts.
std • See “Automatic dimension restriction” on page 7-35.
• An error occurs if you pass a variable-size matrix with
0-by-0 dimensions at run time.
sub2ind • First input (the size vector input) must be fixed size.
sum • See “Automatic dimension restriction” on page 7-35.
• An error occurs if you pass as the first argument a
variable-size matrix that is 0-by-0 at run time.
trapz • See “Automatic dimension restriction” on page 7-35.
• An error occurs if you pass as the first argument a
variable-size matrix that is 0-by-0 at run time.
typecast • See “Variable-length vector restriction” on page 7-35
on first argument.
var • See “Automatic dimension restriction” on page 7-35.
• An error occurs if you pass a variable-size matrix with
0-by-0 dimensions at run time.

7-40
8

Code Generation for MATLAB


Structures

• “Structure Definition for Code Generation” on page 8-2


• “Structure Operations Allowed for Code Generation” on page 8-3
• “Define Scalar Structures for Code Generation” on page 8-4
• “Define Arrays of Structures for Code Generation” on page 8-6
• “Make Structures Persistent” on page 8-8
• “Index Substructures and Fields” on page 8-9
• “Assign Values to Structures and Fields” on page 8-11
• “Pass Structure Arguments by Reference or by Value” on page 8-13
8 Code Generation for MATLAB Structures

Structure Definition for Code Generation


To generate efficient standalone code for structures, you must define and use structures
differently than you normally would when running your code in the MATLAB
environment:

What's Different More Information


Use a restricted set of operations. “Structure Operations Allowed for Code
Generation” on page 8-3
Observe restrictions on properties and “Define Scalar Structures for Code
values of scalar structures. Generation” on page 8-4
Make structures uniform in arrays. “Define Arrays of Structures for Code
Generation” on page 8-6
Reference structure fields individually “Index Substructures and Fields” on page
during indexing. 8-9
Avoid type mismatch when assigning “Assign Values to Structures and Fields” on
values to structures and fields. page 8-11

8-2
Structure Operations Allowed for Code Generation

Structure Operations Allowed for Code Generation


To generate efficient standalone code for MATLAB structures, you are restricted to the
following operations:

• Define structures as local and persistent variables by assignment and using the
struct function
• Index structure fields using dot notation
• Define primary function inputs as structures
• Pass structures to local functions

8-3
8 Code Generation for MATLAB Structures

Define Scalar Structures for Code Generation


In this section...
“Restrictions When Defining Scalar Structures by Assignment” on page 8-4
“Adding Fields in Consistent Order on Each Control Flow Path” on page 8-4
“Restriction on Adding New Fields After First Use” on page 8-5

Restrictions When Defining Scalar Structures by Assignment


When you define a scalar structure by assigning a variable to a preexisting structure,
you do not need to define the variable before the assignment. However, if you already
defined that variable, it must have the same class, size, and complexity as the structure
you assign to it. In the following example, p is defined as a structure that has the same
properties as the predefined structure S:

...
S = struct('a', 0, 'b', 1, 'c', 2);
p = S;
...

Adding Fields in Consistent Order on Each Control Flow Path


When you create a structure, you must add fields in the same order on each control flow
path. For example, the following code generates a compiler error because it adds the
fields of structure x in a different order in each if statement clause:

function y = fcn(u) %#codegen


if u > 0
x.a = 10;
x.b = 20;
else
x.b = 30; % Generates an error (on variable x)
x.a = 40;
end
y = x.a + x.b;

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:

8-4
Define Scalar Structures for Code Generation

function y = fcn(u) %#codegen


if u > 0
x.a = 10;
x.b = 20;
else
x.a = 40;
x.b = 30;
end
y = x.a + x.b;

Restriction on Adding New Fields After First Use


You cannot add fields to a structure after you perform the following operations on the
structure:

• Reading from the structure


• Indexing into the structure array
• Passing the structure to a function

For example, consider this code:


...
x.c = 10; % Defines structure and creates field c
y = x; % Reads from structure
x.d = 20; % Generates an error
...

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:
function y = fcn(u) %#codegen

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.

8-5
8 Code Generation for MATLAB Structures

Define Arrays of Structures for Code Generation


In this section...
“Ensuring Consistency of Fields” on page 8-6
“Using repmat to Define an Array of Structures with Consistent Field Properties” on
page 8-6
“Defining an Array of Structures by Using struct” on page 8-7
“Defining an Array of Structures Using Concatenation” on page 8-7

Ensuring Consistency of Fields


For code generation, when you create an array of MATLAB structures, corresponding
fields in the array elements must have the same size, type, and complexity.

Once you have created the array of structures, you can make the structure fields
variable-size using coder.varsize. For more information, see “Declare a Variable-Size
Structure Field.”.

Using repmat to Define an Array of Structures with Consistent Field


Properties
You can create an array of structures from a scalar structure by using the MATLAB
repmat function, which replicates and tiles an existing scalar structure:

1 Create a scalar structure, as described in “Define Scalar Structures for Code


Generation” on page 8-4.
2 Call repmat, passing the scalar structure and the dimensions of the array.
3 Assign values to each structure using standard array indexing and structure dot
notation.

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);

8-6
Define Arrays of Structures for Code Generation

X(1).a = 1;
X(2).a = 2;
X(3).a = 3;
X(1).b = 4;
X(2).b = 5;
X(3).b = 6;
...

Defining an Array of Structures by Using struct


To create an array of structures using the struct function, specify the field value
arguments as cell arrays. Each cell array element is the value of the field in the
corresponding structure array element. For code generation, corresponding fields in
the structures must have the same type. Therefore, the elements in a cell array of field
values must have the same type.

For example, the following code creates a 1-by-3 structure array. For each structure in
the array of structures, a has type double and b has type char.

s = struct('a', {1 2 3}, 'b', {'a' 'b' 'c'});

Defining an Array of Structures Using Concatenation


To create a small array of structures, you can use the concatenation operator, square
brackets ( [ ] ), to join one or more structures into an array (see “Concatenating
Matrices”). For code generation, the structures that you concatenate must have the same
size, class, and complexity.

For example, the following code uses concatenation and a local function to create the
elements of a 1-by-3 structure array:
...
W = [ sab(1,2) sab(2,3) sab(4,5) ];

function s = sab(a,b)
s.a = a;
s.b = b;
...

8-7
8 Code Generation for MATLAB Structures

Make Structures Persistent


To make structures persist, you define them to be persistent variables and initialize
them with the isempty statement, as described in “Define and Initialize Persistent
Variables” on page 5-10.

For example, the following function defines structure X to be persistent and initializes its
fields a and b:

function f(u) %#codegen


persistent X

if isempty(X)
X.a = 1;
X.b = 2;
end

8-8
Index Substructures and Fields

Index Substructures and Fields


Use these guidelines when indexing substructures and fields for code generation:

Reference substructure field values individually using dot notation

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);
...

The generated code indexes elements of the structures in this example by resolving
symbols as follows:

Dot Notation Symbol Resolution


substruct1.a1 Field a1 of local structure substruct1
substruct2.ele3.a1 Value of field a1 of field ele3, a substructure of local structure
substruct2
substruct2.ele3.a2(1,1) Value in row 1, column 1 of field a2 of field ele3, a substructure
of local structure substruct2

Reference field values individually in structure arrays

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:

...
y = X(1).a % Extracts the value of field a
% of the first structure in array X
...

8-9
8 Code Generation for MATLAB Structures

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 “Define Arrays of Structures for Code Generation” on
page 8-6 for more information.

Do not reference fields dynamically

You cannot reference fields in a structure by using dynamic names, which express the
field as a variable expression that MATLAB evaluates at run time (see “Generate Field
Names from Variables”).

8-10
Assign Values to Structures and Fields

Assign Values to Structures and Fields


When assigning values to a structure, substructure, or field for code generation, use
these guidelines:

Field properties must be consistent across structure-to-structure assignments

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 substructure Define the structure with the same
of a different structure and vice versa. number, type, and size of fields as the
substructure.
Assigning an element of one structure to an The elements must have the same type and
element of another structure. size.

For structures with constant fields, do not assign field values inside control flow constructs

In the following code, the code generation software recognizes that the structure fields
s.a and s.b are constants.

function y = mystruct()
s.a = 3;
s.b = 5;
y = zeros(s.a,s.b);

If a field of a structure is assigned inside a control flow construct, the code generation
software does not recognize that s.a and s.b are constant. Consider the following code:

function y = mystruct(x)
s.a = 3;
if x > 1
s.b = 4;
else
s.b = 5;
end
y = zeros(s.a,s.b);

If variable-sizing is enabled, y is treated as a variable-size array. If variable-sizing is


disabled, y, the code generation software reports an error.

8-11
8 Code Generation for MATLAB Structures

Do not assign mxArrays to structures

You cannot assign mxArrays to structure elements; convert mxArrays to known types
before code generation (see “Working with mxArrays” on page 14-17).

Do not assign classes to structure fields

You cannot assign classes to structure fields.

Do not assign cell arrays to structure fields

You cannot assign cell arrays to structure fields.

8-12
Pass Structure Arguments by Reference or by Value

Pass Structure Arguments by Reference or by Value


This example shows how to control whether structure arguments to entry-point functions
are passed by reference or by value.

Passing by reference uses a pointer to access the structure arguments. If the function
writes to an element of the input structure, it overwrites the input value. Passing by
value makes a copy of the input or output structure argument. To reduce memory usage
and execution time, use pass by reference.

If a structure argument is both an input and output, the generated entry-point function
passes the argument by reference. Generated MEX functions pass structure arguments
by reference. For MEX function output, you cannot specify that you want to pass
structure arguments by value.

Specify Pass by Reference or by Value Using the MATLAB Coder App

To open the Generate dialog box, on the Generate Code page, click the Generate
arrow.

Set the Build type to one of the following:

• Source Code
• Static Library
• Dynamic Library
• Executable

Click More Settings.

On the All Settings tab, set the Pass structures by reference to entry-point
functions option to:

• Yes, for pass by reference (default)


• No, for pass by value

Specify Pass by Reference or by Value Using the Command-Line Interface

Create a code configuration object for 'lib', 'dll', or 'exe'.


cfg = coder.config('lib'); % or 'dll', or 'exe'

Set the PassStructByReference property to:

8-13
8 Code Generation for MATLAB Structures

• true, for pass by reference (default)


• false, for pass by value

For example:
cfg.PassStructByReference = true;

Set Up Example Files

To create a folder and get copies of the example files, click Open This Example.

Pass Input Structure Argument by Reference

View the function my_struct_in that has an input structure argument.


type my_struct_in.m

function y = my_struct_in(s)
%#codegen

y = s.f;

Define a structure variable str in the MATLAB® workspace.


str = struct('f', 1:4);

Create a code generation configuration object for a C static library.


cfg = coder.config('lib');

Specify that you want to pass structure arguments by reference.


cfg.PassStructByReference = true;

Generate code. Specify that the input argument has the type of the variable str.
codegen -config cfg -args {str} my_struct_in

View the generated C code.


type codegen/lib/my_struct_in/my_struct_in.c

/*
* File: my_struct_in.c
*

8-14
Pass Structure Arguments by Reference or by Value

* MATLAB Coder version : 3.1


* C/C++ source code generated on : 15-Feb-2016 15:08:58
*/

/* Include Files */
#include "rt_nonfinite.h"
#include "my_struct_in.h"

/* Function Definitions */

/*
* Arguments : const struct0_T *s
* double y[4]
* Return Type : void
*/
void my_struct_in(const struct0_T *s, double y[4])
{
int i0;
for (i0 = 0; i0 < 4; i0++) {
y[i0] = s->f[i0];
}
}

/*
* File trailer for my_struct_in.c
*
* [EOF]
*/

The generated function signature for my_struct_in is


void my_struct_in(const struct0_T *s, double y[4])

my_struct_in passes the input structure s by reference.

Pass Input Structure Argument by Value

Specify that you want to pass structure arguments by value.


cfg.PassStructByReference = false;

Generate code. Specify that the input argument has the type of the variable str.
codegen -config cfg -args {str} my_struct_in

View the generated C code.

8-15
8 Code Generation for MATLAB Structures

type codegen/lib/my_struct_in/my_struct_in.c

/*
* File: my_struct_in.c
*
* MATLAB Coder version : 3.1
* C/C++ source code generated on : 15-Feb-2016 15:09:09
*/

/* Include Files */
#include "rt_nonfinite.h"
#include "my_struct_in.h"

/* Function Definitions */

/*
* Arguments : const struct0_T s
* double y[4]
* Return Type : void
*/
void my_struct_in(const struct0_T s, double y[4])
{
int i0;
for (i0 = 0; i0 < 4; i0++) {
y[i0] = s.f[i0];
}
}

/*
* File trailer for my_struct_in.c
*
* [EOF]
*/

The generated function signature for my_struct_in is


void my_struct_in(const struct0_T s, double y[4]

my_struct_in passes the input structure s by value.

Pass Output Structure Argument by Reference

View the function my_struct_out that has an output structure argument.


type my_struct_out.m

8-16
Pass Structure Arguments by Reference or by Value

function s = my_struct_out(x)
%#codegen

s.f = x;

Define a variable a in the MATLAB® workspace.

a = 1:4;

Create a code generation configuration object for a C static library.

cfg = coder.config('lib');

Specify that you want to pass structure arguments by reference.

cfg.PassStructByReference = true;

Generate code. Specify that the input argument has the type of the variable a.

codegen -config cfg -args {a} my_struct_out

View the generated C code.

type codegen/lib/my_struct_out/my_struct_out.c

/*
* File: my_struct_out.c
*
* MATLAB Coder version : 3.1
* C/C++ source code generated on : 15-Feb-2016 15:09:13
*/

/* Include Files */
#include "rt_nonfinite.h"
#include "my_struct_out.h"

/* Function Definitions */

/*
* Arguments : const double x[4]
* struct0_T *s
* Return Type : void

8-17
8 Code Generation for MATLAB Structures

*/
void my_struct_out(const double x[4], struct0_T *s)
{
int i0;
for (i0 = 0; i0 < 4; i0++) {
s->f[i0] = x[i0];
}
}

/*
* File trailer for my_struct_out.c
*
* [EOF]
*/

The generated function signature for my_struct_out is

void my_struct_out(const double x[4], struct0_T *s)

my_struct_out passes the output structure s by reference.

Pass Output Structure Argument by Value

Specify that you want to pass structure arguments by value.

cfg.PassStructByReference = false;

Generate code. Specify that the input argument has the type of the variable a.

codegen -config cfg -args {a} my_struct_out

View the generated C code.

type codegen/lib/my_struct_out/my_struct_out.c

/*
* File: my_struct_out.c
*
* MATLAB Coder version : 3.1
* C/C++ source code generated on : 15-Feb-2016 15:09:17
*/

/* Include Files */
#include "rt_nonfinite.h"

8-18
Pass Structure Arguments by Reference or by Value

#include "my_struct_out.h"

/* Function Definitions */

/*
* Arguments : const double x[4]
* Return Type : struct0_T
*/
struct0_T my_struct_out(const double x[4])
{
struct0_T s;
int i0;
for (i0 = 0; i0 < 4; i0++) {
s.f[i0] = x[i0];
}

return s;
}

/*
* File trailer for my_struct_out.c
*
* [EOF]
*/

The generated function signature for my_struct_out is


struct0_T my_struct_out(const double x[4])

my_struct_out returns an output structure.

Pass Input and Output Structure Argument by Reference

When an argument is both an input and an output, the generated C function passes the
argument by reference even when PassStructByReference is false.

View the function my_struct_inout that has a structure argument that is both an
input and an output.
type my_struct_inout.m

function [y,s] = my_struct_inout(x,s)


%#codegen

8-19
8 Code Generation for MATLAB Structures

y = x + sum(s.f);

Define the variable a and structure variable str in the MATLAB® workspace.

a = 1:4;
str = struct('f',a);

Create a code generation configuration object for a C static library.

cfg = coder.config('lib');

Specify that you want to pass structure arguments by value.

cfg.PassStructByReference = false;

Generate code. Specify that the first input has the type of a and the second input has the
type of str.

codegen -config cfg -args {a, str} my_struct_inout

View the generated C code.

type codegen/lib/my_struct_inout/my_struct_inout.c

/*
* File: my_struct_inout.c
*
* MATLAB Coder version : 3.1
* C/C++ source code generated on : 15-Feb-2016 15:09:20
*/

/* Include Files */
#include "rt_nonfinite.h"
#include "my_struct_inout.h"

/* Function Definitions */

/*
* Arguments : const double x[4]
* const struct0_T *s
* double y[4]
* Return Type : void
*/

8-20
Pass Structure Arguments by Reference or by Value

void my_struct_inout(const double x[4], const struct0_T *s, double y[4])


{
double b_y;
int k;
b_y = s->f[0];
for (k = 0; k < 3; k++) {
b_y += s->f[k + 1];
}

for (k = 0; k < 4; k++) {


y[k] = x[k] + b_y;
}
}

/*
* File trailer for my_struct_inout.c
*
* [EOF]
*/

The generated function signature for my_struct_inout is

void my_struct_inout(const double x[4], const struct0_T *s, double y[4])

my_struct_inout passes the structure s by reference even though


PassStructByReference is false.

8-21
9

Code Generation for Cell Arrays

• “Homogeneous vs. Heterogeneous Cell Arrays” on page 9-2


• “Control Whether a Cell Array is Homogeneous or Heterogeneous” on page 9-4
• “Define Cell Array Inputs” on page 9-5
• “Make a Cell Array Variable-Size” on page 9-6
• “Name the Structure Type That Represents a Cell Array” on page 9-8
• “Cell Array Requirements and Limitations for Code Generation” on page 9-10
• “Cell Arrays in Code Generation Reports” on page 9-14
9 Code Generation for Cell Arrays

Homogeneous vs. Heterogeneous Cell Arrays


The code generation software classifies a cell array as homogeneous or heterogeneous.
This classification determines how a cell array is represented in the generated C/C++
code. It also determines how you can use the cell array in MATLAB code from which you
generate C/C++ code.

A homogeneous cell array has the following characteristics:

• The cell array is represented as a C array in the generated code.


• All elements have the same properties. The type associated with the cell array
specifies the properties of all elements rather than the properties of individual
elements.
• The cell array can be variable size.
• You can index into the cell array using an index whose value is determined at run
time.

A heterogeneous cell array has the following characteristics:

• The cell array is represented as a C structure in the generated code. Each element is
represented as a field of the structure.
• The elements can have different properties. The type associated with the cell array
specifies the properties of each element individually.
• The cell array cannot be variable size.
• You must index into the cell array using a constant index or using for-loops with
constant bounds.

The code generation software uses heuristics to determine the classification of a


cell array as homogeneous or heterogeneous. It considers the properties (class, size,
complexity) of the elements and other factors such as how you use the cell array in your
program. A particular cell array can be homogeneous in one case and heterogeneous in
another case. For example, consider the cell array {1 [2 3]}. This cell array can be
a heterogeneous 1x2 cell array whose first element is double scalar and whose second
element is a 1x2 array of doubles. However, if you index into this cell array with an index
whose value is determined at run time, the cell array is a homogeneous cell array. The
elements are variable-size arrays of doubles with an upper bound of 2.

To see whether a cell array is homogeneous or heterogeneous, view the variable in the
code generation report. See “Cell Arrays in Code Generation Reports” on page 9-14.

9-2
Homogeneous vs. Heterogeneous Cell Arrays

For more information, see “Control Whether a Cell Array is Homogeneous or


Heterogeneous” on page 9-4.

More About
• “Cell Array Requirements and Limitations for Code Generation” on page 9-10

9-3
9 Code Generation for Cell Arrays

Control Whether a Cell Array is Homogeneous or Heterogeneous


As long as you do not specify conflicting requirements, you can control whether a cell
array is homogeneous or heterogeneous.

If a cell array is an entry-point function input:

• At the command line, use the coder.typeof function or the coder.newtype


function to create a coder.CellType object. To create homogeneous or
heterogeneous cell array types, use coder.CellType methods.
• In the MATLAB Coder app, select Homogeneous cell array or Heterogeneous
cell array as the type of the input.

If a cell array is not an entry-point function input:

• If you use coder.varsize with the cell array, the cell array is homogeneous.
• If you index the cell array with an index whose value is determined at run time, the
cell array is homogeneous.
• If you use coder.cstructname with the cell array, the cell array is heterogeneous.
• If the elements have different classes, the cell array is heterogeneous.

If the code generation software detects conflicting requirements for a cell array, the code
generation fails. For example, you cannot use coder.varsize with a cell array whose
elements have different classes.

See Also
coder.CellType | coder.cstructname | coder.varsize

Related Examples
• “Define Cell Array Inputs” on page 9-5
• “Make a Cell Array Variable-Size” on page 9-6
• “Name the Structure Type That Represents a Cell Array” on page 9-8

More About
• “Homogeneous vs. Heterogeneous Cell Arrays” on page 9-2

9-4
Define Cell Array Inputs

Define Cell Array Inputs


To define entry-point cell array inputs See
At the command line “Specify Cell Array Inputs at the Command
Line” on page 21-55
Programmatically in the MATLAB file “Define Input Properties Programmatically
in the MATLAB File” on page 21-66
Using the MATLAB Coder app “Automatically Define Input Types Using
the App” on page 18-4

“Define Input Parameters by Example


Using the App” on page 18-5

“Define or Edit Input Parameter Type


Using the App” on page 18-12

9-5
9 Code Generation for Cell Arrays

Make a Cell Array Variable-Size


This example shows how to specify that a cell array that is not an entry-point input is
variable size. To specify a variable-size cell array input, see “Define Cell Array Inputs” on
page 9-5.

Define a function mycellfun that defines the cell array c.


function y = mycellfun()
c = {1, [2 3]};
y = c;
end

Generate code for mycellfun. For example, generate a static library.


codegen -config:lib mycellfun -report

To see whether the code generation software classifies c as homogeneous or


heterogeneous:

1 Click the View report link.


2 Click the MATLAB code tab. Under Functions, click mycellfun.
3 On the Variables tab, expand the information for c. The report specifies the
properties for c{1} and c{2} individually, indicating that c is heterogeneous.

To specify that c is variable size with an upper bound of 10 for the second dimension, add
the coder.varsize call.
function y = mycellfun()

9-6
Make a Cell Array Variable-Size

c = {1, [2 3]};
coder.varsize('c', [1 10]);
y = c;
end

Generate the code again.

View c in the report. c is a variable-size cell array with an upper bound of 10. The report
indicates that c is homogeneous by using the notation {:}. This notation indicates that
all elements of the cell array have the same properties. To make c homogeneous, the code
generation software uses a size 1x:2 that can apply to all of the elements.

See Also
coder.varsize

Related Examples
• “Name the Structure Type That Represents a Cell Array” on page 9-8

More About
• “Homogeneous vs. Heterogeneous Cell Arrays” on page 9-2
• “Cell Arrays in Code Generation Reports” on page 9-14
• “Cell Array Requirements and Limitations for Code Generation” on page 9-10

9-7
9 Code Generation for Cell Arrays

Name the Structure Type That Represents a Cell Array


This example shows how to name the structure type that represents a cell array in the
generated code. If a cell array is an entry-point function input, to name the structure that
represents the cell array, see coder.cstructname and “Define Cell Array Inputs” on
page 9-5.

Define a function mycellfun that defines the cell array c. To name the structure type
that represents c in the generated code, use coder.cstructname.

function y = mycellfun()
c = {1, [2 3]};
coder.cstructname(c, 'myname');
y = c;
end

Generate a static library for mycellfun.

codegen -config:lib mycellfun -report

To see the types that the code generation software specified for c:

1 Click the View report link.


2 Click the MATLAB code tab. Under Functions, click mycellfun.
3 On the Variables tab, expand the information for c, c is a 1x2 heterogeneous cell
array.

To see the types generated for c in the C code:

1 On the C code tab, under Target Source Files, click mycellfun.c.


2 Under Target Source Files, click mycellfun_types.h.

9-8
Name the Structure Type That Represents a Cell Array

The definition for structure type myname is:

typedef struct {
double f1;
double f2[2];
} myname;

See Also
coder.cstructname

Related Examples
• “Make a Cell Array Variable-Size” on page 9-6

More About
• “Homogeneous vs. Heterogeneous Cell Arrays” on page 9-2

9-9
9 Code Generation for Cell Arrays

Cell Array Requirements and Limitations for Code Generation

Cell Array Definition


• You must completely assign cell arrays at compile time. You must assign each cell
array element on all execution paths.

If you use cell to create a cell array, you must assign values to all elements of the
cell array. The following code is not allowed because y{2} is not assigned.

function y = foo()
y = cell(1,3);
y{1} = 1;
y{3} = 3;
end

Even if the element is not used, you must assign a value so that the code generation
software can determine whether the cell array is homogeneous or heterogeneous.
Assign a value that is consistent with how you plan to use the cell array.

In the preceding example, if y{2} is double, y is homogeneous. If y{2} is empty, its


size is 0x0 not 1x1 like the other elements. In this case, y is heterogeneous.
• The assignment must be consistent on all execution paths. The following code is not
allowed because y{2} is double on one execution path and char on the other execution
path.

function y = foo(n)
y = cell(1,3)
if n > 1;
y{1} = 1
y{2} = 2;
y{3} = 3;
else
y{1} = 10;
y{2} = 'a';
y{3} = 30;
end

9-10
Cell Array Requirements and Limitations for Code Generation

Cell Array Indexing


• You cannot index cell arrays by using smooth parentheses(). Instead, consider
indexing cell arrays by using curly braces{} to access the contents of the cell.
• You must index into heterogeneous cell arrays by using constant indexes or by using
for-loops with constant bounds.

For example, the following code is not allowed:


x = {1, 'mystring'};
disp(x{randi});

If the index A and B are constant, the following code is allowed:


x = {1, 'mystring'};
for i = A:B
disp(x{i});
end

When the for-loop has constant bounds, it is unrolled. For large cell arrays, the
unrolling can increase compile time and generate inefficient code.

Growing a Cell Array by Using {end + 1}


To grow a cell array X, you can use X{end + 1}. For example:
X = {1 2};
X{end + 1} = 'a';

When you use {end + 1} to grow a cell array, follow these restrictions:

• Use only {end + 1}. Do not use {end + 2}, {end + 3}, and so on.
• Use {end + 1} with compile-time vectors only. For example, the following code is not
allowed because X is a matrix, not a vector:
X = {1 2; 3 4};
X{end + 1} = 5;
• Use {end + 1} only with a variable. In the following code, {end + 1} does not
cause {1 2 3} to grow. In this case, the code generation software treats {end + 1}
as an out-of-bounds index into X{2}.
X = {'a' { 1 2 3 }};

9-11
9 Code Generation for Cell Arrays

X{2}{end + 1} = 4;
• When {end + 1} grows a cell array in a loop, the cell array must be variable-size.
Therefore, the cell array must be homogeneous.

This code is allowed because X is homogeneous.

X = {1 2};
for i=1:n
X{end + 1} = 3;
end

This code is not allowed because X is heterogeneous.

X = {1 'a' 2 'b'};
for i=1:n
X{end + 1} = 3;
end

Variable-Size Cell Arrays


• Heterogeneous cell arrays cannot be variable-size. See “Make a Cell Array Variable-
Size” on page 9-6.
• You cannot use the cell function to create a variable-size cell array. Consider the
following code:

function y = foo(n)
y = cell(1,n);
...
If n is a compile-time constant, this code is allowed because y has a fixed size.
However, if the value of n is not known at compile time, this code is not allowed
because y has a variable size. Instead, use repmat. For example:

function y = foo(n)
y = repmat({1}, [1 n]);
...
• You cannot use the cell function with coder.varsize to make a variable-size cell
array. For example, the following code is not allowed:

function y = foo()
coder.varsize('y')
y = cell(1,2);
...

9-12
Cell Array Requirements and Limitations for Code Generation

Cell Array Contents


Cell arrays cannot contain mxarrays. In a cell array, you cannot store a value that an
extrinsic function returns.

Cell Arrays in Structures


Structures cannot contain cell arrays.

Passing to External C/C++ Functions


You cannot pass a cell array to coder.ceval. If a variable is an input argument to
coder.ceval, define the variable as an array or structure instead of as a cell array.

More About
• “Differences in Behavior After Compiling MATLAB Code” on page 2-8

9-13
9 Code Generation for Cell Arrays

Cell Arrays in Code Generation Reports

Cell Array Variable in the MATLAB Code Pane


When you place your cursor over a cell array variable in the MATLAB code pane, the
report shows that the variable has class cell.

If the cell array has all constant elements, or some constant and some nonconstant
elements, the variable name is orange. When you place your cursor over the variable, the
report shows the values of the elements. The report displays a nonconstant element as an
empty array. If you export the cell array variable to the base workspace, a nonconstant
element is an empty array in the base workspace. See “MATLAB Code Variables in a
Report” on page 22-18.

Cell Array Variable on the Variables Tab


On the Variables tab, for a cell array, the report shows class cell. By default, the
report collapses the list of cell array elements. To see the properties of the elements,
expand the list.

For a homogeneous cell array, the report has one entry that specifies the properties of all
elements. The notation {:} indicates that all elements of the cell array have the same
properties.

9-14
Cell Arrays in Code Generation Reports

For a heterogeneous cell array, the report has an entry for each element. For example, for
a heterogeneous cell array c with two elements, the entry for c{1} shows the properties
for the first element. The entry for c{2} shows the properties for the second element.

More About
• “Homogeneous vs. Heterogeneous Cell Arrays” on page 9-2
• “Code Generation Reports” on page 22-10

9-15
10

Code Generation for Enumerated


Data

• “Enumerated Data Definition for Code Generation” on page 10-2


• “Enumerated Types Supported for Code Generation” on page 10-3
• “When to Use Enumerated Data for Code Generation” on page 10-6
• “Generate Code for Enumerated Data from MATLAB Algorithms” on page 10-7
• “Define Enumerated Data for Code Generation” on page 10-8
• “Operations on Enumerated Data for Code Generation” on page 10-10
• “Include Enumerated Data in Control Flow Statements” on page 10-13
• “Customize Enumerated Types for Code Generation” on page 10-19
• “Use Enumerated Types in LED Control Function” on page 10-23
• “Control Names of Enumerated Type Values in Generated Code” on page 10-27
• “Change and Reload Enumerated Data Types” on page 10-30
• “Restrictions on Use of Enumerated Data in for-Loops” on page 10-31
• “Toolbox Functions That Support Enumerated Types for Code Generation” on page
10-32
10 Code Generation for Enumerated Data

Enumerated Data Definition for Code Generation


To generate efficient standalone code for enumerated data, you must define and use
enumerated types differently than you do in the MATLAB environment:

Difference More Information


Supports integer-based enumerated types “Enumerated Types Supported for Code
only Generation” on page 10-3
Name of each enumerated data type must “Naming Enumerated Types for Code
be unique Generation” on page 10-9
Each enumerated data type must be “Define Enumerated Data for Code
defined in a separate file on the MATLAB Generation” on page 10-8 and
path “Generate Code for Enumerated Data from
MATLAB Algorithms” on page 10-7
Restricted set of operations “Operations on Enumerated Data for Code
Generation” on page 10-10
Restricted use in for-loops “Restrictions on Use of Enumerated Data
in for-Loops” on page 10-31

10-2
Enumerated Types Supported for Code Generation

Enumerated Types Supported for Code Generation


An enumerated type is a user-defined type whose values belong to a predefined set
of enumerated values. Each enumerated value consists of a name and an underlying
numeric value.

You define an enumerated data type in an enumeration class definition file. For code
generation, you must base the class on int8, uint8, int16, uint16, or int32. For
example:

classdef PrimaryColors < int32


enumeration
Red(1),
Blue(2),
Yellow(4)
end
end

In this example, the statement classdef PrimaryColors < int32 means


that the enumerated type PrimaryColors is based on the built-in type int32.
PrimaryColors inherits the characteristics of the int32 type. It also defines its own
unique characteristics. For example, PrimaryColors is restricted to three enumerated
values:

Enumerated Value Enumerated Name Underlying Numeric Value


Red(1) Red 1
Blue(2) Blue 2
Yellow(4) Yellow 4

Enumeration Class Base Types for Code Generation


For code generation, you must base an enumerated type on one of the following built-in
MATLAB integer data types:

• int8
• uint8
• int16
• uint16

10-3
10 Code Generation for Enumerated Data

• int32

You can use the base type to control the size of an enumerated type in generated C/C++
code. You can:

• Represent an enumerated type as a fixed-size integer that is portable to different


targets.
• Reduce memory usage.
• Interface to legacy code.
• Match company standards.

The base type determines the representation of the enumerated type in generated C/C++
code.

C Code Representation for Base Type int32


If the base type is int32, the code generation software generates a C enumeration type.
Consider the following MATLAB enumerated type definition:
classdef LEDcolor < int32
enumeration
GREEN(1),
RED(2)
end
end

This enumerated type definition results in the following C code:


enum LEDcolor
{
GREEN = 1,
RED
};

typedef enum LEDcolor LEDcolor;

C Code Representation for Base Type Other Than int32


For built-in integer base types other than int32, the code generation software generates
a typedef statement for the enumerated type and #define statements for the
enumerated values. Consider the following MATLAB enumerated type definition:

10-4
Enumerated Types Supported for Code Generation

classdef LEDcolor < int16


enumeration
GREEN(1),
RED(2)
end

end
This enumerated type definition results in the following C code:
typedef short LEDcolor;
#define GREEN ((LEDcolor)1)
#define RED ((LEDcolor)2)
The C type in the typedef statement depends on:

• The integer sizes defined for the production hardware in the Hardware
Implementation object or the project settings. See coder.HardwareImplementation.
• The setting that determines use of built-in C types or MathWorks typedefs in the
generated code. See “Specify Data Types Used in Generated Code” on page 21-38
and “How MATLAB Coder Infers C/C++ Data Types” on page 27-9 .

10-5
10 Code Generation for Enumerated Data

When to Use Enumerated Data for Code Generation


You can use enumerated types to represent program states and to control program logic,
especially when you restrict data to a predetermined set of values and refer to these
values by name. You can sometimes achieve these goals by using integers or strings,
however, enumerated types offer the following advantages:

• More readable code than integers.


• More robust error checking than integers or strings.

For example, if you mistype the name of an element in the enumerated type, you get a
compile-time error that the element does not belong to the set of allowable values.
• More efficient code than strings.

For example, comparisons of enumerated values execute faster than comparisons of


strings.

10-6
Generate Code for Enumerated Data from MATLAB Algorithms

Generate Code for Enumerated Data from MATLAB Algorithms


The basic workflow for generating code for enumerated types in MATLAB code is:

1 Define an enumerated data type that inherits from a base type that code generation
supports. See “Enumerated Types Supported for Code Generation” on page 10-3.
2 Save the enumerated data type in a file on the MATLAB path.
3 Write a MATLAB function that uses the enumerated type.
4 Specify enumerated type inputs using the project or the command-line interface.
5 Generate code.

See Also
• “Use Enumerated Types in LED Control Function” on page 10-23
• “Define Enumerated Data for Code Generation” on page 10-8
• “Specify an Enumerated Type Input Parameter by Example” on page 18-9
• “Specify an Enumerated Type Input Parameter by Type” on page 18-13

10-7
10 Code Generation for Enumerated Data

Define Enumerated Data for Code Generation


To define enumerated data for code generation from MATLAB algorithms:

1 Create a class definition file.

In the Command Window, select File > New > Class.

2 Enter the class definition:


classdef EnumTypeName < BaseType

EnumTypeName is a case-sensitive string that must be unique among data type


names and workspace variable names. BaseType must be int8, uint8, int16,
uint16, or int32.

For example, the following code defines an enumerated type called sysMode that
inherits from the built-in type int32:
classdef sysMode < int32
...
end
3 Define enumerated values in an enumeration section:
classdef EnumTypeName < BaseType
enumeration
EnumName(N)
...
end
end

For example, the following code defines a set of two values for enumerated type
sysMode:
classdef sysMode < int32
enumeration
OFF(0),
ON(1)
end
end

Each enumerated value consists of a string EnumName and an underlying integer


N. Each EnumName must be unique within its type. If the enumerated value name

10-8
Define Enumerated Data for Code Generation

does not include the class name prefix, EnumName must be unique across enumerated
types. See “Control Names of Enumerated Type Values in Generated Code” on page
10-27.

The underlying integers do not have to be consecutive or ordered, or unique within or


across types.
4 Save the file on the MATLAB path.

The name of the file must match the name of the enumerated data type. The match
is case sensitive.

For examples, see “Include Enumerated Data in Control Flow Statements” on page
10-13.

Naming Enumerated Types for Code Generation


You must use a unique name for each enumerated data type. Do not use the name of:

• A toolbox function supported for code generation.


• Another data type.
• A variable in the MATLAB base workspace.

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 “Functions and Objects
Supported for C and C++ Code Generation — Alphabetical List” on page 4-2.

10-9
10 Code Generation for Enumerated Data

Operations on Enumerated Data for Code Generation


To generate efficient standalone code for enumerated data, you are restricted to the
following operations. The examples use the following enumerated class definition:
classdef LEDcolor < int32
enumeration
GREEN(1),
RED(2)
end
end

Assignment Operator, =
Example Result
xon = LEDcolor.GREEN xon =
xoff = LEDcolor.RED
GREEN
xoff =

RED

Relational Operators, < > <= >= == ~=


Example Result
xon == xoff ans =

0
xon <= xoff ans =

1
xon > xoff ans =

Cast Operation
Example Result
double(LEDcolor.RED) ans =

10-10
Operations on Enumerated Data for Code Generation

Example Result

2
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

Control Flow Statements: if, switch, while


Statement Example Executable Example
if if state == sysMode.ON “if Statement with
led = LEDcolor.GREEN; Enumerated Data
else Types” on page
led = LEDcolor.RED;
10-13
end
switch switch button “switch Statement
case VCRButton.Stop with Enumerated
state = VCRState.Stop;

10-11
10 Code Generation for Enumerated Data

Statement Example Executable Example


case VCRButton.PlayOrPause Data Types” on page
state = VCRState.Play; 10-14
case VCRButton.Next
state = VCRState.Forward;
case VCRButton.Previous
state = VCRState.Rewind;
otherwise
state = VCRState.Stop;
end
while while state ~= State.Ready “while Statement
switch state with Enumerated
case State.Standby Data Types” on page
initialize();
10-16
state = State.Boot;
case State.Boot
boot();
state = State.Ready;
end
end

10-12
Include Enumerated Data in Control Flow Statements

Include Enumerated Data in Control Flow Statements


The following examples define enumerated types that use the base type int32. You can
base an enumerated type on one of these built-in integer types:

• int8
• uint8
• int16
• uint16
• int32

The base type determines the representation of the enumerated type in the generated C/
C++ code. See “Enumerated Types Supported for Code Generation” on page 10-3.

if Statement with Enumerated Data Types


This example defines the enumeration types LEDcolor and sysMode. The function
displayState uses these enumerated data types to activate an LED display.

Class Definition: sysMode


classdef sysMode < int32
enumeration
OFF(0),
ON(1)
end
end

This definition must reside on the MATLAB path in a file with the same name as the
class, sysMode.m.

Class Definition: LEDcolor


classdef LEDcolor < int32
enumeration
GREEN(1),
RED(2)
end
end

This definition must reside on the MATLAB path in a file called LEDcolor.m.

10-13
10 Code Generation for Enumerated Data

MATLAB Function: displayState

This function 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.

function led = displayState(state)


%#codegen

if state == sysMode.ON
led = LEDcolor.GREEN;
else
led = LEDcolor.RED;
end

Build and Test a MEX Function for displayState

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.

codegen displayState -args {sysMode.ON}


2 Test the function. For example,

displayState_mex(sysMode.OFF)

ans =

RED

switch Statement with Enumerated Data Types


This example is based on the definition of the enumeration types VCRState and
VCRButton. The function VCR uses these enumerated data types to set the state of the
VCR.

Class Definition: VCRState

classdef VCRState < int32


enumeration
Stop(0),
Pause(1),
Play(2),
Forward(3),

10-14
Include Enumerated Data in Control Flow Statements

Rewind(4)
end
end

This definition must reside on the MATLAB path in a file with the same name as the
class, VCRState.m.

Class Definition: VCRButton

classdef VCRButton < int32


enumeration
Stop(1),
PlayOrPause(2),
Next(3),
Previous(4)
end
end

This definition must reside on the MATLAB path in a file with the same name as the
class, VCRButton.m.

MATLAB Function: VCR

This function uses enumerated data to set the state of a VCR, based on the initial state of
the VCR and the state of the VCR button.

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);
case VCRState.Play
switch button
case VCRButton.PlayOrPause, state = VCRState.Pause;
otherwise, state = handleDefault(button);
end
case VCRState.Pause

10-15
10 Code Generation for Enumerated Data

switch button
case VCRButton.PlayOrPause, state = VCRState.Play;
otherwise, state = handleDefault(button);
end
end
s = state;

function state = handleDefault(button)


switch button
case VCRButton.Stop, state = VCRState.Stop;
case VCRButton.PlayOrPause, state = VCRState.Play;
case VCRButton.Next, state = VCRState.Forward;
case VCRButton.Previous, state = VCRState.Rewind;
otherwise, state = VCRState.Stop;
end

Build and Test a MEX Function for VCR

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.
codegen -args {VCRButton.Stop} VCR
2 Test the function. For example,
s = VCR_mex(VCRButton.Stop)

s =

Stop

while Statement with Enumerated Data Types


This example is based on the definition of the enumeration type State. The function
Setup uses this enumerated data type to set the state of a device.

Class Definition: State


classdef State < int32
enumeration
Standby(0),
Boot(1),
Ready(2)
end
end

10-16
Include Enumerated Data in Control Flow Statements

This definition must reside on the MATLAB path in a file with the same name as the
class, State.m.

MATLAB Function: Setup

The following function Setup uses enumerated data to set the state of a device.
function s = Setup(initState)
%#codegen

state = initState;

if isempty(state)
state = State.Standby;
end

while state ~= State.Ready


switch state
case State.Standby
initialize();
state = State.Boot;
case State.Boot
boot();
state = State.Ready;
end
end
s = state;

function initialize()
% Perform initialization.

function boot()
% Boot the device.

Build and Test a MEX Executable for Setup

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.
codegen Setup -args {State.Standby}
2 Test the function. For example,
s = Setup_mex(State.Standby)

s =

10-17
10 Code Generation for Enumerated Data

Ready

10-18
Customize Enumerated Types for Code Generation

Customize Enumerated Types for Code Generation

Customizing Enumerated Types


For code generation, you can customize an enumerated type by using the same
techniques that work with MATLAB classes, as described in Modifying Superclass
Methods and Properties. To customize an enumerated type, override one of the static
methods described in the following table. Include a customized version of the method in
the static methods section of the class definition. If you do not want to override the static
methods, omit the static methods section.

Method Description Default Value When to Use


Returned or Specified
addClassNameToEnumNames Specifies whether false — prefix is If you want the class
the class name not used. name to become
becomes a prefix in a prefix in the
the generated code. generated code,
override this method
to set the return
value to true. See
“Control Names of
Enumerated Type
Values in Generated
Code” on page
10-27.
getDefaultValue Returns the default First value in the If you want the
enumerated value. enumerated class default value for the
definition. enumerated type
to be something
other than the first
value listed in the
enumerated class
definition, override
this method to specify
a default value. See
“Specify a Default
Enumerated Value”
on page 10-20.

10-19
10 Code Generation for Enumerated Data

Method Description Default Value When to Use


Returned or Specified
getHeaderFile Specifies the '' If you want to use
file in which the an enumerated
enumerated class class definition that
is defined for code is specified in a
generation. custom header file,
override this method
to return the path to
this header file. In
this case, the code
generation software
does not generate
the class definition.
See “Specify a
Header File” on page
10-21

Specify a Default Enumerated Value


If the value of a variable that is cast to an enumerated type does not match one of the
enumerated type values:

• Generated MEX reports an error.


• Generated C/C++ code replaces the value of the variable with the enumerated type
default value.

Unless you specify otherwise, the default value for an enumerated type is the first value
in the enumerated class definition. To specify a different default value, add your own
getDefaultValue method to the methods section. The following code shows a shell for
the getDefaultValue method:
function retVal = getDefaultValue()
% GETDEFAULTVALUE Returns the default enumerated value.
% This value must be an instance of the enumerated class.
% If this method is not defined, the first enumerated value is used.
retVal = ThisClass.EnumName;
end
To customize this method, provide a value for ThisClass.EnumName that specifies
the default that you want. ThisClass must be the name of the class within which the

10-20
Customize Enumerated Types for Code Generation

method exists. EnumName must be the name of an enumerated value defined in that
class. For example:

classdef LEDcolor < int32


enumeration
GREEN(1),
RED(2)
end

methods (Static)
function y = getDefaultValue()
y = LEDcolor.RED;
end
end
end
This example defines the default as LEDcolor.RED. If this method does not appear,
the default value is LEDcolor.GREEN, because that value is the first value listed in the
enumerated class definition.

Specify a Header File


To prevent the declaration of an enumerated type from being embedded in the generated
code, allowing you to provide the declaration in an external file, include the following
method in the enumerated class methods section:

function y = getHeaderFile()
% GETHEADERFILE File where type is defined for generated code.
% If specified, this file is #included where required in the code.
% Otherwise, the type is written out in the generated code.
y = 'filename';
end
Substitute a legal filename for filename. Be sure to provide a filename suffix, typically
.h. Providing the method replaces the declaration that appears in the generated code
with an #include statement like:

#include "imported_enum_type.h"
The getHeaderFile method does not create the declaration file itself. You must provide
a file of the specified name that declares the enumerated data type. The file can also
contain definitions of enumerated types that you do not use in your MATLAB code.

For example, to use the definition of LEDcolor in my_LEDcolor.h:

10-21
10 Code Generation for Enumerated Data

1 Modify the definition of LEDcolor to override the getHeaderFile method to return


the name of the external header file:
classdef LEDcolor < int32
enumeration
GREEN(1),
RED(2)
end

methods(Static)
function y=getHeaderFile()
y='my_LEDcolor.h';
end
end
end
2 In the current folder, provide a header file, my_LEDcolor.h, that contains the
definition:
enum LEDcolor
{
GREEN = 1,
RED
};

typedef enum LEDcolor LEDcolor;


3 Generate a library for the function displayState that takes one input of
enumerated data type sysMode.

codegen -config:lib -report displayState -args {sysMode.ON}

codegen generates a C static library with the default name, displayState, and
supporting files in the default folder, codegen/lib/displayState.
4 Click the View Report link.
5 In the report, on the C Code tab, click the link to the displayState_types.h file.

The header file contains a #include statement for the external header file.

#include "my_LEDcolor.h"
It does not include a declaration for the enumerated class.

10-22
Use Enumerated Types in LED Control Function

Use Enumerated Types in LED Control Function


This example shows how to define, use, and generate code for enumerated types in a
function that controls an LED. In this example, the enumerated types inherit from base
type int32. The base type can be int8, uint8, int16, uint16, or int32.

To create a working folder and get copies of the example files, click Open This
Example.

View the enumerated type sysMode.


type sysMode

classdef sysMode < int32


enumeration
OFF(0),
ON(1)
end
end

View the enumerated type LEDcolor.


type LEDcolor

classdef LEDcolor < int32


enumeration
GREEN(1),
RED(2)
end
end

View the function displayState that uses enumerated data to activate an LED display,
based on the state of a device. displayState lights a green LED display to indicate the
ON state. It lights a red LED display to indicate the OFF state.
type displayState

function led = displayState(state)


%#codegen

if state == sysMode.ON
led = LEDcolor.GREEN;
else

10-23
10 Code Generation for Enumerated Data

led = LEDcolor.RED;
end

Generate the MEX function displayState_mex. Specify that displayState_mex has


one input that is an enumerated data type sysMode.
codegen displayState -args {sysMode.ON}

Test the MEX function.


displayState_mex(sysMode.OFF)

ans =

RED

Generate a static library for the function displayState that takes one input of
enumerated data type sysMode.
codegen -config:lib displayState -args {sysMode.ON}

codegen generates a C static library with the default name, displayState. It generates
supporting files in the default folder, codegen/lib/displayState.

View the header file displayState_types.h.


type codegen/lib/displayState/displayState_types.h

/*
* File: displayState_types.h
*
* MATLAB Coder version : 3.1
* C/C++ source code generated on : 15-Feb-2016 15:09:30
*/

#ifndef DISPLAYSTATE_TYPES_H
#define DISPLAYSTATE_TYPES_H

/* Include Files */
#include "rtwtypes.h"

/* Type Definitions */

10-24
Use Enumerated Types in LED Control Function

#ifndef enum_LEDcolor
#define enum_LEDcolor

enum LEDcolor
{
GREEN = 1,
RED
};

#endif /*enum_LEDcolor*/

#ifndef typedef_LEDcolor
#define typedef_LEDcolor

typedef enum LEDcolor LEDcolor;

#endif /*typedef_LEDcolor*/

#ifndef enum_sysMode
#define enum_sysMode

enum sysMode
{
OFF,
ON
};

#endif /*enum_sysMode*/

#ifndef typedef_sysMode
#define typedef_sysMode

typedef enum sysMode sysMode;

#endif /*typedef_sysMode*/
#endif

/*
* File trailer for displayState_types.h
*
* [EOF]
*/

10-25
10 Code Generation for Enumerated Data

The enumerated type LEDcolor is represented as a C enumerated type because the


base type in the class definition for LEDcolor is int32. When the base type is int8,
uint8, int16, or uint16, the code generation software generates a typedef for the
enumerated type. It generates #define statements for the enumerated type values. For
example:
typedef short LEDcolor;
#define GREEN ((LEDcolor)1)
#define RED ((LEDcolor)2)

Related Examples
• “Generate Code for Enumerated Data from MATLAB Algorithms” on page 10-7
• “Customize Enumerated Types for Code Generation” on page 10-19

More About
• “Enumerated Data Definition for Code Generation” on page 10-2
• “Enumerated Types Supported for Code Generation” on page 10-3

10-26
Control Names of Enumerated Type Values in Generated Code

Control Names of Enumerated Type Values in Generated Code


This example shows how to control whether generated enumerated type value names
include the class name prefix from the enumerated type definition. By default, the
generated enumerated type value name does not include the class name prefix.

1 Define the enumerated type sysMode. Store it in sysMode.m on the MATLAB path.

classdef sysMode < int32


enumeration
OFF(0),
ON(1)
end
end
2 Define the enumerated type LEDcolor. Store it in LEDcolor.m on the MATLAB
path.

classdef LEDcolor < int32


enumeration
GREEN(1),
RED(2)
end
end
3 Define the function displayState, which uses enumerated data to activate an LED
display, based on the state of a device. displayState lights a green LED display to
indicate the ON state and lights a red LED display to indicate the OFF state. Store
in displayState.m on the MATLAB path.

function led = displayState(state)


%#codegen

if state == sysMode.ON
led = LEDcolor.GREEN;
else
led = LEDcolor.RED;
end
4 Generate a library for the function displayState that takes one input of
enumerated data type sysMode.

codegen -config:lib -report displayState -args {sysMode.ON}

10-27
10 Code Generation for Enumerated Data

codegen generates a C static library with the default name, displayState, and
supporting files in the default folder, codegen/lib/displayState.
5 Click the View Report link.
6 In the report, on the C Code tab, click the link to the displayState_types.h file.

The report displays the header file containing the enumerated data type definition.

enum LEDcolor
{
GREEN = 1,
RED
};

typedef enum LEDcolor LEDcolor;

The enumerated value names do not include the class name prefix LEDcolor_.
7 Modify the definition of LEDcolor to add the addClassNameToEnumNames method.
Set the return value to true so that the enumerated value names in the generated
code contain the class prefix.

classdef LEDcolor < int32


enumeration
GREEN(1),
RED(2)
end

methods(Static)
function y=addClassNameToEnumNames()
y=true;
end
end
end
8 Clear existing class instances.

clear classes
9 Generate code.

codegen -config:lib -report displayState -args {sysMode.ON}


10 Open the code generation report and look at the enumerated type definition in
displayState_types.h.

10-28
Control Names of Enumerated Type Values in Generated Code

enum LEDcolor
{
LEDcolor_GREEN = 1,
LEDcolor_RED
};

typedef enum LEDcolor LEDcolor;


The enumerated value names include the class name prefix.

10-29
10 Code Generation for Enumerated Data

Change and Reload Enumerated Data Types


You can change the definition of an enumerated data type by editing and saving the file
that contains the definition. You do not need to inform MATLAB that a class definition
has changed. MATLAB automatically reads the modified definition when you save
the file. However, the class definition changes do not take full effect if class instances
(enumerated values) exist that reflect the previous class definition. Such instances might
exist in the base workspace or might be cached. The following table explains options for
removing instances of an enumerated data type from the base workspace and cache.

If In Base Workspace... If In Cache...


Do one of the following: • Clear MEX functions that are caching
instances of the class.
• Locate and delete specific obsolete
instances.
• Delete the classes from the workspace
by using the clear classes
command. For more information, see
clear.

10-30
Restrictions on Use of Enumerated Data in for-Loops

Restrictions on Use of Enumerated Data in for-Loops


Do not use enumerated data as the loop counter variable in for- loops

To iterate over a range of enumerated data with consecutive values, in the loop counter,
cast the enumerated data to a built-in integer type. The size of the built-in integer type
must be big enough to contain the enumerated value.

For example, suppose you define an enumerated type ColorCodes as follows:

classdef ColorCodes < int32


enumeration
Red(1),
Blue(2),
Green(3),
Yellow(4),
Purple(5)
end
end

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

10-31
10 Code Generation for Enumerated Data

Toolbox Functions That Support Enumerated Types for Code


Generation
The following MATLAB toolbox functions support enumerated types for code generation:

• cast
• cat
• circshift
• fliplr
• flipud
• histc
• intersect
• ipermute
• isequal
• isequaln
• isfinite
• isinf
• ismember
• isnan
• issorted
• length
• permute
• repmat
• reshape
• rot90
• setdiff
• setxor
• shiftdim
• sort
• sortrows
• squeeze

10-32
Toolbox Functions That Support Enumerated Types for Code Generation

• union
• unique

10-33
11

Code Generation for MATLAB Classes

• “MATLAB Classes Definition for Code Generation” on page 11-2


• “Classes That Support Code Generation” on page 11-8
• “Generate Code for MATLAB Value Classes” on page 11-9
• “Generate Code for MATLAB Handle Classes and System Objects” on page 11-14
• “MATLAB Classes in Code Generation Reports” on page 11-17
• “Troubleshooting Issues with MATLAB Classes” on page 11-20
• “Handle Object Limitations for Code Generation” on page 11-22
• “System Objects Requirements and Limitations for Code Generation” on page
11-25
11 Code Generation for MATLAB Classes

MATLAB Classes Definition for Code Generation


To generate efficient standalone code for MATLAB classes, you must use classes
differently than when running your code in the MATLAB environment.

What’s Different More Information


Class must be in a single file. Because “Create a Single, Self-Contained Class
of this limitation, code generation is not Definition File”
supported for a class definition that uses an
@-folder.
Restricted set of language features. “Language Limitations” on page 11-2
Restricted set of code generation features. “Code Generation Features Not Compatible
with Classes” on page 11-3
Definition of class properties. “Defining Class Properties for Code
Generation” on page 11-4
Use of handle classes. “Generate Code for MATLAB Handle
Classes and System Objects” on page
11-14

“Handle Object Limitations for Code


Generation” on page 11-22
Calls to base class constructor. “Calls to Base Class Constructor” on page
11-5
Global variables containing MATLAB N/A
objects are not supported for code
generation.
Inheritance from built-in MATLAB classes “Inheritance from Built-In MATLAB
is not supported. Classes Not Supported” on page 11-7

Language Limitations
Although code generation support is provided for common features of classes such
as properties and methods, there are a number of advanced features which are not
supported, such as:

• Events

11-2
MATLAB Classes Definition for Code Generation

• Listeners
• Arrays of objects
• Recursive data structures

• Linked lists
• Trees
• Graphs
• Overloadable operators subsref, subsassign, and subsindex

In MATLAB, classes can define their own versions of the subsref, subsassign, and
subsindex methods. Code generation does not support classes that have their own
definitions of these methods.
• The empty method

In MATLAB, classes have a built-in static method, empty, which creates an empty
array of the class. Code generation does not support this method.
• The following MATLAB handle class methods:

• addlistener
• delete
• eq
• findobj
• findpro
• The AbortSet property attribute

Code Generation Features Not Compatible with Classes


• You can generate code for entry-point MATLAB functions that use classes, but you
cannot generate code directly for a MATLAB class.

For example, if ClassNameA is a class definition, you cannot generate code by


executing:

codegen ClassNameA
• If an entry-point MATLAB function has an input or output that is a MATLAB class,
you cannot generate code for this function.

11-3
11 Code Generation for MATLAB Classes

For example, if function foo takes one input, a, that is a MATLAB object, you cannot
generate code for foo by executing:

codegen foo -args {a}


• Code generation does not support classes in matrices or structures. As a workaround,
consider using cell arrays because code generation supports classes in cell arrays.
• Code generation does not support assigning an object of a value class into a
nontunable property. For example, obj.prop=v; is invalid when prop is a
nontunable property and v is an object based on a value class.
• You cannot use coder.extrinsic to declare a class or method as extrinsic.
• You cannot pass a MATLAB class to the coder.ceval function.
• If you use classes in code in the MATLAB Function block, you cannot use the
debugger to view class information.
• The coder.nullcopy function does not support MATLAB classes as inputs.

Defining Class Properties for Code Generation


For code generation, you must define class properties differently than you do when
running your code in the MATLAB environment:

• Code generation does not support the property restriction syntax. For example, the
following class definition is not allowed because it uses the property restriction syntax
to restrict the types of the Number and Today properties.

classdef Myclass
properties
Number double
Today char = date;
end
end
• After defining a property, do not assign it an incompatible type. Do not use a property
before attempting to grow it.

When you define class properties for code generation, consider the same factors that
you take into account when defining variables. In the MATLAB language, variables
can change their class, size, or complexity dynamically at run time so you can use
the same variable to hold a value of varying class, size, or complexity. C and C++ use
static typing. Before using variables, to determine their type, the code generation

11-4
MATLAB Classes Definition for Code Generation

software requires a complete assignment to each variable. Similarly, before using


properties, you must explicitly define their class, size, and complexity.
• Initial values:

• If the property does not have an explicit initial value, the code generation software
assumes that it is undefined at the beginning of the constructor. The code
generation software does not assign an empty matrix as the default.
• If the property does not have an initial value and the code generation software
cannot determine that the property is assigned prior to first use, the software
generates a compilation error.
• For System objects, if a nontunable property is a structure, you must completely
assign the structure. You cannot do partial assignment using subscripting.

For example, for a nontunable property, you can use the following assignment:
mySystemObject.nonTunableProperty=struct('fieldA','a','fieldB','b');

You cannot use the following partial assignments:


mySystemObject.nonTunableProperty.fieldA = a;
mySystemObject.nonTunableProperty.fieldB = b;
• If dynamic memory allocation is enabled, code generation supports variable-size
properties for handle classes. Without dynamic memory allocation, you cannot
generate code for handle classes that have variable-size properties.
• coder.varsize is not supported for class properties.
• MATLAB computes class initial values at class loading time before code generation.
If you use persistent variables in MATLAB class property initialization, the value of
the persistent variable computed when the class loads belongs to MATLAB; it is not
the value used at code generation time. If you use coder.target in MATLAB class
property initialization, coder.target('MATLAB') returns true (1).

Calls to Base Class Constructor


If a class constructor contains a call to the constructor of the base class, the call to the
base class constructor must come before for, if, return, switch or while statements.

For example, if you define a class B based on class A:


classdef B < A
methods

11-5
11 Code Generation for MATLAB Classes

function obj = B(varargin)


if nargin == 0
a = 1;
b = 2;
elseif nargin == 1
a = varargin{1};
b = 1;
elseif nargin == 2
a = varargin{1};
b = varargin{2};
end
obj = obj@A(a,b);
end

end
end

Because the class definition for B uses an if statement before calling the base class
constructor for A, you cannot generate code for function callB:
function [y1,y2] = callB
x = B;
y1 = x.p1;
y2 = x.p2;
end

However, you can generate code for callB if you define class B as:
classdef B < A
methods
function obj = NewB(varargin)
[a,b] = getaandb(varargin{:});
obj = obj@A(a,b);
end

end
end

function [a,b] = getaandb(varargin)


if nargin == 0
a = 1;
b = 2;
elseif nargin == 1
a = varargin{1};
b = 1;

11-6
MATLAB Classes Definition for Code Generation

elseif nargin == 2
a = varargin{1};
b = varargin{2};
end
end

Inheritance from Built-In MATLAB Classes Not Supported


You cannot generate code for classes that inherit from built-in MATLAB classes. For
example, you cannot generate code for the following class:
classdef myclass < double

11-7
11 Code Generation for MATLAB Classes

Classes That Support Code Generation


You can generate code for MATLAB value and handle classes and user-defined System
objects. Your class can have multiple methods and properties and can inherit from
multiple classes.

To generate code for: Example:


Value classes “Generate Code for MATLAB Value
Classes” on page 11-9
Handle classes including user-defined “Generate Code for MATLAB Handle
System objects Classes and System Objects” on page
11-14

For more information, see:

• “Role of Classes in MATLAB”


• “MATLAB Classes Definition for Code Generation” on page 11-2

11-8
Generate Code for MATLAB Value Classes

Generate Code for MATLAB Value Classes


This example shows how to generate code for a MATLAB value class and then view the
generated code in the code generation report.

1 In a writable folder, create a MATLAB value class, Shape. Save the code as
Shape.m.

classdef Shape
% SHAPE Create a shape at coordinates
% centerX and centerY
properties
centerX;
centerY;
end
properties (Dependent = true)
area;
end
methods
function out = get.area(obj)
out = obj.getarea();
end
function obj = Shape(centerX,centerY)
obj.centerX = centerX;
obj.centerY = centerY;
end
end
methods(Abstract = true)
getarea(obj);
end
methods(Static)
function d = distanceBetweenShapes(shape1,shape2)
xDist = abs(shape1.centerX - shape2.centerX);
yDist = abs(shape1.centerY - shape2.centerY);
d = sqrt(xDist^2 + yDist^2);
end
end
end
2 In the same folder, create a class, Square, that is a subclass of Shape. Save the code
as Square.m.

classdef Square < Shape


% Create a Square at coordinates center X and center Y

11-9
11 Code Generation for MATLAB Classes

% with sides of length of side


properties
side;
end
methods
function obj = Square(side,centerX,centerY)
obj@Shape(centerX,centerY);
obj.side = side;
end
function Area = getarea(obj)
Area = obj.side^2;
end
end
end
3 In the same folder, create a class, Rhombus, that is a subclass of Shape. Save the
code as Rhombus.m.

classdef Rhombus < Shape


properties
diag1;
diag2;
end
methods
function obj = Rhombus(diag1,diag2,centerX,centerY)
obj@Shape(centerX,centerY);
obj.diag1 = diag1;
obj.diag2 = diag2;
end
function Area = getarea(obj)
Area = 0.5*obj.diag1*obj.diag2;
end
end
end
4 Write a function that uses this class.

function [TotalArea, Distance] = use_shape


%#codegen
s = Square(2,1,2);
r = Rhombus(3,4,7,10);
TotalArea = s.area + r.area;
Distance = Shape.distanceBetweenShapes(s,r);
5 Generate a static library for use_shape and generate a code generation report.

11-10
Generate Code for MATLAB Value Classes

codegen -config:lib -report use_shape

codegen generates a C static library with the default name, use_shape, and
supporting files in the default folder, codegen/lib/use_shape.
6 Click the View report link.
7 In the report, on the MATLAB code tab, click the link to the Rhombus class.

The report displays the class definition of the Rhombus class and highlights the
class constructor. On the Variables tab, it provides details of the variables used
in the class. If a variable is a MATLAB object, by default, the report displays the
object without displaying its properties. To view the list of properties, expand the
list. Within the list of properties, the list of inherited properties is collapsed. In the
following report, the lists of properties and inherited properties are expanded.

11-11
11 Code Generation for MATLAB Classes

8 At the top right side of the report, expand the Calls list.

The Calls list shows that there is a call to the Rhombus constructor from use_shape
and that this constructor calls the Shape constructor.

9 The constructor for the Rhombus class calls the Shape method of the base Shape
class: obj@Shape. In the report, click the Shape link in this call.

The link takes you to the Shape method in the Shape class definition.

11-12
Generate Code for MATLAB Value Classes

11-13
11 Code Generation for MATLAB Classes

Generate Code for MATLAB Handle Classes and System Objects


This example shows how to generate code for a user-defined System object and then view
the generated code in the code generation report.

1 In a writable folder, create a System object, AddOne, which subclasses from


matlab.System. Save the code as AddOne.m.

classdef AddOne < matlab.System


% ADDONE Compute an output value that increments the input by one

methods (Access=protected)
% stepImpl method is called by the step method
function y = stepImpl(~,x)
y = x+1;
end
end
end
2 Write a function that uses this System object.

function y = testAddOne(x)
%#codegen
p = AddOne();
y = p.step(x);
end
3 Generate a MEX function for this code.

codegen -report testAddOne -args {0}

The -report option instructs codegen to generate a code generation report, even
if no errors or warnings occur. The -args option specifies that the testAddOne
function takes one scalar double input.
4 Click the View report link.
5 In the report, on the MATLAB Code tab Functions panel, click testAddOne, then
click the Variables tab. You can view information about the variable p on this tab.

11-14
Generate Code for MATLAB Handle Classes and System Objects

6 To view the class definition, on the Classes panel, click AddOne.

11-15
11 Code Generation for MATLAB Classes

11-16
MATLAB Classes in Code Generation Reports

MATLAB Classes in Code Generation Reports


What Reports Tell You About Classes
Code generation reports:

• Provide a hierarchical tree of the classes used in your MATLAB code.


• Display a list of methods for each class in the MATLAB code tab.
• Display the objects used in your MATLAB code together with their properties on the
Variables tab.
• Provide a filter so that you can sort methods by class, size, and complexity.
• List the set of calls from and to the selected method in the Calls list.

How Classes Appear in Code Generation Reports


In the MATLAB Code Tab

The report displays an alphabetical hierarchical list of the classes used in the your
MATLAB code. For each class, you can:

• Expand the class information to view the class methods.


• View a class method by clicking its name. The report displays the methods in the
context of the full class definition.
• Filter the methods by size, complexity, and class by using the Filter functions and
methods option.
Default Constructors

If a class has a default constructor, the report displays the constructor in italics.
Specializations

If the same class is specialized into multiple different classes, the report differentiates
the specializations by grouping each one under a single node in the tree. The report
associates the class definition functions and static methods with the primary node. It
associates the instance-specific methods with the corresponding specialized node.

For example, consider a base class, Shape that has two specialized subclasses,
Rhombus and Square. The Shape class has an abstract method, getarea, and a
static method, distanceBetweenShapes. The code generation report, displays a

11-17
11 Code Generation for MATLAB Classes

node for the specialized Rhombus and Square classes with their constructors and
getarea method. It displays a node for the Shape class and its associated static method,
distanceBetweenShapes, and two instances of the Shape class, Shape1 and Shape2.

Packages

If you define classes as part of a package, the report displays the package in the list
of classes. You can expand the package to view the classes that it contains. For more
information about packages, see “Packages Create Namespaces”.

In the Variables Tab

The report displays the objects in the selected function or class. By default, for classes
that have properties, the list of properties is collapsed. To expand the list, click the
+ symbol next to the object name. Within the list of properties, the list of inherited
properties is collapsed. To expand the list of inherited properties, click the + symbol next
to Inherited.

The report displays the properties using just the base property name, not the fully
qualified name. For example, if your code uses variable obj1 that is a MATLAB object

11-18
MATLAB Classes in Code Generation Reports

with property prop1, then the report displays the property as prop1 not obj1.prop1.
When you sort the Variables column, the sort order is based on the fully qualified
property name.

In the Call Stack

The call stack lists the functions and methods in the order that the top-level function
calls them. It also lists the local functions that each function calls.

11-19
11 Code Generation for MATLAB Classes

Troubleshooting Issues with MATLAB Classes

Class class does not have a property with name name


If a MATLAB class has a method, mymethod, that returns a handle class with a property,
myprop, you cannot generate code for the following type of assignment:

obj.mymethod().myprop=...

For example, consider the following classes:

classdef MyClass < handle


properties
myprop
end
methods
function this = MyClass
this.myprop = MyClass2;
end
function y = mymethod(this)
y = this.myprop;
end
end
end

classdef MyClass2 < handle


properties
aa
end
end

You cannot generate code for function foo.

function foo

h = MyClass;

h.mymethod().aa = 12;
In this function, h.mymethod() returns a handle object of type MyClass2. In MATLAB,
the assignment h.mymethod().aa = 12; changes the property of that object. Code
generation does not support this assignment.

11-20
Troubleshooting Issues with MATLAB Classes

Workaround

Rewrite the code to return the object and then assign a value to a property of the object.
function foo

h = MyClass;

b=h.mymethod();
b.aa=12;

11-21
11 Code Generation for MATLAB Classes

Handle Object Limitations for Code Generation


The code generation software statically determines the lifetimes of handle objects. It
can reuse memory rather than rely on a dynamic memory management scheme such as
reference counting or garbage collection. It generates code that does not use dynamic
memory allocation or incur the overhead of run-time automatic memory management.
These characteristics of the generated code are important for some safety-critical and
real-time applications.

When you use handle objects, the static analysis that the code generation software uses
requires that you adhere to the following restrictions:

• “A Variable Outside a Loop Cannot Refer to a Handle Object Created Inside a Loop”
on page 11-22
• “A Handle Object That a Persistent Variable Refers To Must Be a Singleton Object”
on page 11-22

A Variable Outside a Loop Cannot Refer to a Handle Object Created


Inside a Loop
Consider the handle class mycls and the function usehandle1. The code generation
software reports an error because p, which is outside the loop, has a property that refers
to a mycls object created inside the loop.
classdef mycls < handle
properties
prop
end
end

function usehandle1
p = mycls;
for i = 1:10
p.prop = mycls;
end

A Handle Object That a Persistent Variable Refers To Must Be a Singleton


Object
If a persistent variable refers to a handle object, the code generation software allows only
one instance of the object during the program’s lifetime. The object must be a singleton

11-22
Handle Object Limitations for Code Generation

object. To create a singleton handle object, enclose statements that create the object in
the if isempty() guard for the persistent variable.

For example, consider the class mycls and the function usehandle2. The code
generation software reports an error for usehandle2 because p.prop refers to the
mycls object that the statement inner = mycls creates. This statement creates a
mycls object for each invocation of usehandle2.

classdef mycls < handle


properties
prop
end
end

function usehandle2(x)
assert(isa(x, 'double'));
persistent p;
inner = mycls;
inner.prop = x;
if isempty(p)
p = mycls;
p.prop = inner;
end

If you move the statements inner = mycls and inner.prop = x inside the if
isempty() guard, code generation succeeds. The statement inner = mycls executes
only once during the program’s lifetime.
function usehandle2(x)
assert(isa(x, 'double'));
persistent p;
if isempty(p)
inner = mycls;
inner.prop = x;
p = mycls;
p.prop = inner;
end

Consider the function usehandle3. The code generation software reports an error
for usehandle3 because the persistent variable p refers to the mycls object that the
statement myobj = mycls creates. This statement creates a mycls object for each
invocation of usehandle3.

function usehandle3(x)

11-23
11 Code Generation for MATLAB Classes

assert(isa(x, 'double'));
myobj = mycls;
myobj.prop = x;
doinit(myobj);
disp(myobj.prop);
function doinit(obj)
persistent p;
if isempty(p)
p = obj;
end

If you make myobj persistent and enclose the statement myobj = mycls inside an if
isempty() guard, code generation succeeds. The statement myobj = mycls executes
only once during the program’s lifetime.
function usehandle3(x)
assert(isa(x, 'double'));
persistent myobj;
if isempty(myobj)
myobj = mycls;
end

doinit(myobj);

function doinit(obj)
persistent p;
if isempty(p)
p = obj;
end

11-24
System Objects Requirements and Limitations for Code Generation

System Objects Requirements and Limitations for Code Generation


The following usage rules and limitations apply to using System objects in code
generated from MATLAB.

Object Construction and Initialization

• If objects are stored in persistent variables, initialize System objects once by


embedding the object handles in an if statement with a call to isempty( ).
• Set arguments to System object constructors as compile-time constants.
• You cannot initialize System objects properties with other MATLAB class objects
as default values in code generation. You must initialize these properties in the
constructor.

Inputs and Outputs

• System objects accept a maximum of 32 inputs. A maximum of 8 dimensions per input


is supported.
• The data type of the inputs should not change.
• If you want the size of inputs to change, verify that variable-size is enabled. Code
generation support for variable-size data also requires that the Enable variable
sizing option is enabled, which is the default in MATLAB.

Note: Variable-size properties in MATLAB Function block in Simulink are not


supported. System objects predefined in the software do not support variable-size if
their data exceeds the DynamicMemoryAllocationThreshold value.
• Do not set System objects to become outputs from the MATLAB Function block.
• Do not use the Save and Restore Simulation State as SimState option for any System
object in a MATLAB Function block.
• Do not pass a System object as an example input argument to a function being
compiled with codegen.
• Do not pass a System object to functions declared as extrinsic (functions called in
interpreted mode) using the coder.extrinsic function. System objects returned
from extrinsic functions and scope System objects that automatically become extrinsic
can be used as inputs to another extrinsic function, but do not generate code.

Tunable and Nontunable Properties

11-25
11 Code Generation for MATLAB Classes

• The value assigned to a nontunable property must be a constant and there can be at
most one assignment to that property (including the assignment in the constructor).
• For most System objects, the only time you can set their nontunable properties during
code generation is when you construct the objects.

• For System objects that are predefined in the software, you can set their tunable
properties at construction time or using dot notation after the object is locked.
• For System objects that you define, you can change their tunable properties
at construction time or using dot notation during code generation. For
getNumInputsImpl and getNumOutputsImpl methods, if you set the
return argument from an object property, that object property must have the
Nontunable attribute.
• Objects cannot be used as default values for properties.

Global Variables

• Global variables are allowed in a System object, unless you will be using that System
object in Simulink via the MATLAB System block. To avoid syncing global variables
between a MEX file and the workspace, use a coder configuration object. For example:
f = coder.MEXConfig;
f.GlobalSyncMethod = 'NoSync'
Then, include '-config f' in your codegen command.

Methods

• Code generation support is available only for these System object methods:

• get
• getNumInputs
• getNumOutputs
• isDone (for sources only)
• isLocked
• release
• reset
• set (for tunable properties)
• step
• For System objects that you define,

11-26
System Objects Requirements and Limitations for Code Generation

Code generation support is available only for these methods:

• getDiscreteStateImpl
• getNumInputsImpl
• getNumOutputsImpl
• infoImpl
• isDoneImpl
• isInputDirectFeedThroughImpl
• outputImpl
• processTunedPropertiesImpl
• releaseImpl — Code is not generated automatically for the this method. To
release an object, you must explicitly call the release method in your code.
• resetImpl
• setupImpl
• stepImpl
• updateImpl
• validateInputsImpl
• validatePropertiesImpl
• Code generation support for using dot notation depends on whether the System object
is predefined in the software or is one that you defined.

• For System objects that are predefined in the software, you cannot use dot
notation to call methods.
• For System objects that you define, you can use dot notation or function call
notation, with the System object as first argument, to call methods.

11-27
12

Code Generation for Function Handles

• “Function Handle Definition for Code Generation” on page 12-2


• “Define and Pass Function Handles for Code Generation” on page 12-3
• “Function Handle Limitations for Code Generation” on page 12-5
12 Code Generation for Function Handles

Function Handle Definition for Code Generation


You can use function handles to invoke functions indirectly and parameterize operations
that you repeat frequently. You can perform the following operations with function
handles:

• Define handles that reference user-defined functions and built-in functions supported
for code generation (see “Functions and Objects Supported for C and C++ Code
Generation — Alphabetical List” on page 4-2)

Note: You cannot define handles that reference extrinsic MATLAB functions.
• Define function handles as scalar values
• Define structures that contain function handles
• Pass function handles as arguments to other functions (excluding extrinsic functions)

Related Examples
• “Define and Pass Function Handles for Code Generation” on page 12-3

More About
• “Function Handle Limitations for Code Generation” on page 12-5

12-2
Define and Pass Function Handles for Code Generation

Define and Pass Function Handles for Code Generation


This example shows how to define and pass function handles for code generation.

Write this MATLAB code.

function addval(m)
%#codegen

% Pass function handle for addone


% to add one to each element of m
m = map(@addone, m);
disp(m);

% Pass function handle for addtwo


% to add two to each element of m
m = map(@addtwo, m);
disp(m);

function y = map(f,y)
for i = 1:numel(y)
y(i) = f(y(i));
end

function y = addone(u)
y = u + 1;

function y = addtwo(u)
y = u + 2;

The function addone adds 1 to the value of the input. The function addtwo adds 2 to the
value of the input. The function map invokes the function whose handle is stored in f. It
invokes the function for each element of the input matrix. To add 1 to each element of its
input matrix, the function addval passes the function handle @addone to map. To add 2
to each element of the input matrix, addval passes the function handle @addtwo to map.

Define a 3-by-3 matrix m.

m = zeros(3);

Run addval in MATLAB. Pass m as the input argument.

addval(m)

12-3
12 Code Generation for Function Handles

1 1 1
1 1 1
1 1 1

3 3 3
3 3 3
3 3 3

Generate a MEX function for addval. Specify that the input argument has the class and
size of the MATLAB variable m.

codegen addval -args {m} -report

Run the MEX function.


addval_mex(m)

1 1 1
1 1 1
1 1 1

3 3 3
3 3 3
3 3 3

The output is the same as the output from running addval in MATLAB.

Related Examples
• “MEX Function Generation at the Command Line”

More About
• “Function Handle Definition for Code Generation” on page 12-2
• “Function Handle Limitations for Code Generation” on page 12-5

12-4
Function Handle Limitations for Code Generation

Function Handle Limitations for Code Generation


Do not use the same bound variable to reference different function handles

In some cases, using the same bound variable to reference different function handles
causes a compile-time error. For example, this code does not compile:
function y = foo(p)
x = @plus;
if p
x = @minus;
end
y = x(1, 2);

Do not pass function handles to or from coder.ceval

You cannot pass function handles as inputs to or outputs from coder.ceval. For
example, suppose that f and str.f are function handles:
f = @sin;
str.x = pi;
str.f = f;

The following statements result in compilation errors:


coder.ceval('foo', @sin);
coder.ceval('foo', f);
coder.ceval('foo', str);

Do not pass function handles to or from extrinsic functions

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 14-12.

Do not pass function handles to or from primary functions

You cannot pass function handles as inputs to or outputs from primary functions. For
example, consider this function:
function x = plotFcn(fhandle, data)

assert(isa(fhandle,'function_handle') && isa(data,'double'));

12-5
12 Code Generation for Function Handles

plot(data, fhandle(data));
x = fhandle(data);

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. The error
indicates 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.

Related Examples
• “Define and Pass Function Handles for Code Generation” on page 12-3

More About
• “Function Handle Definition for Code Generation” on page 12-2

12-6
13

Defining Functions for Code


Generation

• “Specify Variable Numbers of Arguments” on page 13-2


• “Supported Index Expressions” on page 13-3
• “Apply Operations to a Variable Number of Arguments” on page 13-4
• “Implement Wrapper Functions” on page 13-6
• “Variable Length Argument Lists for Code Generation” on page 13-7
13 Defining Functions for Code Generation

Specify Variable Numbers of Arguments


You can use varargin in a function definition to specify that the function accepts a
variable number of input arguments for a given input argument. You can use varargout
in a function definition to specify that the function returns a variable number of
arguments for a given output argument.

When you use varargin and varargout for code generation, there are the following
limitations:

• You cannot use varargout in the function definition for a top-level function.
• You cannot use varargin in the function definition for a top-level function in
a MATLAB Function block in a Simulink model, or in a MATLAB function in a
Stateflow diagram.
• If you use varargin to define an argument to a top-level function, the code
generation software generates the function with a fixed number of arguments. This
fixed number of arguments is based on the number of example arguments that you
provide on the command line or in a MATLAB Coder project test file.

Common applications of varargin and varargout for code generation are to:

• “Apply Operations to a Variable Number of Arguments” on page 13-4


• “Implement Wrapper Functions” on page 13-6
• Pass property/value pairs

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 some uses are not allowed (see “Variable Length Argument Lists for
Code Generation” on page 13-7).

For more information about using varargin and varargout in MATLAB functions, see
Passing Variable Numbers of Arguments.

13-2
Supported Index Expressions

Supported Index Expressions


In MATLAB, varargin and varargout are cell arrays. For code generation, to index
varargin and varargout, you must use a syntax that code generation supports. You
can use the most common syntax — curly braces {}. For example:

%#codegen
function [x,y,z] = fcn(a,b,c)
[x,y,z] = subfcn(a,b,c);

function varargout = subfcn(varargin)


for i = 1:length(varargin)
varargout{i} = varargin{i};
end

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 exp
(read only) 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.

13-3
13 Defining Functions for Code Generation

Apply Operations to a Variable Number of Arguments


You can use varargin and varargout in for-loops to apply operations to a variable
number of arguments. To index into varargin and varargout arrays in generated
code, the value of the loop index variable must be known at compile time. Therefore,
during code generation, the compiler attempts to automatically unroll these for-loops.
Unrolling 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. For example, the following function automatically unrolls its for-loop in the
generated code:
%#codegen
function [cmlen,cmwth,cmhgt] = conv_2_metric(inlen,inwth,inhgt)

[cmlen,cmwth,cmhgt] = inch_2_cm(inlen,inwth,inhgt);

function varargout = inch_2_cm(varargin)


for i = 1:length(varargin)
varargout{i} = varargin{i} * 2.54;
end

When to Force Loop Unrolling


To automatically unroll for-loops containing varargin and varargout expressions,
the relationship between the loop index expression and the index variable must be
determined at compile time.

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);

function varargout = subfcn(varargin)


j = 0;
for i = 1:length(varargin)
j = j+1;
varargout{j} = varargin{j};
end
As a result, the function does not unroll the loop and generates a compilation error:

13-4
Apply Operations to a Variable Number of Arguments

Nonconstant expression or empty matrix.


This expression must be constant because
its value determines the size or class of some expression.

To fix 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);

function varargout = subfcn(varargin)


j = 0;
for i = coder.unroll(1:length(varargin))
j = j + 1;
varargout{j} = varargin{j};
end;

Using Variable Numbers of Arguments in a for-Loop


The following example multiplies a variable number of input dimensions in inches by
2.54 to convert them to centimeters:
%#codegen
function [cmlen,cmwth,cmhgt] = conv_2_metric(inlen,inwth,inhgt)

[cmlen,cmwth,cmhgt] = inch_2_cm(inlen,inwth,inhgt);

function varargout = inch_2_cm(varargin)


for i = 1:length(varargin)
varargout{i} = varargin{i} * 2.54;
end

Key Points About the Example

• varargin and varargout appear in the local function inch_2_cm, not in the top-
level function conv_2_metric.
• The index into varargin and varargout is a for-loop variable

For more information, see “Variable Length Argument Lists for Code Generation” on
page 13-7.

13-5
13 Defining Functions for Code Generation

Implement Wrapper Functions


You can use varargin and varargout to write wrapper functions that accept up to 64
inputs and pass them directly to another function.

Passing Variable Numbers of Arguments from One Function to Another


The following example passes a variable number of inputs to different optimization
functions, based on a specified input method:
%#codegen
function answer = fcn(method,a,b,c)
answer = optimize(method,a,b,c);

function answer = optimize(method,varargin)


if strcmp(method,'simple')
answer = simple_optimization(varargin{:});
else
answer = complex_optimization(varargin{:});
end
...

Key Points About the Example

• 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 “Variable Length Argument Lists for Code Generation” on
page 13-7.

13-6
Variable Length Argument Lists for Code Generation

Variable Length Argument Lists for Code Generation


Use variable length argument lists in top-level functions according to guidelines

When you use varargin and varargout for code generation, there are the following
limitations:

• You cannot use varargout in the function definition for a top-level function.
• You cannot use varargin in the function definition for a top-level function in
a MATLAB Function block in a Simulink model, or in a MATLAB function in a
Stateflow diagram.
• If you use varargin to define an argument to a top-level function, the code
generation software generates the function with a fixed number of arguments. This
fixed number of arguments is based on the number of example arguments that you
provide on the command line or in a MATLAB Coder project test file.

A top-level function is:

• The function called by Simulink in a MATLAB Function block or by Stateflow in a


MATLAB function.
• The function that you provide on the command line to codegen or fiaccel.

For example, the following code generates compilation errors:


%#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. Then call inch_2_cm as an external function or local function, as in this
example:
%#codegen
function [cmL, cmW, cmH] = conv_2_metric(inL, inW, inH)
[cmL, cmW, cmH] = inch_2_cm(inL, inW, inH);

function varargout = inch_2_cm(varargin)


for i = 1:length(varargin)
varargout{i} = varargin{i} * 2.54;
end

13-7
13 Defining Functions for Code Generation

Use curly braces {} to index into the argument list

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 13-3.

Verify that indices can be computed at compile time

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 “Apply Operations
to a Variable Number of Arguments” on page 13-4.

Do not write to varargin

Generated code treats varargin as a read-only variable. If you want to write to input
arguments, copy the values into a local variable.

13-8
14

Calling Functions for Code Generation

• “Resolution of Function Calls for Code Generation” on page 14-2


• “Resolution of File Types on Code Generation Path” on page 14-6
• “Compilation Directive %#codegen” on page 14-8
• “Call Local Functions” on page 14-9
• “Call Supported Toolbox Functions” on page 14-10
• “Call MATLAB Functions” on page 14-11
14 Calling Functions for Code Generation

Resolution of Function Calls for Code Generation


From a MATLAB function, you can call local functions, supported toolbox functions,
and other MATLAB functions. MATLAB resolves function names for code generation as
follows:

14-2
Resolution of Function Calls for Code Generation

Start

Dispatch to Function
Yes on Yes
MATLAB Extrinsic
for execution MATLAB function?
at runtime path?

No No

Yes
Subfunction?

No

Function Yes Yes


on the code Suitable
generation for code
path? generation?

No No
Generate
C code

Function
on Yes
MATLAB
path?

No

Generate error

14-3
14 Calling Functions for Code Generation

Key Points About Resolving Function Calls


The diagram illustrates key points about how MATLAB resolves function calls for code
generation:

• Searches two paths, the code generation path and the MATLAB path

See “Compile Path Search Order” on page 14-4.


• Attempts to compile functions unless the code generation software determines that it
should not compile them or you explicitly declare them to be extrinsic.

If a MATLAB function is not supported for code generation, you can declare it to
be extrinsic by using the construct coder.extrinsic, as described in “Declaring
MATLAB Functions as Extrinsic Functions” on page 14-12. During simulation,
the code generation software generates code for the call to an extrinsic function, but
does not generate the internal code for the function. Therefore, simulation can run
only on platforms where MATLAB software is installed. During standalone code
generation, the code generation software attempts to determine whether the extrinsic
function affects the output of the function in which it is called — for example by
returning mxArrays to an output variable. Provided that the output does not change,
code generation proceeds, but the extrinsic function is excluded from the generated
code. Otherwise, compilation errors occur.

The code generation software detects calls to many common visualization functions,
such as plot, disp, and figure. The software treats these functions like extrinsic
functions but you do not have to declare them extrinsic using the coder.extrinsic
function.
• Resolves file type based on precedence rules described in “Resolution of File Types on
Code Generation Path” on page 14-6

Compile Path Search Order


During code generation, function calls are resolved on two paths:

1 Code generation path

MATLAB searches this path first during code generation. The code generation path
contains the toolbox functions supported for code generation.
2 MATLAB path

14-4
Resolution of Function Calls for Code Generation

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 “Function
Precedence Order”).

When to Use the Code Generation Path


Use the code generation path to override a MATLAB function with a customized version.
A file on the code generation path shadows a file of the same name on the MATLAB path.

14-5
14 Calling Functions for Code Generation

Resolution of File Types on Code Generation Path


MATLAB uses the following precedence rules for code generation:

14-6
Resolution of File Types on Code Generation Path

Start

M-file and Yes


MEX-file in same
directory?

No

Yes
MEX-file?

No

Yes
Generate MDL-file? Compile
error M-file

No

Yes
P-file?

No

No Yes 14-7
M-file?
14 Calling Functions for Code Generation

Compilation Directive %#codegen


Add the %#codegen directive (or pragma) to your function after the function signature
to indicate that you intend to generate code for the MATLAB algorithm. Adding this
directive instructs the MATLAB code analyzer to help you diagnose and fix violations
that would result in errors during code generation.
function y = my_fcn(x) %#codegen

....

14-8
Call Local Functions

Call Local Functions


Local functions 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 local function mean:

function [mean, stdev] = stats(vals)


%#codegen

% Calculates a statistical mean and a standard


% deviation for the values in vals.

len = length(vals);
mean = avg(vals, len);
stdev = sqrt(sum(((vals-avg(vals,len)).^2))/len);
plot(vals,'-+');

function mean = avg(array,size)


mean = sum(array)/size;

14-9
14 Calling Functions for Code Generation

Call Supported Toolbox Functions


You can call toolbox functions directly if they are supported for code generation. For a
list of supported functions, see “Functions and Objects Supported for C and C++ Code
Generation — Alphabetical List” on page 4-2.

14-10
Call MATLAB Functions

Call MATLAB Functions


The code generation software attempts to generate code for functions, even if they
are not supported for C code generation. The software detects calls to many common
visualization functions, such as plot, disp, and figure. The software treats these
functions like extrinsic functions but you do not have to declare them extrinsic using
coder.extrinsic. During simulation, the code generation software generates code
for these functions, but does not generate their internal code. During standalone
code generation, the code generation software attempts to determine whether the
visualization function affects the output of the function in which it is called. Provided
that the output does not change, the code generation software proceeds with code
generation, but excludes the visualization function from the generated code. Otherwise,
compilation errors occur.

For example, you might want to call plot to visualize your results in the MATLAB
environment. If you generate a MEX function from a function that calls plot and then
run the generated MEX function, the code generation software dispatches calls to the
plot function to MATLAB. If you generate a library or executable, the generated code
does not contain calls to the plot function. The code generation report highlights calls
from your MATLAB code to extrinsic functions so that it is easy to determine which
functions are supported only in the MATLAB environment.

For unsupported functions other than common visualization functions, you must declare
the functions to be extrinsic (see “Resolution of Function Calls for Code Generation”
on page 14-2). Extrinsic functions are not compiled, but instead executed in MATLAB
during simulation (see “Resolution of Extrinsic Functions During Simulation” on page
14-16).

There are two ways to declare a function to be extrinsic:

14-11
14 Calling Functions for Code Generation

• Use the coder.extrinsic construct in main functions or local functions (see


“Declaring MATLAB Functions as Extrinsic Functions” on page 14-12).
• Call the function indirectly using feval (see “Calling MATLAB Functions Using
feval” on page 14-16).

Declaring MATLAB Functions as Extrinsic Functions


To declare a MATLAB function to be extrinsic, add the coder.extrinsic construct at
the top of the main function or a local function:

coder.extrinsic('function_name_1', ... , 'function_name_n');

Declaring Extrinsic Functions

The following code declares the MATLAB patch function extrinsic in the local function
create_plot. You do not have to declare axis as extrinsic because axis is one of the
common visualization functions that the code generation software automatically treats as
extrinsic.

function c = pythagoras(a,b,color) %#codegen


% Calculates the hypotenuse of a right triangle
% and displays the triangle.

c = sqrt(a^2 + b^2);
create_plot(a, b, color);

function create_plot(a, b, color)


%Declare patch as extrinsic

coder.extrinsic('patch');

x = [0;a;a];
y = [0;0;b];
patch(x, y, color);
axis('equal');

The code generation software does not generate code for patch and axis, but instead
dispatches them to MATLAB for execution.

To test the function, follow these steps:

14-12
Call MATLAB Functions

1 Convert pythagoras to a MEX function by executing this command at the MATLAB


prompt:

codegen -report pythagoras -args {1, 1, [.3 .3 .3]}


2 Click the link to the code generation report and then, in the report, view the
MATLAB code for create_plot.

The report highlights the patch and axis functions to indicate that they are
supported only within the MATLAB environment.

3 Run the MEX function by executing this command:

pythagoras_mex(3, 4, [1.0 0.0 0.0]);

MATLAB displays a plot of the right triangle as a red patch object:

14-13
14 Calling Functions for Code Generation

When to Use the coder.extrinsic Construct

Use the coder.extrinsic construct to:

• Call MATLAB functions that do not produce output during simulation, without
generating unnecessary code (see “Resolution of Extrinsic Functions During
Simulation” on page 14-16).
• Make your code self-documenting and easier to debug. You can scan the source code
for coder.extrinsic statements to isolate calls to MATLAB functions, which can
potentially create and propagate mxArrays (see “Working with mxArrays” on page
14-17).

14-14
Call MATLAB Functions

• Save typing. With one coder.extrinsic statement, each subsequent function call
is extrinsic, as long as the call and the statement are in the same scope (see “Scope of
Extrinsic Function Declarations” on page 14-15).
• Declare the MATLAB function(s) extrinsic throughout the calling function scope (see
“Scope of Extrinsic Function Declarations” on page 14-15). To narrow the scope,
use feval (see “Calling MATLAB Functions Using feval” on page 14-16).

Rules for Extrinsic Function Declarations


Observe the following rules when declaring functions extrinsic for code generation:

• Declare the function extrinsic before you call it.


• Do not use the extrinsic declaration in conditional statements.

Scope of Extrinsic Function Declarations


The coder.extrinsic construct has function scope. For example, consider the following
code:
function y = foo %#codegen
coder.extrinsic('rat','min');
[N D] = rat(pi);
y = 0;
y = min(N, D);

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:

• Declare the MATLAB function extrinsic in a local function, as in this example:


function y = foo %#codegen
coder.extrinsic('rat');
[N D] = rat(pi);
y = 0;
y = mymin(N, D);

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 local function
mymin.

14-15
14 Calling Functions for Code Generation

• Call the MATLAB function using feval, as described in “Calling MATLAB Functions
Using feval” on page 14-16.

Calling MATLAB Functions Using feval


The function feval is automatically interpreted as an extrinsic function during code
generation. Therefore, you can use feval to conveniently call functions that you want to
execute in the MATLAB environment, rather than compiled to generated code.

Consider the following example:

function y = foo
coder.extrinsic('rat');
[N D] = rat(pi);
y = 0;
y = feval('min', N, D);

Because feval is extrinsic, the statement feval('min', N, D) is evaluated by


MATLAB — not compiled — which has the same result as declaring the function min
extrinsic for just this one call. By contrast, the function rat is extrinsic throughout the
function foo.

Resolution of Extrinsic Functions During Simulation


The code generation software resolves calls to extrinsic functions — functions that do not
support code generation — as follows:

14-16
Call MATLAB Functions

During simulation, the code generation software generates code for the call to an
extrinsic function, but does not generate the internal code for the function. Therefore, you
can run the simulation only on platforms where you install MATLAB software.

During code generation, the code generation software attempts to determine whether the
extrinsic function affects the output of the function in which it is called — for example
by returning mxArrays to an output variable (see “Working with mxArrays” on page
14-17). Provided that the output does not change, code generation proceeds, but the
extrinsic function is excluded from the generated code. Otherwise, the code generation
software issues a compiler error.

Working with mxArrays


The output of an extrinsic function is an mxArray — also called a MATLAB array. The
only valid operations for mxArrays are:

• Storing mxArrays in variables

14-17
14 Calling Functions for Code Generation

• Passing mxArrays to functions and returning them from functions


• Converting mxArrays to known types at run time

To use mxArrays returned by extrinsic functions in other operations, you must first
convert them to known types, as described in “Converting mxArrays to Known Types” on
page 14-18.

Converting mxArrays to Known Types

To convert an mxArray to a known type, assign the mxArray to a variable whose type is
defined. At run time, the mxArray is converted to the type of the variable assigned to it.
However, if the data in the mxArray is not consistent with the type of the variable, you
get a run-time error.

For example, consider this code:

function y = foo %#codegen


coder.extrinsic('rat');
[N D] = rat(pi);
y = min(N, D);

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.

If you run this function foo in a MATLAB Function block in a Simulink model, the code
generates the following error during simulation:

Function output 'y' cannot be of MATLAB type.

To fix 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:

function y = foo %#codegen


coder.extrinsic('rat');
[N D] = rat(pi);
y = 0; % Define y as a scalar of type double
y = min(N,D);

14-18
Call MATLAB Functions

Restrictions on Extrinsic Functions for Code Generation


The full MATLAB run-time environment is not supported during code generation.
Therefore, the following restrictions apply when calling MATLAB functions extrinsically:

• MATLAB functions that inspect the caller, or read or write to the caller workspace do
not work during code generation. Such functions include:

• dbstack
• evalin
• assignin
• save
• The MATLAB debugger cannot inspect variables defined in extrinsic functions.
• Functions in generated code can produce unpredictable results if your extrinsic
function performs 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

Limit on Function Arguments


You can call functions with up to 64 inputs and 64 outputs.

14-19
15

Fixed-Point Conversion

• “Detect Dead and Constant-Folded Code” on page 15-2


• “Convert MATLAB Code to Fixed-Point C Code” on page 15-7
• “Propose Fixed-Point Data Types Based on Simulation Ranges” on page 15-9
• “Propose Fixed-Point Data Types Based on Derived Ranges” on page 15-23
• “Specify Type Proposal Options” on page 15-36
• “Detect Overflows” on page 15-40
• “Replace the exp Function with a Lookup Table” on page 15-50
• “Replace a Custom Function with a Lookup Table” on page 15-59
• “Enable Plotting Using the Simulation Data Inspector” on page 15-68
• “Visualize Differences Between Floating-Point and Fixed-Point Results” on page
15-69
• “Log Data for Histogram” on page 15-80
• “View and Modify Variable Information” on page 15-82
• “Automated Fixed-Point Conversion” on page 15-86
• “Convert Fixed-Point Conversion Project to MATLAB Scripts” on page 15-107
• “Generated Fixed-Point Code” on page 15-110
• “Fixed-Point Code for MATLAB Classes” on page 15-116
• “Automated Fixed-Point Conversion Best Practices” on page 15-119
• “Replacing Functions Using Lookup Table Approximations” on page 15-127
• “MATLAB Language Features Supported for Automated Fixed-Point Conversion” on
page 15-128
• “Inspecting Data Using the Simulation Data Inspector” on page 15-130
• “Custom Plot Functions” on page 15-133
• “Data Type Issues in Generated Code” on page 15-135
15 Fixed-Point Conversion

Detect Dead and Constant-Folded Code


During the simulation of your test file, the MATLAB Coder app detects dead code or code
that is constant folded. The app uses the code coverage information when translating
your code from floating-point MATLAB code to fixed-point MATLAB code. Reviewing
code coverage results helps you to verify that your test file is exercising the algorithm
adequately.

The app inserts inline comments in the fixed-point code to mark the dead and
untranslated regions. It includes the code coverage information in the generated fixed-
point conversion HTML report. The app editor displays a color-coded bar to the left of the
code. This table describes the color coding.

Coverage Bar Indicates


Color
Green One of the following situations:

• The entry-point function executes multiple times and the code


executes more than one time.
• The entry-point function executes one time and the code executes
one time.

Different shades of green indicate different ranges of line execution


counts. The darkest shade of green indicates the highest range.
Orange The entry-point function executes multiple times, but the code
executes one time.
Red Code does not execute.

What Is Dead Code?


Dead code is code that does not execute during simulation. Dead code can result from
these scenarios:

• Defensive code containing intended corner cases that are not reached
• Human error in the code, resulting in code that cannot be reached by any execution
path
• Inadequate test bench range

15-2
Detect Dead and Constant-Folded Code

• Constant folding

Detect Dead Code


This example shows how to detect dead code in your algorithm by using the MATLAB
Coder app.

1 In a local writable folder, create the function myFunction.m.

function y = myFunction(u,v)
%#codegen
for i = 1:length(u)
if u(i) > v(i)
y=bar(u,v);
else
tmp = u;
v = tmp;
y = baz(u,v);
end
end
end

function y = bar(u,v)
y = u+v;
end

function y = baz(u,v)
y = u-v;
end
2 In the same folder, create a test file, myFunction_tb.

u = 1:100;
v = 101:200;

myFunction(u,v);
3 From the apps gallery, open the MATLAB Coder app.
4 Set Numeric Conversion to Convert to fixed point.
5 On the Select Source Files page, browse to the myFunction file, and click Open.
6 Click Next. On the Define Input Types page, browse to select the test file that you
created, myFunction_tb. Click Autodefine Input Types.
7 Click Next. On the Check for Run-Time Issues page, click Check for Issues.

The app runs the myFunction_tb test file and detects no issues.

15-3
15 Fixed-Point Conversion

8 Click Next. On the Convert to Fixed-Point page, click Simulate to simulate the
entry-point functions, gather range information, and get proposed data types.

The color-coded bar on the left side of the edit window indicates whether the code
executes. The code in the first condition of the if-statement does not execute during
simulation because u is never greater than v. The bar function never executes
because the if-statement never executes. These parts of the algorithm are marked
with a red bar, indicating that they are dead code.

9 To apply the proposed data types to the function, click Convert .

The MATLAB Coder app generates a fixed-point function, myFunction_fixpt. The


generated fixed-point code contains comments around the pieces of code identified
as dead code. The Validation Results pane proposes that you use a more thorough
test bench.
15-4
Detect Dead and Constant-Folded Code

When the MATLAB Coder app detects dead code, consider editing your test file so
that your algorithm is exercised over its full range. If your test file already reflects
the full range of the input variables, consider editing your algorithm to eliminate the
dead code.
10 Close the MATLAB Coder app.

Fix Dead Code


1 Edit the test file myFunction_tb.m to include a wider range of inputs.

u = 1:100;
v = -50:2:149;

15-5
15 Fixed-Point Conversion

myFunction(u,v);
2 Reopen the MATLAB Coder app.
3 Using the same function and the edited test file, go through the conversion process
again.
4 After you click Simulate, this time the code coverage bar shows that all parts of the
algorithm execute with the new test file input ranges.

To finish the conversion process and convert the function to fixed point, click
Convert.

15-6
Convert MATLAB Code to Fixed-Point C Code

Convert MATLAB Code to Fixed-Point C Code


To convert MATLAB Code to fixed-point C Code using the MATLAB Coder app:

1 Open the MATLAB Coder app.


2 Set Fixed-Point Conversion to Enabled.
3 On the Select Source Files page, add the entry-point function from which you want
to generate code.
4 Click Next to go to the Define Input Types step. The app analyzes the function for
coding issues and code generation readiness. If the app identifies issues, it opens the
Review Code Generation Readiness page where you can review and fix issues. If
the app does not find issues, it opens the Define Input Types page.
5 On the Define Input Types page, specify a test file that the app can use to define
the input types.
6 Click Next to go to the Check for Run-Time Issues step.
7 On the Check for Run-Time Issues page, specify a test file that calls your entry-
point function. Alternatively, at the prompt, enter code that calls your entry-point
function. The app generates instrumented MEX. It runs the test file or code that
you specified, replacing calls to your entry-point function with calls to the generated
MEX function. If the app finds issues, it provides warning and error messages. Click
a message to highlight the problematic code in a window where you can edit the
code.
8 Click Next to go to the Convert to Fixed Point step.
9 Propose data types based on simulation range data, derived (also known as static)
range data, or both. See “Propose Fixed-Point Data Types Based on Simulation
Ranges” on page 15-9 and “Propose Fixed-Point Data Types Based on Derived
Ranges” on page 15-23.
10 To convert the floating-point MATLAB code to fixed-point MATLAB code, click
Convert. During fixed-point conversion, the app validates the build using the
proposed fixed-point data types. See “Validating Types” on page 15-105.
11 Verify the behavior of the fixed-point MATLAB code. See “Testing Numerics” on page
15-105.
12 Click Next to go to the Generate Code step.
13 In the Generate dialog box, set Build source to Fixed-Point. Set the Build
type to build a static or dynamic library, or executable. Set Language to C. Click
Generate.

15-7
15 Fixed-Point Conversion

MATLAB Coder generates fixed-point C code for your entry-point MATLAB function.

Related Examples
• “Propose Fixed-Point Data Types Based on Simulation Ranges” on page 15-9
• “Propose Fixed-Point Data Types Based on Derived Ranges” on page 15-23

15-8
Propose Fixed-Point Data Types Based on Simulation Ranges

Propose Fixed-Point Data Types Based on Simulation Ranges


This example shows how to propose fixed-point data types based on simulation range
data using the MATLAB Coder app.

Prerequisites

This example requires the following products:

• MATLAB
• MATLAB Coder
• Fixed-Point Designer
• C compiler (for most platforms, a default C compiler is supplied with MATLAB). See
http://www.mathworks.com/support/compilers/current_release/

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

Create a New Folder and Copy Relevant Files

1 Create a local working folder, for example, c:\ex_2ndOrder_filter.


2 Change to the docroot\toolbox\fixpoint\examples folder. At the MATLAB
command line, enter:
cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples'))
3 Copy the ex_2ndOrder_filter.m and ex_2ndOrder_filter_test.m files to
your local working folder.

Type Name Description


Function code ex_2ndOrder_filter.m Entry-point MATLAB function
Test file ex_2ndOrder_filter_test.m MATLAB script that tests
ex_2ndOrder_filter.m

The ex_2ndOrder_filter Function


function y = ex_2ndOrder_filter(x) %#codegen
persistent z
if isempty(z)
z = zeros(2,1);
end
% [b,a] = butter(2, 0.25)

15-9
15 Fixed-Point Conversion

b = [0.0976310729378175, 0.195262145875635, 0.0976310729378175];


a = [1, -0.942809041582063, 0.3333333333333333];

y = zeros(size(x));
for i = 1:length(x)
y(i) = b(1)*x(i) + z(1);
z(1) = b(2)*x(i) + z(2) - a(2) * y(i);
z(2) = b(3)*x(i) - a(3) * y(i);
end
end

The ex_2ndOrder_filter_test Script

The test script runs the ex_2ndOrder_filter function with three input signals: chirp,
step, and impulse to cover the full intended operating range of the system. The script
then plots the outputs.
% ex_2ndOrder_filter_test
%
% Define representative inputs
N = 256; % Number of points
t = linspace(0,1,N); % Time vector from 0 to 1 second
f1 = N/2; % Target frequency of chirp set to Nyquist
x_chirp = sin(pi*f1*t.^2); % Linear chirp from 0 to Fs/2 Hz in 1 second
x_step = ones(1,N); % Step
x_impulse = zeros(1,N); % Impulse
x_impulse(1) = 1;

% Run the function under test


x = [x_chirp;x_step;x_impulse];
y = zeros(size(x));
for i = 1:size(x,1)
y(i,:) = ex_2ndOrder_filter(x(i,:));
end

% Plot the results


titles = {'Chirp','Step','Impulse'}
clf
for i = 1:size(x,1)
subplot(size(x,1),1,i)
plot(t,x(i,:),t,y(i,:))
title(titles{i})
legend('Input','Output')
end

15-10
Propose Fixed-Point Data Types Based on Simulation Ranges

xlabel('Time (s)')
figure(gcf)

disp('Test complete.')

Open the MATLAB Coder App

1 Navigate to the work folder that contains the file for this example.
2 On the MATLAB Toolstrip Apps tab, under Code Generation, click the app icon.

Enable Fixed-Point Conversion

Set Numeric Conversion to Convert to fixed point.

15-11
15 Fixed-Point Conversion

Select Source Files

1 To add the entry-point function ex_2ndOrder_filter to the project, browse


to the file ex_2ndOrder_filter.m, and then click Open. By default, the app
saves information and settings for this project in the current folder in a file named
ex_2ndOrder_filter.prj.
2 Click Next to go to the Define Input Types step.

The app screens ex_2ndOrder_filter.m for code violations and code generation
readiness issues. The app does not find issues in ex_2ndOrder_filter.m.

Define Input Types

1 On the Define Input Types page, to add ex_2ndOrder_filter_test as a test


file, browse to ex_2ndOrder_filter_test, and then click Open.
2 Click Autodefine Input Types.

The test file runs and displays the outputs of the filter for each of the input signals.

15-12
Propose Fixed-Point Data Types Based on Simulation Ranges

The app determines from the test file that the input type of x is double(1x256).

15-13
15 Fixed-Point Conversion

3 Click Next to go to the Check for Run-Time Issues step.

Check for Run-Time Issues

The Check for Run-Time Issues step generates instrumented MEX. It runs the test
file ex_2ndOrder_filter_test replacing calls to ex_2ndOrder_filter with calls
to the generated MEX function. If the app finds issues, it provides warning and error
messages. You can click a message to highlight the problematic code in a window where
you can edit the code.

1 On the Check for Run-Time Issues page, the app populates the test file field with
ex_2ndOrder_filter_test, the test file that you used to define the input types.
2 Click Check for Issues.

The app does not detect issues.


3 Click Next to go to the Convert to Fixed Point step.

Convert to Fixed Point

1 The app displays compiled information—type, size, and complexity—for variables in


your code. See “View and Modify Variable Information” on page 15-82.

15-14
Propose Fixed-Point Data Types Based on Simulation Ranges

On the Function Replacements tab, the app displays functions that are not
supported for fixed-point conversion. See “Running a Simulation” on page 15-91.
2
Click the Simulate arrow . Verify that the test file is
ex_2ndOrder_filter_test. You can add test files and select to run more than
one test file during the simulation. If you run multiple test files, the app merges the
simulation results.

3 Select Log data for histogram.

15-15
15 Fixed-Point Conversion

By default, the Show code coverage option is selected. This option provides
code coverage information that helps you verify that your test file is testing your
algorithm over the intended operating range.
4 Click Simulate.

The simulation runs and the app displays a color-coded code coverage bar to the left
of the MATLAB code. Review this information to verify that the test file is testing
the algorithm adequately. The dark green line to the left of the code indicates that
the code runs every time the algorithm executes. The orange bar indicates that the
code next to it executes only once. This behavior is expected for this example because
the code initializes a persistent variable. If your test file does not cover all of your
code, update the test or add more test files.

15-16
Propose Fixed-Point Data Types Based on Simulation Ranges

If a value has ... next to it, the value is rounded. Place your cursor over the ... to
view the actual value.

The app displays simulation minimum and maximum ranges on the Variables
tab. Using the simulation range data, the software proposes fixed-point types for
each variable based on the default type proposal settings, and displays them in the
Proposed Type column. The app enables the Convert option.

Note: You can manually enter static ranges. These manually entered ranges take
precedence over simulation ranges. The app uses the manually entered ranges to
propose data types. You can also modify and lock the proposed type.

15-17
15 Fixed-Point Conversion

5 Examine the proposed types and verify that they cover the full simulation range. To
view logged histogram data for a variable, click its Proposed Type field.

To modify the proposed data types, either enter the required type into the Proposed
Type field or use the histogram controls. For more information about the histogram,
see “Log Data for Histogram” on page 15-102.
6 To convert the floating-point algorithm to fixed point, click Convert.

During the fixed-point conversion process, the software validates the proposed types
and generates the following files in the codegen\ex_2ndOrder_filter\fixpt
folder in your local working folder.

• ex_2ndOrder_filter_fixpt.m — the fixed-point version of


ex_2ndOrder_filter.m.
• ex_2ndOrder_filter_wrapper_fixpt.m — this file converts the floating-
point data values supplied by the test file to the fixed-point types determined for
the inputs during conversion. These fixed-point values are fed into the converted
fixed-point design, ex_2ndOrder_filter_fixpt.m.
• ex_2ndOrder_filter_fixpt_report.html — this report shows the generated
fixed-point code and the fixed-point instrumentation results.
• ex_2ndOrder_filter_report.html — this report shows the original
algorithm and the fixed-point instrumentation results.

15-18
Propose Fixed-Point Data Types Based on Simulation Ranges

• ex_2ndOrder_filter_fixpt_args.mat — MAT-file containing a structure for


the input arguments, a structure for the output arguments and the name of the
fixed-point file.

If errors or warnings occur during validation, you see them on the Type Validation
Output tab. See “Validating Types” on page 15-105.
7 In the Output Files list, select ex_2ndOrder_filter_fixpt.m. The app displays
the generated fixed-point code.

8
Click the Test arrow . Select Log inputs and outputs for comparison plots,
and then click Test.

15-19
15 Fixed-Point Conversion

To test the fixed-point MATLAB code, the app runs the test file that you used to
define input types. Optionally, you can add test files and select to run more than
one test file to test numerics. The software runs both a floating-point and a fixed-
point simulation and then calculates the errors for the output variable y. Because
you selected to log inputs and outputs for comparison plots, the app generates a plot
for each input and output. The app docks these plots in a single figure window.

The app also reports error information on the Verification Output tab. The
maximum error is less than 0.03%. For this example, this margin of error is
acceptable.

15-20
Propose Fixed-Point Data Types Based on Simulation Ranges

If the difference is not acceptable, modify the fixed-point data types or your original
algorithm. For more information, see “Testing Numerics” on page 15-105.
9 On the Verification Output tab, the app provides a link to a type proposal
report. The report displays the generated fixed-point code and the proposed type
information.

10 Click Next to go to the Generate Code page.

Generate Fixed-Point C Code

1 In the Generate dialog box, set Build source to Fixed-Point and Build type to
Static Library.
2 Set Language to C.

15-21
15 Fixed-Point Conversion

3 Click Generate to generate a library using the default project settings.

MATLAB Coder builds the project and generates a C static library and supporting
files in the default subfolder, codegen/lib/ex_2ndOrder_filter.
4 The app displays the generated code for ex_2ndOrder_filter.c. In the generated
C code, variables are assigned fixed-point data types.
5 Click Next to go to the Finish Workflow page.

On the Finish Workflow page, the app displays a project summary and links to
generated output files.

15-22
Propose Fixed-Point Data Types Based on Derived Ranges

Propose Fixed-Point Data Types Based on Derived Ranges


This example shows how to propose fixed-point data types based on static ranges using
the MATLAB Coder app. When you propose data types based on derived ranges you, do
not have to provide test files that exercise your algorithm over its full operating range.
Running such test files often takes a long time. You can save time by deriving ranges
instead.

Prerequisites

This example requires the following products:

• MATLAB
• MATLAB Coder
• Fixed-Point Designer
• C compiler (for most platforms, a default C compiler is supplied with MATLAB). See
http://www.mathworks.com/support/compilers/current_release/.

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

Create a New Folder and Copy Relevant Files

1 Create a local working folder, for example, c:\dti.


2 Change to the docroot\toolbox\fixpoint\examples folder. At the MATLAB
command line, enter:
cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples'))
3 Copy the dti.m and dti_test.m files to your local working folder.

Type Name Description


Function code dti.m Entry-point MATLAB function
Test file dti_test.m MATLAB script that tests
dti.m

The dti Function

The dti function implements a Discrete Time Integrator in MATLAB.


function [y, clip_status] = dti(u_in) %#codegen

15-23
15 Fixed-Point Conversion

% Discrete Time Integrator in MATLAB


%
% Forward Euler method, also known as Forward Rectangular, or left-hand
% approximation. The resulting expression for the output of the block at
% step 'n' is y(n) = y(n-1) + K * u(n-1)
%
init_val = 1;
gain_val = 1;
limit_upper = 500;
limit_lower = -500;

% variable to hold state between consecutive calls to this block


persistent u_state;
if isempty(u_state)
u_state = init_val+1;
end

% Compute Output
if (u_state > limit_upper)
y = limit_upper;
clip_status = -2;
elseif (u_state >= limit_upper)
y = limit_upper;
clip_status = -1;
elseif (u_state < limit_lower)
y = limit_lower;
clip_status = 2;
elseif (u_state <= limit_lower)
y = limit_lower;
clip_status = 1;
else
y = u_state;
clip_status = 0;
end

% Update State
tprod = gain_val * u_in;
u_state = y + tprod;

The dti_test Function

The test script runs the dti function with a sine wave input. The script then plots the
input and output signals.
% dti_test

15-24
Propose Fixed-Point Data Types Based on Derived Ranges

% cleanup
clear dti

% input signal
x_in = sin(2.*pi.*(0:0.001:2)).';

pause(10);

len = length(x_in);
y_out = zeros(1,len);
is_clipped_out = zeros(1,len);

for ii=1:len
data = x_in(ii);
% call to the dti function
init_val = 0;
gain_val = 1;
upper_limit = 500;
lower_limit = -500;

% call to the design that does DTI


[y_out(ii), is_clipped_out(ii)] = dti(data);

end

figure('Name', [mfilename, '_plot']);


subplot(2,1,1)
plot(1:len,x_in)
xlabel('Time')
ylabel('Amplitude')
title('Input Signal (Sin)')

subplot(2,1,2)
plot(1:len,y_out)
xlabel('Time')
ylabel('Amplitude')
title('Output Signal (DTI)')

disp('Test complete.');

Open the MATLAB Coder App

1 Navigate to the work folder that contains the file for this example.
2 On the MATLAB Toolstrip Apps tab, under Code Generation, click the app icon.

15-25
15 Fixed-Point Conversion

Enable Fixed-Point Conversion

Set Numeric Conversion to Convert to fixed point.

Select Source Files

1 To add the entry-point function dti to the project, browse to the file dti.m, and then
click Open. By default, the app saves information and settings for this project in the
current folder in a file named dti.prj.
2 Click Next to go to the Define Input Types step.

The app screens dti.m for code violations and code generation readiness issues. The
app does not find issues in dti.m.

15-26
Propose Fixed-Point Data Types Based on Derived Ranges

Define Input Types

1 On the Define Input Types page, to add dti_test as a test file, browse to
dti_test.m, and then click Open.
2 Click Autodefine Input Types.

The test file runs. The app determines from the test file that the input type of u_in
is double(1x1).

3 Click Next to go to the Check for Run-Time Issues step.

Check for Run-Time Issues

The Check for Run-Time Issues step generates instrumented MEX. It runs the test
file dti_test replacing calls to dti with calls to the generated MEX function. If the
app finds issues, it provides warning and error messages. You can click a message to
highlight the problematic code in a window where you can edit the code.

1 On the Check for Run-Time Issues page, the app populates the test file field with
dti_test, the test file that you used to define the input types.
2 Click Check for Issues.

The app does not detect issues.


3 Click Next to go to the Convert to Fixed Point step.

15-27
15 Fixed-Point Conversion

Convert to Fixed Point

1 The app displays compiled information—type, size, and complexity—for variables


in your code. For more information, see “View and Modify Variable Information” on
page 15-82.

If functions are not supported for fixed-point conversion, the app displays them on
the Function Replacements tab.
2 On the Convert to Fixed Point page, on the Variables tab, for input u_in, select
Static Min and set it to -1. Set Static Max to 1.

To compute derived range information, at a minimum you must specify static


minimum and maximum values or proposed data types for all input variables.

15-28
Propose Fixed-Point Data Types Based on Derived Ranges

Note: If you manually enter static ranges, these manually entered ranges take
precedence over simulation ranges. The app uses the manually entered ranges to
propose data types. You can also modify and lock the proposed type.
3 Click Derive.

Range analysis computes the derived ranges and displays them in the Variables
tab. Using these derived ranges, the analysis proposes fixed-point types for each
variable based on the default type proposal settings. The app displays them in the
Proposed Type column.

In the dti function, the clip_status output has a minimum value of -2 and a
maximum of 2.

% Compute Output
if (u_state > limit_upper)
y = limit_upper;
clip_status = -2;
elseif (u_state >= limit_upper)
y = limit_upper;
clip_status = -1;
elseif (u_state < limit_lower)
y = limit_lower;
clip_status = 2;
elseif (u_state <= limit_lower)
y = limit_lower;
clip_status = 1;
else
y = u_state;
clip_status = 0;
end

When you derive ranges, the app analyzes the function and computes these
minimum and maximum values for clip_status.

15-29
15 Fixed-Point Conversion

The app provides a Quick derived range analysis option and the option to specify
a timeout in case the analysis takes a long time. See “Computing Derived Ranges” on
page 15-92.
4 To convert the floating-point algorithm to fixed point, click Convert.

During the fixed-point conversion process, the software validates the proposed types
and generates the following files in the codegen\dti\fixpt folder in your local
working folder:

• dti_fixpt.m — the fixed-point version of dti.m.

15-30
Propose Fixed-Point Data Types Based on Derived Ranges

• dti_wrapper_fixpt.m — this file converts the floating-point data values


supplied by the test file to the fixed-point types determined for the inputs during
conversion. The app feeds these fixed-point values into the converted fixed-point
design, dti_fixpt.m.
• dti_fixpt_report.html — this report shows the generated fixed-point code
and the fixed-point instrumentation results.
• dti_report.html — this report shows the original algorithm and the fixed-
point instrumentation results.
• dti_fixpt_args.mat — MAT-file containing a structure for the input
arguments, a structure for the output arguments and the name of the fixed-point
file.

If errors or warnings occur during validation, they show on the Type Validation
Output tab. See “Validating Types” on page 15-105.
5 In the Output Files list, select dti_fixpt.m. The app displays the generated fixed-
point code.
6 Use the Simulation Data Inspector to plot the floating-point and fixed-point results.

a
Click the Settings arrow .
b Expand the Plotting and Reporting settings and set Plot with Simulation
Data Inspector to Yes.

c
Click the Test arrow . Select Log inputs and outputs for comparison
plots. Click Test.

15-31
15 Fixed-Point Conversion

The app runs the test file that you used to define input types to test the fixed-
point MATLAB code. Optionally, you can add test files and select to run more
than one test file to test numerics. The software runs both a floating-point and
a fixed-point simulation and then calculates the errors for the output variable y.
Because you selected to log inputs and outputs for comparison plots and to use
the Simulation Data Inspector for these plots, the Simulation Data Inspector
opens.

d You can use the Simulation Data Inspector to view floating-point and fixed-point
run information and compare results. For example, to compare the floating-point

15-32
Propose Fixed-Point Data Types Based on Derived Ranges

and fixed-point values for the output y, on the Compare tab, select y. Select
Runs and then click Compare.

The Simulation Data Inspector displays a plot of the baseline floating-point run
against the fixed-point run and the difference between them.

7 On the Verification Output tab, the app provides a link to a type proposal report.

15-33
15 Fixed-Point Conversion

To open the report, click the dti_fixpt_report.html link.

15-34
Propose Fixed-Point Data Types Based on Derived Ranges

8 Click Next to go to the Generate Code step.

Generate Fixed-Point C Code

1 In the Generate dialog box, set Build source to Fixed-Point and Build type to
Source Code.
2 Set Language to C.
3 Click Generate to generate a library using the default project settings.

MATLAB Coder builds the project and generates a C static library and supporting
files in the default subfolder, codegen/lib/dti_fixpt.
4 The app displays the generated code for dti_fixpt.c. In the generated C code,
variables are assigned fixed-point data types.
5 Click Next to go to the Finish Workflow page.

On the Finish Workflow page, the app displays a project summary and links to
generated output files.

15-35
15 Fixed-Point Conversion

Specify Type Proposal Options


To view type proposal options, in the MATLAB Coder app, on the Convert to Fixed
Point page, click the Settings arrow .

The following options are available.

Basic Type Proposal Settings Values Description


Fixed-point type proposal Propose fraction lengths for Use the specified word
mode specified word length length for data type
proposals and propose the
minimum fraction lengths to
avoid overflows.
Propose word lengths for Use the specified fraction
specified fraction length length for data type
(default) proposals and propose the
minimum word lengths to
avoid overflows.
Default word length 16 (default) Default word length to
use when Fixed-point
type proposal mode is
set to Propose fraction
lengths for specified
word lengths
Default fraction length 4 (default) Default fraction length to
use when Fixed-point type
proposal mode is set to
Propose word lengths
for specified fraction
lengths

Advanced Type Proposal Settings Values Description


When proposing types ignore simulation Propose data types based on
ranges derived ranges.
ignore derived Propose data types based on
Note: Manually-entered static ranges
ranges simulation ranges.
always take precedence over simulation
ranges.

15-36
Specify Type Proposal Options

Advanced Type Proposal Settings Values Description


use all collected data Propose data types based on both
(default) simulation and derived ranges.
Propose target container types Yes Propose data type with the smallest
word length that can represent the
range and is suitable for C code
generation ( 8,16,32, 64 … ). For
example, for a variable with range
[0..7], propose a word length of 8
rather than 3.
No (default) Propose data types with the
minimum word length needed to
represent the value.
Optimize whole numbers No Do not use integer scaling for
variables that were whole numbers
during simulation.
Yes (default) Use integer scaling for variables
that were whole numbers during
simulation.
Signedness Automatic (default) Proposes signed and unsigned
data types depending on the range
information for each variable.
Signed Propose signed data types.
Unsigned Propose unsigned data types.

15-37
15 Fixed-Point Conversion

Advanced Type Proposal Settings Values Description


Safety margin for sim min/max (%) 0 (default) Specify safety factor for simulation
minimum and maximum values.

The simulation minimum and


maximum values are adjusted
by the percentage designated by
this parameter, allowing you to
specify a range different from that
obtained from the simulation run.
For example, a value of 55 specifies
that you want a range at least
55 percent larger. A value of -15
specifies that a range up to 15
percent smaller is acceptable.

fimath Settings Values Description


Rounding method Ceiling Specify the fimath
Convergent properties for the generated
fixed-point data types.
Floor (default)
Nearest The default fixed-point
math properties use the
Round Floor rounding and Wrap
Zero overflow because they are
Overflow action Saturate the default actions in C.
These settings generate
Wrap (default) the most efficient code but
Product mode FullPrecision (default) might cause problems with
overflow.
KeepLSB
KeepMSB After code generation, if
required, modify these
SpecifyPrecision
settings to optimize the
Sum mode FullPrecision (default) generated code, or example,
KeepLSB avoid overflow or eliminate
bias, and then rerun the
KeepMSB
verification.
SpecifyPrecision

15-38
Specify Type Proposal Options

fimath Settings Values Description


For more information on
fimath properties, see
“fimath Object Properties”.

Generated File Settings Value Description


Generated fixed-point file _fixpt (default) Specify the suffix to add to
name suffix the generated fixed-point
file names. For example, by
default, if you generate a
static library for a project
named test, the generated
files are in the subfolder
codegen\lib\test_fixpt.
The generated static library
is named test.lib, but
the generated C code files
use the suffix, for example,
test_fixpt.c.

Plotting and Reporting Values Description


Settings
Custom plot function Empty string Specify the name of a custom
plot function to use for
comparison plots.
Plot with Simulation Data No (default) Specify whether to use the
Inspector Yes Simulation Data Inspector
for comparison plots.
Highlight potential data No (default) Specify whether to highlight
type issues Yes potential data types in the
generated html report. If
this option is turned on, the
report highlights single-
precision, double-precision,
and expensive fixed-point
operation usage in your
MATLAB code.

15-39
15 Fixed-Point Conversion

Detect Overflows
This example shows how to detect overflows using the MATLAB Coder app. At the
numerical testing stage in the conversion process, you choose to simulate the fixed-point
code using scaled doubles. The app then reports which expressions in the generated code
produce values that overflow the fixed-point data type.

Prerequisites
This example requires the following products:

• MATLAB
• MATLAB Coder
• Fixed-Point Designer
• C compiler (for most platforms, a default C compiler is supplied with MATLAB) See
http://www.mathworks.com/support/compilers/current_release/.

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

Create a New Folder and Copy Relevant Files

1 Create a local working folder, for example, c:\overflow.


2 Change to the docroot\toolbox\fixpoint\examples folder. At the MATLAB
command line, enter:
cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples'))
3 Copy the overflow.m and overflow_test.m files to your local working folder.
Type Name Description
Function code overflow.m Entry-point MATLAB function
Test file overflow_test.m MATLAB script that tests
overflow.m

The overflow Function


function y = overflow(b,x,reset)
if nargin<3, reset = true; end
persistent z p
if isempty(z) || reset
p = 0;

15-40
Detect Overflows

z = zeros(size(b));
end
[y,z,p] = fir_filter(b,x,z,p);
end
function [y,z,p] = fir_filter(b,x,z,p)
y = zeros(size(x));
nx = length(x);
nb = length(b);
for n = 1:nx
p=p+1; if p>nb, p=1; end
z(p) = x(n);
acc = 0;
k = p;
for j=1:nb
acc = acc + b(j)*z(k);
k=k-1; if k<1, k=nb; end
end
y(n) = acc;
end
end

The overflow_test Function

You use this test file to define input types for b, x, and reset, and, later, to verify the
fixed-point version of the algorithm.
function overflow_test
% The filter coefficients were computed using the FIR1 function from
% Signal Processing Toolbox.
% b = fir1(11,0.25);
b = [-0.004465461051254
-0.004324228005260
+0.012676739550326
+0.074351188907780
+0.172173206073645
+0.249588554524763
+0.249588554524763
+0.172173206073645
+0.074351188907780
+0.012676739550326
-0.004324228005260
-0.004465461051254]';

% Input signal
nx = 256;

15-41
15 Fixed-Point Conversion

t = linspace(0,10*pi,nx)';

% Impulse
x_impulse = zeros(nx,1); x_impulse(1) = 1;

% Max Gain
% The maximum gain of a filter will occur when the inputs line up with the
% signs of the filter's impulse response.
x_max_gain = sign(b)';
x_max_gain = repmat(x_max_gain,ceil(nx/length(b)),1);
x_max_gain = x_max_gain(1:nx);

% Sums of sines
f0=0.1; f1=2;
x_sines = sin(2*pi*t*f0) + 0.1*sin(2*pi*t*f1);

% Chirp
f_chirp = 1/16; % Target frequency
x_chirp = sin(pi*f_chirp*t.^2); % Linear chirp

x = [x_impulse, x_max_gain, x_sines, x_chirp];


titles = {'Impulse', 'Max gain', 'Sum of sines', 'Chirp'};
y = zeros(size(x));

for i=1:size(x,2)
reset = true;
y(:,i) = overflow(b,x(:,i),reset);
end

test_plot(1,titles,t,x,y)

end
function test_plot(fig,titles,t,x,y1)
figure(fig)
clf
sub_plot = 1;
font_size = 10;
for i=1:size(x,2)
subplot(4,1,sub_plot)
sub_plot = sub_plot+1;
plot(t,x(:,i),'c',t,y1(:,i),'k')
axis('tight')
xlabel('t','FontSize',font_size);

15-42
Detect Overflows

title(titles{i},'FontSize',font_size);
ax = gca;
ax.FontSize = 10;
end
figure(gcf)
end

Open the MATLAB Coder App

1 Navigate to the work folder that contains the file for this example.
2 On the MATLAB Toolstrip Apps tab, under Code Generation, click the app icon.

Enable Fixed-Point Conversion

Set Numeric Conversion to Convert to fixed point.

15-43
15 Fixed-Point Conversion

Select Source Files

1 To add the entry-point function overflow to the project, browse to the file
overflow.m, and then click Open. By default, the app saves information and
settings for this project in the current folder in a file named overflow.prj.
2 Click Next to go to the Define Input Types step.

The app screens overflow.m for code violations and code generation readiness
issues. The app does not find issues in overflow.m.

15-44
Detect Overflows

Define Input Types

1 On the Define Input Types page, to add overflow_test as a test file, browse to
overflow_test.m, and then click Open.
2 Click Autodefine Input Types.

The test file runs. The app determines from the test file that the input type of b is
double(1x12), x is double(256x1), and reset is logical(1x1).

3 Click Next to go to the Check for Run-Time Issues step.

Check for Run-Time Issues

The Check for Run-Time Issues step generates instrumented MEX. It runs the test
file overflow_test replacing calls to overflow with calls to the generated MEX
function. If the app finds issues, it provides warning and error messages. You can click a
message to highlight the problematic code in a pane where you can edit the code.

1 On the Check for Run-Time Issues page, the app populates the test file field with
overflow_test, the test file that you used to define the input types.
2 Click Check for Issues.

15-45
15 Fixed-Point Conversion

The app does not detect issues.


3 Click Next to go to the Convert to Fixed Point step.

Convert to Fixed Point

1 The app displays compiled information — type, size, and complexity — for variables
in your code. For more information, see “View and Modify Variable Information” on
page 15-82.

On the Function Replacements tab the app displays functions that are not
supported for fixed-point conversion. See “Running a Simulation” on page 15-91.

15-46
Detect Overflows

2
To view the fimath settings, click the Settings arrow . Set the fimath Product
mode and Sum mode to KeepLSB. These settings model the behavior of integer
operations in the C language.

3 Click Simulate.

The test file, overflow_test, runs. The app displays simulation minimum and
maximum ranges on the Variables tab. Using the simulation range data, the
software proposes fixed-point types for each variable based on the default type
proposal settings, and displays them in the Proposed Type column.

4 To convert the floating-point algorithm to fixed point, click Convert.

15-47
15 Fixed-Point Conversion

The software validates the proposed types and generates a fixed-point version of the
entry-point function.

If errors and warnings occur during validation, the app displays them on the Type
Validation Output tab. See “Validating Types” on page 15-105.

Test Numerics and Check for Overflows

1
Click the Test arrow . Verify that the test file is overflow_test.m. Select Use
scaled doubles to detect overflows, and then click Test.

The app runs the test file that you used to define input types to test the fixed-point
MATLAB code. Because you selected to detect overflows, it also runs the simulation
using scaled double versions of the proposed fixed-point types. Scaled doubles
store their data in double-precision floating-point, so they carry out arithmetic in
full range. Because they retain their fixed-point settings, they can report when a
computation goes out of the range of the fixed-point type.

The simulation runs. The app detects an overflow. The app reports the overflow on
the Overflow tab. To highlight the expression that overflowed, click the overflow.

15-48
Detect Overflows

2 Determine whether it was the sum or the multiplication that overflowed.

In the fimath settings, set Product mode to FullPrecision, and then repeat the
conversion and test the fixed-point code again.

The overflow still occurs, indicating that it is the addition in the expression that is
overflowing.

15-49
15 Fixed-Point Conversion

Replace the exp Function with a Lookup Table


This example shows how to replace the exp function with a lookup table approximation
in fixed-point code generated using the MATLAB Coder app.

Prerequisites

To complete this example, you must install the following products:

• MATLAB
• MATLAB Coder
• Fixed-Point Designer
• C compiler (for most platforms, a default C compiler is supplied with MATLAB). See
http://www.mathworks.com/support/compilers/current_release/.

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

Create Algorithm and Test Files

1 Create a MATLAB function, my_fcn.m, that calls the exp function.


function y = my_fcn(x)
y = exp(x);
end
2 Create a test file, my_fcn_test.m, that uses my_fcn.m.
close all

x = linspace(-10,10,1e3);
for itr = 1e3:-1:1
y(itr) = my_fcn( x(itr) );
end
plot( x, y );

Open the MATLAB Coder App

1 Navigate to the work folder that contains the file for this example.
2 On the MATLAB Toolstrip Apps tab, under Code Generation, click the app icon.

Enable Fixed-Point Conversion

Set Numeric Conversion to Convert to fixed point.

15-50
Replace the exp Function with a Lookup Table

Select Source Files

1 To add the entry-point function my_fcn to the project, browse to the file my_fcn.m,
and then click Open. By default, the app saves information and settings for this
project in the current folder in a file named my_fcn.prj.
2 Click Next to go to the Define Input Types step.

The app screens my_fcn.m for code violations and code generation readiness issues.
The app opens the Review Code Generation Readiness page.

15-51
15 Fixed-Point Conversion

Review Code Generation Readiness

1 Click Review Issues. The app indicates that the exp function is not supported for
fixed-point conversion. In a later step, you specify a lookup table replacement for this
function.

2 Click Next to go to the Define Input Types step.

Define Input Types

1 Add my_fcn_test as a test file and then click Autodefine Input Types.

The test file runs. The app determines from the test file that x is a scalar double.
2 Click Next to go to the Check for Run-Time Issues step.

15-52
Replace the exp Function with a Lookup Table

Check for Run-Time Issues

The Check for Run-Time Issues step generates an instrumented MEX function. It
runs the test file my_fcn_test replacing calls to my_fcn with calls to the generated
MEX function. If the app finds issues, it provides warning and error messages. You can
click a message to highlight the problematic code in a pane where you can edit the code.

1 On the Check for Run-Time Issues page, the app populates the test file field with
my_fcn_test, the test file that you used to define the input types.
2 Click Check for Issues.

The app does not detect issues.


3 Click Next to go to the Convert to Fixed Point step.

Replace exp Function with Lookup Table

1 Select the Function Replacements tab.

The app indicates that you must replace the exp function.

15-53
15 Fixed-Point Conversion

2 On the Function Replacements tab, right-click the exp function and select
Lookup Table.

15-54
Replace the exp Function with a Lookup Table

The app moves the exp function to the list of functions that it will replace with a
Lookup Table. By default, the lookup table uses linear interpolation and 1000 points.
Design Min and Design Max are set to Auto which means that the app uses the
design minimum and maximum values that it detects by either running a simulation
or computing derived ranges.

3
Click the Simulate arrow , select Log data for histogram, and verify that the
test file is my_fcn_test.

15-55
15 Fixed-Point Conversion

4 Click Simulate.

The simulation runs. On the Variables tab, the app displays simulation minimum
and maximum ranges. Using the simulation range data, the software proposes
fixed-point types for each variable based on the default type proposal settings, and
displays them in the Proposed Type column. The app enables the Convert option.
5 Examine the proposed types and verify that they cover the full simulation range.
To view logged histogram data for a variable, click its Proposed Type field. The
histogram provides range information and the percentage of simulation range
covered by the proposed data type.

Convert to Fixed Point

1 Click Convert.

The app validates the proposed types, and generates a fixed-point version of the
entry-point function, my_fcn_fixpt.m.
2 In the Output Files list, select my_fcn_fixpt.m.

The conversion process generates a lookup table approximation, replacement_exp,


for the exp function.

15-56
Replace the exp Function with a Lookup Table

The generated fixed-point function, my_fcn_fixpt.m, calls this approximation


instead of calling exp. The fixed-point conversion process infers the ranges for the
function and then uses an interpolated lookup table to replace the function. By
default, the lookup table uses linear interpolation, 1000 points, and the minimum
and maximum values detected by running the test file.

function y = my_fcn_fixpt(x)
fm = get_fimath();

y = fi(replacement_exp(x), 0, 16, 1, fm);


end

15-57
15 Fixed-Point Conversion

You can now test the generated fixed-point code and compare the results against the
original MATLAB function. If the behavior of the generated fixed-point code does
not match the behavior of the original code closely enough, modify the interpolation
method or number of points used in the lookup table. Then, regenerate the code.

15-58
Replace a Custom Function with a Lookup Table

Replace a Custom Function with a Lookup Table


This example shows how to replace a custom function with a lookup table approximation
function using the MATLAB Coder app.

Prerequisites

This example requires the following products:

• MATLAB
• MATLAB Coder
• Fixed-Point Designer
• C compiler (for most platforms, a default C compiler is supplied with MATLAB). See
http://www.mathworks.com/support/compilers/current_release/.

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

Create Algorithm and Test Files

In a local, writable folder:

1 Create a MATLAB function, custom_fcn.m which is the function that you want to
replace.

function y = custom_fcn(x)
y = 1./(1+exp(-x));
end
2 Create a wrapper function, call_custom_fcn.m, that calls custom_fcn.m.

function y = call_custom_fcn(x)
y = custom_fcn(x);
end
3 Create a test file, custom_test.m, that uses call_custom_fcn.

close all
clear all

x = linspace(-10,10,1e3);
for itr = 1e3:-1:1
y(itr) = call_custom_fcn( x(itr) );

15-59
15 Fixed-Point Conversion

end
plot( x, y );

Open the MATLAB Coder App

1 Navigate to the work folder that contains the file for this example.
2 On the MATLAB Toolstrip Apps tab, under Code Generation, click the app icon.

Enable Fixed-Point Conversion

Set Numeric Conversion to Convert to fixed point.

15-60
Replace a Custom Function with a Lookup Table

Select Source Files

1 To add the entry-point function call_custom_fcn to the project, browse to


the file call_custom_fcn.m, and then click Open. By default, the app saves
information and settings for this project in the current folder in a file named
call_custom_fcn.prj.
2 Click Next to go to the Define Input Types step.

The app screens call_custom_fcn.m for code violations and code generation
readiness issues. The app opens the Review Code Generation Readiness page.

Review Code Generation Readiness

1 Click Review Issues. The app indicates that the exp function is not supported for
fixed-point conversion. You can ignore this warning because you are going to replace
custom_fcn, which is the function that calls exp.

15-61
15 Fixed-Point Conversion

2 Click Next to go to the Define Input Types step.

Define Input Types

1 Add custom_test as a test file and then click Autodefine Input Types.

The test file runs. The app determines from the test file that x is a scalar double.
2 Click Next to go to the Check for Run-Time Issues step.

Check for Run-Time Issues

The Check for Run-Time Issues step generates instrumented MEX. It runs the test
file custom_test replacing calls to call_custom_fcn with calls to the generated MEX
function. If the app finds issues, it provides warning and error messages. You can click a
message to highlight the problematic code in a pane where you can edit the code.

15-62
Replace a Custom Function with a Lookup Table

1 On the Check for Run-Time Issues page, the app populates the test file field with
custom_test, the test file that you used to define the input types.
2 Click Check for Issues.

The app does not detect issues.


3 Click Next to go to the Convert to Fixed Point step.

Replace custom_fcn with Lookup Table

1 Select the Function Replacements tab.

The app indicates that you must replace the exp function.

2 Enter the name of the function to replace, custom_fcn, select Lookup Table, and
then click .

15-63
15 Fixed-Point Conversion

The app adds custom_fcn to the list of functions that it will replace with a Lookup
Table. By default, the lookup table uses linear interpolation and 1000 points. The
app sets Design Min and Design Max to Auto which means that app uses the
design minimum and maximum values that it detects by either running a simulation
or computing derived ranges.

15-64
Replace a Custom Function with a Lookup Table

3
Click the Simulate arrow , select Log data for histogram, and verify that the
test file is call_custom_test.

4 Click Simulate.

The simulation runs. The app displays simulation minimum and maximum ranges
on the Variables tab. Using the simulation range data, the software proposes
fixed-point types for each variable based on the default type proposal settings, and
displays them in the Proposed Type column. The Convert option is now enabled.
5 Examine the proposed types and verify that they cover the full simulation range.
To view logged histogram data for a variable, click its Proposed Type field. The
histogram provides range information and the percentage of simulation range
covered by the proposed data type.

15-65
15 Fixed-Point Conversion

Convert to Fixed Point

1 Click Convert.

The app validates the proposed types and generates a fixed-point version of the
entry-point function, call_custom_fcn_fixpt.m.

2 In the Output Files list, select call_custom_fcn_fixpt.m.

The conversion process generates a lookup table approximation,


replacement_custom_fcn, for the custom_fcn function. The fixed-point
conversion process infers the ranges for the function and then uses an interpolated
lookup table to replace the function. By default, the lookup table uses linear
interpolation, 1000 points, and the minimum and maximum values detected by
running the test file.

The generated fixed-point function, call_custom_fcn_fixpt.m, calls this


approximation instead of calling custom_fcn.

15-66
Replace a Custom Function with a Lookup Table

function y = call_custom_fcn_fixpt(x)
fm = get_fimath();

y = fi(replacement_custom_fcn(x), 0, 16, 16, fm);


end

You can now test the generated fixed-point code and compare the results against the
original MATLAB function. If the behavior of the generated fixed-point code does
not match the behavior of the original code closely enough, modify the interpolation
method or number of points used in the lookup table and then regenerate code.

15-67
15 Fixed-Point Conversion

Enable Plotting Using the Simulation Data Inspector


You can use the Simulation Data Inspector with the MATLAB Coder app to inspect and
compare floating-point and fixed-point logged input and output data.

1 On the Convert to Fixed Point page,

Click the Settings arrow .


2 Expand the Plotting and Reporting settings and set Plot with Simulation Data
Inspector to Yes.

3
Click the Test arrow . Select Log inputs and outputs for comparison plots,
and then click Test.

For an example, see “Propose Fixed-Point Data Types Based on Derived Ranges” on page
15-23“Propose Data Types Based on Derived Ranges”.

15-68
Visualize Differences Between Floating-Point and Fixed-Point Results

Visualize Differences Between Floating-Point and Fixed-Point


Results
This example shows how to configure the MATLAB Coder app to use a custom plot
function to compare the behavior of the generated fixed-point code against the behavior
of the original floating-point MATLAB code.

By default, when the Log inputs and outputs for comparison plots option is
enabled, the conversion process uses a time series based plotting function to show the
floating-point and fixed-point results and the difference between them. However, during
fixed-point conversion you might want to visualize the numerical differences in a view
that is more suitable for your application domain. This example shows how to customize
plotting and produce scatter plots at the test numerics step of the fixed-point conversion.

Prerequisites

This example requires the following products:

• MATLAB
• Fixed-Point Designer
• MATLAB Coder
• C compiler (for most platforms, a default C compiler is supplied with MATLAB). See
http://www.mathworks.com/support/compilers/current_release/.

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

Create a New Folder and Copy Relevant Files

1 Create a local working folder, for example, c:\custom_plot.


2 Change to the docroot\toolbox\fixpoint\examples folder. At the MATLAB
command line, enter:
cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples'))
3 Copy the myFilter.m, myFilterTest.m, plotDiff.m, and filterData.mat files
to your local working folder.

Type Name Description


Function code myFilter.m Entry-point MATLAB function

15-69
15 Fixed-Point Conversion

Type Name Description


Test file myFilterTest.m MATLAB script that tests
myFilter.m
Plotting function plotDiff.m Custom plot function
MAT-file filterData.mat Data to filter.

The myFilter Function


function [y, ho] = myFilter(in)

persistent b h;
if isempty(b)
b = complex(zeros(1,16));
h = complex(zeros(1,16));
h(8) = 1;
end

b = [in, b(1:end-1)];
y = b*h.';

errf = 1-sqrt(real(y)*real(y) + imag(y)*imag(y));


update = 0.001*conj(b)*y*errf;

h = h + update;
h(8) = 1;
ho = h;

end

The myFilterTest File


% load data
data = load('filterData.mat');
d = data.symbols;

for idx = 1:4000


y = myFilter(d(idx));
end

The plotDiff Function


% varInfo - structure with information about the variable. It has the following fields
% i) name

15-70
Visualize Differences Between Floating-Point and Fixed-Point Results

% ii) functionName
% floatVals - cell array of logged original values for the 'varInfo.name' variable
% fixedVals - cell array of logged values for the 'varInfo.name' variable after
% Fixed-Point Conversion.
function plotDiff(varInfo, floatVals, fixedVals)
varName = varInfo.name;
fcnName = varInfo.functionName;

% convert from cell to matrix


floatVals = cell2mat(floatVals);
fixedVals = cell2mat(fixedVals);

% escape the '_'s because plot titles treat these as subscripts


escapedVarName = regexprep(varName,'_','\\_');
escapedFcnName = regexprep(fcnName,'_','\\_');

% flatten the values


flatFloatVals = floatVals(1:end);
flatFixedVals = fixedVals(1:end);

% build Titles
floatTitle = [ escapedFcnName ' > ' 'float : ' escapedVarName ];
fixedTitle = [ escapedFcnName ' > ' 'fixed : ' escapedVarName ];

data = load('filterData.mat');

switch varName
case 'y'
x_vec = data.symbols;

figure('Name', 'Comparison plot', 'NumberTitle', 'off');

% plot floating point values


y_vec = flatFloatVals;
subplot(1, 2, 1);
plotScatter(x_vec, y_vec, 100, floatTitle);

% plot fixed point values


y_vec = flatFixedVals;
subplot(1, 2, 2);
plotScatter(x_vec, y_vec, 100, fixedTitle);

otherwise
% Plot only output 'y' for this example, skip the rest

15-71
15 Fixed-Point Conversion

end

end

function plotScatter(x_vec, y_vec, n, figTitle)


% plot the last n samples
x_plot = x_vec(end-n+1:end);
y_plot = y_vec(end-n+1:end);

hold on
scatter(real(x_plot),imag(x_plot), 'bo');

hold on
scatter(real(y_plot),imag(y_plot), 'rx');

title(figTitle);
end

Open the MATLAB Coder App

1 Navigate to the folder that contains the files for this example.
2 On the MATLAB Toolstrip Apps tab, under Code Generation, click the app icon.

Enable Fixed-Point Conversion

Set Numeric Conversion to Convert to fixed point.

15-72
Visualize Differences Between Floating-Point and Fixed-Point Results

Select Source Files

1 To add the entry-point function myFilter to the project, browse to the file
myFilter.m, and then click Open.

By default, the app saves information and settings for this project in the current
folder in a file named myFilter.prj.
2 Click Next to go to the Define Input Types step.

The app screens myFilter.m for code violations and code generation readiness
issues. The app does not find issues in myFilter.m.

15-73
15 Fixed-Point Conversion

Define Input Types

1 On the Define Input Types page, to add myFilter_test as a test file, browse to
myFilter_test.m, and then click Open.
2 Click Autodefine Input Types.

The app determines from the test file that the input type of in is
complex(double(1x1)).

3 Click Next to go to the Check for Run-Time Issues step.

Check for Run-Time Issues

The Check for Run-Time Issues step generates instrumented MEX. myFilter. It
runs the test file myFilterTest replacing calls to myFilter with calls to the generated
MEX. If the app finds issues, it provides warning and error messages. You can click a
message to highlight the problematic code in a window where you can edit the code.

1 Browse to the test file myFiltertest.m.


2 Click Check for Issues.

The app does not detect issues.


3 Click Next to go to the Convert to Fixed Point step.

15-74
Visualize Differences Between Floating-Point and Fixed-Point Results

Convert to Fixed Point

1 The app displays compiled information for variables in your code. For more
information, see “View and Modify Variable Information” on page 15-82“View
and Modify Variable Information”.

2
To open the settings dialog box, click the Settings arrow .

a Verify that Default word length is set to 16.


b Under Advanced, set Signedness to Signed
c Under Plotting and Reporting, set Custom plot function to plotDiff.
3
Click the Simulate arrow . Verify that the test file is myFilterTest.

15-75
15 Fixed-Point Conversion

4 Click Simulate.

The test file, myFilterTest, runs and the app displays simulation minimum
and maximum ranges on the Variables tab. Using the simulation range data, the
software proposes fixed-point types for each variable based on the default type
proposal settings, and displays them in the Proposed Type column.

5 To convert the floating-point algorithm to fixed point, click Convert.

The software validates the proposed types and generates a fixed-point version of the
entry-point function.

15-76
Visualize Differences Between Floating-Point and Fixed-Point Results

Test Numerics and View Comparison Plots

1
Click Test arrow , select Log inputs and outputs for comparison plots, and
then click Test.

The app runs the test file that you used to define input types to test the fixed-point
MATLAB code. Because you selected to log inputs and outputs for comparison plots
and to use the custom plotting function, plotDiff.m, for these plots, the app uses
this function to generate the comparison plot. The plot shows that the fixed-point
results do not closely match the floating-point results.

15-77
15 Fixed-Point Conversion

2 In the settings, increase the DefaultWordLength to 24 and then convert to fixed


point again.

The app converts myFilter.m to fixed point and proposes fixed-point data types
using the new default word length.
3 Run the test numerics step again.

The increased word length improves the results. This time, the plot shows that the
fixed-point results match the floating-point results.

15-78
Visualize Differences Between Floating-Point and Fixed-Point Results

15-79
15 Fixed-Point Conversion

Log Data for Histogram


To log data for histograms:


On the Convert to Fixed Point page, click the Simulate arrow .
• Select Log data for histogram.

• Click Simulate.

After simulation, to view the histogram for a variable, on the Variables tab, click the
Proposed Type field for that variable.

The histogram provides the range of the proposed data type and the percentage of
simulation values that the proposed data type covers. The bit weights are displayed along
the X-axis, and the percentage of occurrences along the Y-axis. Each bin in the histogram
corresponds to a bit in the binary word. For example, this histogram displays the range
for a variable of type numerictype(1,16,14).

You can view the effect of changing the proposed data types by:

• Dragging the edges of the bounding box in the histogram window to change the
proposed data type.

15-80
Log Data for Histogram

• Selecting or clearing Signed.

To revert to the types proposed by the automatic conversion, in the histogram window,

click .

15-81
15 Fixed-Point Conversion

View and Modify Variable Information

View Variable Information


On the Convert to Fixed Point page of the MATLAB Coder app, you can view
information about the variables in the MATLAB functions. To view information about
the variables that you select in the Source Code pane, use the Variables tab or place
your cursor over a variable in the code window. For more information, see “Viewing
Variables” on page 15-100.

You can view the variable information:

• Variable

Variable name. Variables are classified and sorted as inputs, outputs, persistent, or
local variables.
• Type

The original size, type, and complexity of each variable.


• Sim Min

The minimum value assigned to the variable during simulation.


• Sim Max

The maximum value assigned to the variable during simulation.

To search for a variable in the MATLAB code window and on the Variables tab, use
Ctrl+F. The app highlights occurrences of the variable in the code.

Modify Variable Information


If you modify variable information, the app highlights the modified values using bold
text. You can modify the following fields:

• Static Min

You can enter a value for Static Min into the field or promote Sim Min information.
See “Promote Sim Min and Sim Max Values” on page 15-85.

15-82
View and Modify Variable Information

Editing this field does not trigger static range analysis, but the app uses the edited
values in subsequent analyses.
• Static Max

You can enter a value for Static Max into the field or promote Sim Max information.
See “Promote Sim Min and Sim Max Values” on page 15-85.

Editing this field does not trigger static range analysis, but the app uses the edited
values in subsequent analyses.
• Whole Number

The app uses simulation data to determine whether the values assigned to a variable
during simulation were always integers. You can manually override this field.

Editing this field does not trigger static range analysis, but the app uses the edited
value in subsequent analyses.
• Proposed Type

You can modify the signedness, word length, and fraction length settings individually:

• On the Variables tab, modify the value in the ProposedType field.

• In the code window, select a variable, and then modify the ProposedType field.

15-83
15 Fixed-Point Conversion

If you selected to log data for a histogram, the histogram dynamically updates to
reflect the modifications to the proposed type. You can also modify the proposed type
in the histogram, see “Log Data for Histogram” on page 15-102.

Revert Changes
• To clear results and revert edited values, right-click the Variables tab and select
Reset entire table.

• To revert the type of a selected variable to the type computed by the app, right-click
the field and select Undo changes.
• To revert changes to variables, right-click the field and select Undo changes for
all variables.

15-84
View and Modify Variable Information

• To clear a static range value, right-click an edited field and select Clear this
static range.
• To clear manually entered static range values, right-click anywhere on the Variables
tab and select Clear all manually entered static ranges.

Promote Sim Min and Sim Max Values


With the MATLAB Coder app, you can promote simulation minimum and maximum
values to static minimum and maximum values. This capability is useful if you have not
specified static ranges and you have simulated the model with inputs that cover the full
intended operating range.

To copy:

• A simulation range for a selected variable, select a variable, right-click, and then
select Copy sim range.
• Simulation ranges for top-level inputs, right-click the Static Min or Static Max
column, and then select Copy sim ranges for all top-level inputs.
• Simulation ranges for persistent variables, right-click the Static Min or Static Max
column, and then select Copy sim ranges for all persistent variables.

15-85
15 Fixed-Point Conversion

Automated Fixed-Point Conversion


In this section...
“Automated Fixed-Point Conversion Capabilities” on page 15-86
“Code Coverage” on page 15-87
“Proposing Data Types” on page 15-91
“Locking Proposed Data Types” on page 15-93
“Viewing Functions” on page 15-93
“Viewing Variables” on page 15-100
“Log Data for Histogram” on page 15-102
“Function Replacements” on page 15-104
“Validating Types” on page 15-105
“Testing Numerics” on page 15-105
“Detecting Overflows” on page 15-106

Automated Fixed-Point Conversion Capabilities


You can convert floating-point MATLAB code to fixed-point code using the MATLAB
Coder app or at the command line using the codegen function -float2fixed option.
You can choose to propose data types based on simulation range data, derived (also
known as static) range data, or both.

You can manually enter static ranges. These manually entered ranges take precedence
over simulation ranges and the app uses them when proposing data types. In addition,
you can modify and lock the proposed type so that the app cannot change it. For more
information, see “Locking Proposed Data Types” on page 15-93.

For a list of supported MATLAB features and functions, see “MATLAB Language
Features Supported for Automated Fixed-Point Conversion”.

During fixed-point conversion, you can:

• Verify that your test files cover the full intended operating range of your algorithm
using code coverage results.
• Propose fraction lengths based on default word lengths.

15-86
Automated Fixed-Point Conversion

• Propose word lengths based on default fraction lengths.


• Optimize whole numbers.
• Specify safety margins for simulation min/max data.
• Validate that you can build your project with the proposed data types.
• Test numerics by running the test file with the fixed-point types applied.
• View a histogram of bits that each variable uses.
• Detect overflows.

Code Coverage
By default, the app shows code coverage results. Your test files must exercise the
algorithm over its full operating range so that the simulation ranges are accurate. The
quality of the proposed fixed-point data types depends on how well the test files cover the
operating range of the algorithm with the accuracy that you want.

Reviewing code coverage results helps you to verify that your test files are exercising
the algorithm adequately. If the code coverage is inadequate, modify the test files or add
more test files to increase coverage. If you simulate multiple test files in one run, the app
displays cumulative coverage. However, if you specify multiple test files, but run them
one at a time, the app displays the coverage of the file that ran last.

The app displays a color-coded coverage bar to the left of the code.

15-87
15 Fixed-Point Conversion

This table describes the color coding.

Coverage Bar Indicates


Color
Green One of the following situations:

15-88
Automated Fixed-Point Conversion

Coverage Bar Indicates


Color
• The entry-point function executes multiple times and the code
executes more than one time.
• The entry-point function executes one time and the code executes
one time.

Different shades of green indicate different ranges of line execution


counts. The darkest shade of green indicates the highest range.
Orange The entry-point function executes multiple times, but the code
executes one time.
Red Code does not execute.

When you place your cursor over the coverage bar, the color highlighting extends over
the code. For each section of code, the app displays the number of times that the section
executes.

15-89
15 Fixed-Point Conversion

To verify that your test files are testing your algorithm over the intended operating
range, review the code coverage results.

Coverage Bar Action


Color
Green If you expect sections of code to execute more frequently than the
coverage shows, either modify the MATLAB code or the test files.
Orange This behavior is expected for initialization code, for example, the
initialization of persistent variables. If you expect the code to execute
more than one time, either modify the MATLAB code or the test files.
Red If the code that does not execute is an error condition, this behavior
is acceptable. If you expect the code to execute, either modify the

15-90
Automated Fixed-Point Conversion

Coverage Bar Action


Color
MATLAB code or the test files. If the code is written conservatively
and has upper and lower boundary limits, and you cannot modify
the test files to reach this code, add static minimum and maximum
values. See “Computing Derived Ranges” on page 15-92.

Code coverage is on by default. Turn it off only after you have verified that you have
adequate test file coverage. Turning off code coverage can speed up simulation. To turn
off code coverage, on the Convert to Fixed Point page:

1
Click the Simulate arrow .
2 Clear the Show code coverage check box.

Proposing Data Types


The app proposes fixed-point data types based on computed ranges and the word length
or fraction length setting. The computed ranges are based on simulation range data,
derived range data (also known as static ranges), or both. If you run a simulation and
compute derived ranges, the app merges the simulation and derived ranges.

Note: You cannot propose data types based on derived ranges for MATLAB classes.

You can manually enter static ranges. These manually entered ranges take precedence
over simulation ranges and the app uses them when proposing data types. You
can modify and lock the proposed type so that the tool cannot change it. For more
information, see “Locking Proposed Data Types” on page 15-93.

Running a Simulation

During fixed-point conversion, the app generates an instrumented MEX function for
your entry-point MATLAB file. If the build completes without errors, the app displays
compiled information (type, size, complexity) for functions and variables in your code.
To navigate to local functions, click the Functions tab. If build errors occur, the app
provides error messages that link to the line of code that caused the build issues. You
must address these errors before running a simulation. Use the link to navigate to
the offending line of code in the MATLAB editor and modify the code to fix the issue.
If your code uses functions that are not supported for fixed-point conversion, the app

15-91
15 Fixed-Point Conversion

displays them on the Function Replacements tab. See “Function Replacements” on


page 15-104.

Before running a simulation, specify the test file or files that you want to run. When you
run a simulation, the app runs the test file, calling the instrumented MEX function. If
you modify the MATLAB design code, the app automatically generates an updated MEX
function before running a test file.

If the test file runs successfully, the simulation minimum and maximum values and the
proposed types are displayed on the Variables tab. If you manually enter static ranges
for a variable, the manually entered ranges take precedence over the simulation ranges.
If you manually modify the proposed types by typing or using the histogram, the data
types are locked so that the app cannot modify them.

If the test file fails, the errors are displayed on the Simulation Output tab.

Test files must exercise your algorithm over its full operating range. The quality of the
proposed fixed-point data types depends on how well the test file covers the operating
range of the algorithm with the accuracy that you want. You can add test files and select
to run more than one test file during the simulation. If you run multiple test files, the
app merges the simulation results.

Optionally, you can select to log data for histograms. After running a simulation, you
can view the histogram for each variable. For more information, see “Log Data for
Histogram” on page 15-102.

Computing Derived Ranges

The advantage of proposing data types based on derived ranges is that you do not have to
provide test files that exercise your algorithm over its full operating range. Running such
test files often takes a very long time.

To compute derived ranges and propose data types based on these ranges, provide
static minimum and maximum values or proposed data types for all input variables.
To improve the analysis, enter as much static range information as possible for other
variables. You can manually enter ranges or promote simulation ranges to use as static
ranges. Manually entered static ranges always take precedence over simulation ranges.

If you know what data type your hardware target uses, set the proposed data types to
match this type. Manually entered data types are locked so that the app cannot modify
them. The app uses these data types to calculate the input minimum and maximum

15-92
Automated Fixed-Point Conversion

values and to derive ranges for other variables. For more information, see “Locking
Proposed Data Types” on page 15-93.

When you select Compute Derived Ranges, the app runs a derived range analysis to
compute static ranges for variables in your MATLAB algorithm. When the analysis is
complete, the static ranges are displayed on the Variables tab. If the run produces +/-
Inf derived ranges, consider defining ranges for all persistent variables.

Optionally, you can select Quick derived range analysis. With this option, the app
performs faster static analysis. The computed ranges might be larger than necessary.
Select this option in cases where the static analysis takes more time than you can afford.

If the derived range analysis for your project is taking a long time, you can optionally set
a timeout. When the timeout is reached, the app aborts the analysis.

Locking Proposed Data Types


You can lock proposed data types against changes by the app using one of the following
methods:

• Manually setting a proposed data type in the app.


• Right-clicking a type proposed by the tool and selecting Lock computed value.

The app displays locked data types in bold so that they are easy to identify. You can
unlock a type using one of the following methods:

• Manually overwriting it.


• Right-clicking it and selecting Undo changes. This action unlocks only the selected
type.
• Right-clicking and selecting Undo changes for all variables. This action
unlocks all locked proposed types.

Viewing Functions
During the Convert to Fixed Point step of the fixed-point conversion process, you can
view a list of functions in your project in the left pane. This list also includes function
specializations and class methods. When you select a function from the list, the MATLAB
code for that function or class method is displayed in the code window and the variables
that they use are displayed on the Variables tab.

15-93
15 Fixed-Point Conversion

After conversion, the left pane also displays a list of output files including the fixed-
point version of the original algorithm. If your function is not specialized, the app
retains the original function name in the fixed-point file name and appends the fixed-
point suffix. For example, here the fixed-point version of ex_2ndOrder_filter.m is
ex_2ndOrder_filter_fixpt.m.

Classes

The app displays information for the class and each of its methods. For example, consider
a class, Counter, that has a static method, MAX_VALUE, and a method, next.

If you select the class, the app displays the class and its properties on the Variables tab.

15-94
Automated Fixed-Point Conversion

If you select a method, the app displays only the variables that the method uses.

15-95
15 Fixed-Point Conversion

Specializations

If a function is specialized, the app lists each specialization and numbers them
sequentially. For example, consider a function, dut, that calls subfunctions, foo and
bar, multiple times with different input types.

function y = dut(u, v)

tt1 = foo(u);
tt2 = foo([u v]);
tt3 = foo(complex(u,v));

ss1 = bar(u);
ss2 = bar([u v]);
ss3 = bar(complex(u,v));

y = (tt1 + ss1) + sum(tt2 + ss2) + real(tt3) + real(ss3);

15-96
Automated Fixed-Point Conversion

end

function y = foo(u)
y = u * 2;
end

function y = bar(u)
y = u * 4;
end

If you select the top-level function, the app displays all the variables on the Variables
tab.

If you select the tree view, the app also displays the line numbers for the call to each
specialization.

15-97
15 Fixed-Point Conversion

If you select a specialization, the app displays only the variables that the specialization
uses.

15-98
Automated Fixed-Point Conversion

In the generated fixed-point code, the number of each fixed-point specialization matches
the number in the Source Code list, which makes it easy to trace between the floating-
point and fixed-point versions of your code. For example, the generated fixed-point
function for foo > 1 is named foo_s1.

15-99
15 Fixed-Point Conversion

Viewing Variables
The Variables tab provides the following information for each variable in the function
selected in the Navigation pane:

• Type — The original data type of the variable in the MATLAB algorithm.
• Sim Min and Sim Max — The minimum and maximum values assigned to the
variable during simulation.

You can edit the simulation minimum and maximum values. Edited fields are shown
in bold. Editing these fields does not trigger static range analysis, but the tool uses
the edited values in subsequent analyses. You can revert to the types proposed by the
app.
• Static Min and Static Max — The static minimum and maximum values.

15-100
Automated Fixed-Point Conversion

To compute derived ranges and propose data types based on these ranges, provide
static minimum and maximum values for all input variables. To improve the analysis,
enter as much static range information as possible for other variables.

When you compute derived ranges, the app runs a static analysis to compute static
ranges for variables in your code. When the analysis is complete, the static ranges are
displayed. You can edit the computed results. Edited fields are shown in bold. Editing
these fields does not trigger static range analysis, but the tool uses the edited values
in subsequent analyses. You can revert to the types proposed by the app.
• Whole Number — Whether all values assigned to the variable during simulation are
integers.

The app determines whether a variable is always a whole number. You can modify
this field. Edited fields are shown in bold. Editing these fields does not trigger static
range analysis, but the app uses the edited values in subsequent analyses. You can
revert to the types proposed by the app.
• The proposed fixed-point data type for the specified word (or fraction)
length. Proposed data types use the numerictype notation. For example,
numerictype(1,16,12) denotes a signed fixed-point type with a word length of 16
and a fraction length of 12. numerictype(0,16,12) denotes an unsigned fixed-point
type with a word length of 16 and a fraction length of 12.

Because the app does not apply data types to expressions, it does not display proposed
types for them. Instead, it displays their original data types.

You can also view and edit variable information in the code pane by placing your cursor
over a variable name.

You can use Ctrl+F to search for variables in the MATLAB code and on the Variables
tab. The app highlights occurrences in the code and displays only the variable with the
specified name on the Variables tab.

Viewing Information for MATLAB Classes

The app displays:

• Code for MATLAB classes and code coverage for class methods in the code window.
Use the Source Code list on the Convert to Fixed Point page to select which class
or class method to view. If you select a class method, the app highlights the method in
the code window.

15-101
15 Fixed-Point Conversion

• Information about MATLAB classes on the Variables tab.

Log Data for Histogram


To log data for histograms:


On the Convert to Fixed Point page, click the Simulate arrow .

15-102
Automated Fixed-Point Conversion

• Select Log data for histogram.

• Click Simulate.

After simulation, to view the histogram for a variable, on the Variables tab, click the
Proposed Type field for that variable.

The histogram provides the range of the proposed data type and the percentage of
simulation values that the proposed data type covers. The bit weights are displayed along
the X-axis, and the percentage of occurrences along the Y-axis. Each bin in the histogram
corresponds to a bit in the binary word. For example, this histogram displays the range
for a variable of type numerictype(1,16,14).

You can view the effect of changing the proposed data types by:

• Dragging the edges of the bounding box in the histogram window to change the
proposed data type.

15-103
15 Fixed-Point Conversion

• Selecting or clearing Signed.

To revert to the types proposed by the automatic conversion, in the histogram window,

click .

Function Replacements
If your MATLAB code uses functions that do not have fixed-point support, the app
lists these functions on the Function Replacements tab. You can choose to replace
unsupported functions with a custom function replacement or with a lookup table.

You can add and remove function replacements from this list. If you enter a function
replacement for a function, the replacement function is used when you build the

15-104
Automated Fixed-Point Conversion

project. If you do not enter a replacement, the app uses the type specified in the original
MATLAB code for the function.

Note: Using this table, you can replace the names of the functions but you cannot replace
argument patterns.

If code generation readiness screening is disabled, the list of unsupported functions on


the Function Replacements tab can be incomplete or incorrect. In this case, add the
functions manually. See “Code Generation Readiness Screening in the MATLAB Coder
App” on page 18-34.

Validating Types
Converting the code to fixed point validates the build using the proposed fixed-point data
types. If the validation is successful, you are ready to test the numerical behavior of the
fixed-point MATLAB algorithm.

If the errors or warnings occur during validation, they are displayed on the Type
Validation Output tab. If errors or warning occur:

• On the Variables tab, inspect the proposed types and manually modified types to
verify that they are valid.
• On the Function Replacements tab, verify that you have provided function
replacements for unsupported functions.

Testing Numerics
After converting code to fixed point and validating the proposed fixed-point data types,
click Test to verify the behavior of the fixed-point MATLAB algorithm. By default, if
you added a test file to define inputs or run a simulation, the app uses this test file to
test numerics. Optionally, you can add test files and select to run more than one test file.
The app compares the numerical behavior of the generated fixed-point MATLAB code
with the original floating-point MATLAB code. If you select to log inputs and outputs for
comparison plots, the app generates an additional plot for each scalar output. This plot
shows the floating-point and fixed-point results and the difference between them. For
nonscalar outputs, only the error information is shown.

After fixed-point simulation, if the numerical results do not meet the accuracy that you
want, modify fixed-point data type settings and repeat the type validation and numerical

15-105
15 Fixed-Point Conversion

testing steps. You might have to iterate through these steps multiple times to achieve the
results that you want.

Detecting Overflows
When testing numerics, selecting Use scaled doubles to detect overflows enables
overflow detection. When this option is selected, the conversion app runs the simulation
using scaled double versions of the proposed fixed-point types. Because scaled doubles
store their data in double-precision floating-point, they carry out arithmetic in full range.
They also retain their fixed-point settings, so they are able to report when a computation
goes out of the range of the fixed-point type. .

If the app detects overflows, on its Overflow tab, it provides:

• A list of variables and expressions that overflowed


• Information on how much each variable overflowed
• A link to the variables or expressions in the code window

If your original algorithm uses scaled doubles, the app also provides overflow information
for these expressions.

See Also

“Detect Overflows” on page 15-40

15-106
Convert Fixed-Point Conversion Project to MATLAB Scripts

Convert Fixed-Point Conversion Project to MATLAB Scripts


This example shows how to convert a MATLAB Coder project to MATLAB scripts when
the project includes automated fixed-point conversion. You can use the -tocode option of
the coder command to create a pair of scripts for fixed-point conversion and fixed-point
code generation. You can use the scripts to repeat the project workflow in a command-
line workflow. Before you convert the project to the scripts, you must complete the Test
step of the fixed-point conversion process.

Prerequisites

This example uses the following files:

• Project file ex_2ndOrder_filter.prj


• Entry-point file ex_2ndOrder_filter.m
• Test bench file ex_2ndOrder_filter_test.m
• Generated fixed-point MATLAB file ex_2ndOrder_filter_fixpt.m

To obtain these files, complete the example “Propose Fixed-Point Data Types Based on
Simulation Ranges” on page 15-9, including these steps:

1 Complete the Test step of the fixed-point conversion process.


2 Configure the project to build a C/C++ static library.

Generate the Scripts

1 Change to the folder that contains the project file ex_2ndOrder_filter.prj.


2 Use the -tocode option of the coder command to convert the project to the scripts.
Use the -script option to specify the file name for the scripts.

coder -tocode ex_2ndOrder_filter -script ex_2ndOrder_filter_script.m

The coder command generates two scripts in the current folder:

ex_2ndOrder_filter_script.m contains the MATLAB commands to:

• Create a code configuration object that has the same settings as the project.
• Run the codegen command to convert the fixed-point MATLAB function
ex_2ndOrder_filter_fixpt to a fixed-point C function.

15-107
15 Fixed-Point Conversion

The fixedPointConverter command generates a script in the current folder.


ex_2ndOrder_filter_script_fixpt.m contains the MATLAB commands to:

• Create a floating-point to fixed-point conversion configuration object that has the


same fixed-point conversion settings as the project.
• Run the codegen command to convert the MATLAB function
ex_2ndOrder_filter to the fixed-point MATLAB function
ex_2ndOrder_filter_fixpt.

The suffix in the script file name is the generated fixed-point file name suffix
specified by the project file. In this example, the suffix is the default value
_fixpt.

The coder command overwrites existing files that have the same names as the
generated scripts. If you omit the -script option, the coder command writes the
scripts to the Command Window.

Run Script That Generates Fixed-Point C Code

To run the script that generates fixed-point C code from fixed-point MATLAB code, the
fixed-point MATLAB function specified in the script must be available.

1 Make sure that the fixed-point MATLAB function ex_2ndOrder_filter_fixpt.m


is on the search path.

addpath c:\coder\ex_2ndOrder_filter\codegen\ex_2ndOrder_filter\fixpt
2 Run the script:

ex_2ndOrder_filter_script

The code generation software generates a C static library with the


name ex_2ndOrder_filter_fixpt in the folder codegen\lib
\ex_2ndOrder_filter_fixpt. The variables cfg and ARGS appear in the base
workspace.

Run Script That Generates Fixed-Point MATLAB Code

If you do not have the fixed-point MATLAB function, or if you want to regenerate it,
use the script that generates the fixed-point MATLAB function from the floating-point
MATLAB function.

15-108
Convert Fixed-Point Conversion Project to MATLAB Scripts

1 Make sure that the current folder contains the entry-point function
ex_2ndOrder_filter.m and the test bench file ex_2ndOrder_filter_test.m.
2 Run the script.
ex_2ndOrder_filter_script_fixpt

The code generation software generates ex_2ndOrder_filter_fixpt.m in the


folder codegen\ex_2ndOrder_filter\fixpt. The variables cfg and ARGS appear
in the base workspace.

See Also
coder.FixptConfig | codegen | coder

Related Examples
• “Convert MATLAB Code to Fixed-Point C Code” on page 15-7
• “Propose Fixed-Point Data Types Based on Simulation Ranges” on page 15-9
• “Convert MATLAB Coder Project to MATLAB Script” on page 21-43

15-109
15 Fixed-Point Conversion

Generated Fixed-Point Code

In this section...
“Location of Generated Fixed-Point Files” on page 15-110
“Minimizing fi-casts to Improve Code Readability” on page 15-111
“Avoiding Overflows in the Generated Fixed-Point Code” on page 15-111
“Controlling Bit Growth” on page 15-112
“Avoiding Loss of Range or Precision” on page 15-112
“Handling Non-Constant mpower Exponents” on page 15-114

Location of Generated Fixed-Point Files


By default, the fixed-point conversion process generates files in a folder named
codegen/fcn_name/fixpt in your local working folder. fcn_name is the name of the
MATLAB function that you are converting to fixed point.

File name Description


fcn_name_fixpt.m Generated fixed-point MATLAB code.

To integrate this fixed-point code into a


larger application, consider generating a
MEX-function for the function and calling
this MEX-function in place of the original
MATLAB code.
fcn_name_fixpt_exVal.mat MAT-file containing:

• A structure for the input arguments.


• The name of the fixed-point file.
fcn_name_fixpt_report.html Link to the type proposal report that
displays the generated fixed-point code and
the proposed type information.
fcn_name_report.html Link to the type proposal report that
displays the original MATLAB code and the
proposed type information.

15-110
Generated Fixed-Point Code

File name Description


fcn_name_wrapper_fixpt.m File that converts the floating-point data
values supplied by the test file to the fixed-
point types determined for the inputs
during the conversion step. These fixed-
point values are fed into the converted
fixed-point function, fcn_name_fixpt.

Minimizing fi-casts to Improve Code Readability


The conversion process tries to reduce the number of fi-casts by analyzing the floating-
point code. If an arithmetic operation is comprised of only compile-time constants, the
conversion process does not cast the operands to fixed point individually. Instead, it casts
the entire expression to fixed point.

For example, here is the fixed-point code generated for the constant expression x = 1/
sqrt(2) when the selected word length is 14.

Original MATLAB Code Generated Fixed-Point Code


x = 1/sqrt(2); x = fi(1/sqrt(2), 0, 14, 14, fm);

fm is the local fimath.

Avoiding Overflows in the Generated Fixed-Point Code


The conversion process avoids overflows by:

• Using full-precision arithmetic unless you specify otherwise.


• Avoiding arithmetic operations that involve double and fi data types. Otherwise, if
the word length of the fi data type is not able to represent the value in the double
constant expression, overflows occur.
• Avoiding overflows when adding and subtracting non fixed-point variables and fixed-
point variables.

The fixed-point conversion process casts non-fi expressions to the corresponding fi


type.

For example, consider the following MATLAB algorithm.

15-111
15 Fixed-Point Conversion

% A = 5;
% B = ones(300, 1)
function y = fi_plus_non_fi(A, B)
% '1024' is non-fi, cast it
y = A + 1024;
% 'size(B, 1)*length(A)' is a non-fi, cast it
y = A + size(B, 1)*length(A);
end

The generated fixed-point code is:


%#codegen
% A = 5;
% B = ones(300, 1)
function y = fi_plus_non_fi_fixpt(A, B)
% '1024' is non-fi, cast it
fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap',...
'ProductMode', 'FullPrecision', 'MaxProductWordLength', 128,...
'SumMode', 'FullPrecision', 'MaxSumWordLength', 128);

y = fi(A + fi(1024, 0, 11, 0, fm), 0, 11, 0, fm);


% 'size(B, 1)*length(A)' is a non-fi, cast it
y(:) = A + fi(size(B, fi(1, 0, 1, 0, fm))*length(A), 0, 9, 0, fm);
end

Controlling Bit Growth


The conversion process controls bit growth by using subscripted assignments, that
is, assignments that use the colon (:) operator, in the generated code. When you use
subscripted assignments, MATLAB overwrites the value of the left-hand side argument
but retains the existing data type and array size. Using subscripted assignment keeps
fixed-point variables fixed point rather than inadvertently turning them into doubles.
Maintaining the fixed-point type reduces the number of type declarations in the
generated code. Subscripted assignment also prevents bit growth which is useful when
you want to maintain a particular data type for the output.

Avoiding Loss of Range or Precision


Avoiding Loss of Range or Precision in Unsigned Subtraction Operations

When the result of the subtraction is negative, the conversion process promotes the left
operand to a signed type.

15-112
Generated Fixed-Point Code

For example, consider the following MATLAB algorithm.


% A = 1;
% B = 5
function [y,z] = unsigned_subtraction(A,B)
y = A - B;

C = -20;
z = C - B;
end

In the original code, both A and B are unsigned and the result of A-B can be negative. In
the generated fixed-point code, A is promoted to signed. In the original code, C is signed,
so does not require promotion in the generated code.
%#codegen
% A = 1;
% B = 5
function [y,z] = unsigned_subtraction_fixpt(A,B)

fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap',...


'ProductMode', 'FullPrecision', 'MaxProductWordLength', 128,...
'SumMode', 'FullPrecision', 'MaxSumWordLength', 128);
y = fi(fi_signed(A) - B, 1, 3, 0, fm);
C = fi(-20, 1, 6, 0, fm);
z = fi(C - B, 1, 6, 0, fm);
end

function y = fi_signed(a)
coder.inline( 'always' );
if isfi( a ) && ~(issigned( a ))
nt = numerictype( a );
new_nt = numerictype( 1, nt.WordLength + 1, nt.FractionLength );
y = fi( a, new_nt, fimath( a ) );
else
y = a;
end
end

Avoiding Loss of Range When Concatenating Arrays of Fixed-Point Numbers

If you concatenate matrices using vertcat and horzcat, the conversion process uses
the largest numerictype among the expressions of a row and casts the leftmost element to
that type. This type is then used for the concatenated matrix to avoid loss of range.

15-113
15 Fixed-Point Conversion

For example, consider the following MATLAB algorithm.

% A = 1, B = 100, C = 1000
function [y, z] = lb_node(A, B, C)
%% single rows
y = [A B C];
%% multiple rows
z = [A 5; A B; A C];
end

In the generated fixed-point code:

• For the expression y = [A B C], the leftmost element, A, is cast to the type of C
because C has the largest type in the row.
• For the expression [A 5; A B; A C]:

• In the first row, A is cast to the type of C because C has the largest type of the
whole expression.
• In the second row, A is cast to the type of B because B has the larger type in the
row.
• In the third row, A is cast to the type of C because C has the larger type in the row.

%#codegen
% A = 1, B = 100, C = 1000
function [y, z] = lb_node_fixpt(A, B, C)
%% single rows
fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap',...
'ProductMode', 'FullPrecision', 'MaxProductWordLength', 128, ...
'SumMode', 'FullPrecision', 'MaxSumWordLength', 128);

y = fi([fi(A, 0, 10, 0, fm) B C], 0, 10, 0, fm);

%% multiple rows
z = fi([fi(A, 0, 10, 0, fm) 5; fi(A, 0, 7, 0, fm) B;...
fi(A, 0, 10, 0, fm) C], 0, 10, 0, fm);
end

Handling Non-Constant mpower Exponents


If the function that you are converting has a scalar input, and the mpower exponent
input is not constant, the conversion process sets the fimath ProductMode to

15-114
Generated Fixed-Point Code

SpecifyPrecision in the generated code. With this setting , the output data type can
be determined at compile time.

For example, consider the following MATLAB algorithm.


% a = 1
% b = 3
function y = exp_operator(a, b)
% exponent is a constant so no need to specify precision
y = a^3;
% exponent is not a constant, use 'SpecifyPrecision' for 'ProductMode'
y = b^a;
end

In the generated fixed-point code, for the expression y = a^3 , the exponent is a
constant, so there is no need to specify precision. For the expression, y = b^a, the
exponent is not constant, so the ProductMode is set to SpecifyPrecision.

%#codegen
% a = 1
% b = 3
function y = exp_operator_fixpt(a, b)
% exponent is a constant so no need to specify precision
fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap',...
'ProductMode', 'FullPrecision', 'MaxProductWordLength', 128,...
'SumMode', 'FullPrecision', 'MaxSumWordLength', 128);

y = fi(a^3, 0, 2, 0, fm);
% exponent is not a constant, use 'SpecifyPrecision' for 'ProductMode'
y(:) = fi(b, 'ProductMode', 'SpecifyPrecision',...
'ProductWordLength', 2, 'ProductFractionLength', 0 )^a;
end

15-115
15 Fixed-Point Conversion

Fixed-Point Code for MATLAB Classes


In this section...
“Automated Conversion Support for MATLAB Classes” on page 15-116
“Unsupported Constructs” on page 15-116
“Coding Style Best Practices” on page 15-117

Automated Conversion Support for MATLAB Classes


The automated fixed-point conversion process:

• Proposes fixed-point data types based on simulation ranges for MATLAB classes. It
does not propose data types based on derived ranges for MATLAB classes.

After simulation, the MATLAB Coder app:

• Function list contains class constructors, methods, and specializations.


• Code window displays the objects used in each function.
• Provides code coverage for methods.

For more information, see “Viewing Information for MATLAB Classes” on page
15-101.
• Supports class methods, properties, and specializations. For each specialization of a
class, class_name, the conversion generates a separate class_name_fixpt.m file.
For every instantiation of a class, the generated fixed-point code contains a call to the
constructor of the appropriate specialization.
• Supports classes that have get and set methods such as get.PropertyName,
set.PropertyName. These methods are called when properties are read or assigned.
The set methods can be specialized. Sometimes, in the generated fixed-point code,
assignment statements are transformed to function calls.

Unsupported Constructs
The automated conversion process does not support:

• Class inheritance.
• Packages.

15-116
Fixed-Point Code for MATLAB Classes

• Constructors that use nargin and varargin.

Coding Style Best Practices


When you write MATLAB code that uses MATLAB classes:

• Initialize properties in the class constructor.


• Replace constant properties with static methods.

For example, consider the counter class.

classdef Counter < handle


properties
Value = 0;
end

properties(Constant)
MAX_VALUE = 128
end

methods
function out = next(this)
out = this.Count;
if this.Value == this.MAX_VALUE
this.Value = 0;
else
this.Value = this.Value + 1;
end
end
end
end
To use the automated fixed-point conversion process, rewrite the class to have a static
class that initializes the constant property MAX_VALUE and a constructor that initializes
the property Value.

classdef Counter < handle


properties
Value;
end

methods(Static)
function t = MAX_VALUE()
t = 128;

15-117
15 Fixed-Point Conversion

end
end

methods
function this = Counter()
this.Value = 0;
end
function out = next(this)
out = this.Value;
if this.Value == this.MAX_VALUE
this.Value = 0;
else
this.Value = this.Value + 1;
end
end
end
end

15-118
Automated Fixed-Point Conversion Best Practices

Automated Fixed-Point Conversion Best Practices


In this section...
“Create a Test File” on page 15-119
“Prepare Your Algorithm for Code Acceleration or Code Generation” on page 15-120
“Check for Fixed-Point Support for Functions Used in Your Algorithm” on page
15-121
“Manage Data Types and Control Bit Growth” on page 15-121
“Convert to Fixed Point” on page 15-122
“Use the Histogram to Fine-Tune Data Type Settings” on page 15-123
“Optimize Your Algorithm” on page 15-124
“Avoid Explicit Double and Single Casts” on page 15-126

Create a Test File


A best practice for structuring your code is to separate your core algorithm from other
code that you use to test and verify the results. Create a test file to call your original
MATLAB algorithm and fixed-point versions of the algorithm. For example, as shown in
the following table, you might set up some input data to feed into your algorithm, and
then, after you process that data, create some plots to verify the results. Since you need
to convert only the algorithmic portion to fixed point, it is more efficient to structure your
code so that you have a test file, in which you create your inputs, call your algorithm, and
plot the results, and one (or more) algorithmic files, in which you do the core processing.

Original code Best Practice Modified code


% TEST INPUT Issue Test file
x = randn(100,1);
Generation of test input % TEST INPUT
% ALGORITHM and verification of results x = randn(100,1);
y = zeros(size(x)); are intermingled with the
y(1) = x(1); % ALGORITHM
algorithm code.
for n=2:length(x) y = cumulative_sum(x);
y(n)=y(n-1) + x(n);
Fix % VERIFY RESULTS
end
yExpected = cumsum(x);
% VERIFY RESULTS
Create a test file that is plot(y-yExpected)
yExpected=cumsum(x); separate from your algorithm. title('Error')

15-119
15 Fixed-Point Conversion

Original code Best Practice Modified code


plot(y-yExpected) Put the algorithm in its own Algorithm in its own function
title('Error') function.
function y = cumulative_sum(x)
y = zeros(size(x));
y(1) = x(1);
for n=2:length(x)
y(n) = y(n-1) + x(n);
end
end

You can use the test file to:

• Verify that your floating-point algorithm behaves as you expect before you convert it
to fixed point. The floating-point algorithm behavior is the baseline against which you
compare the behavior of the fixed-point versions of your algorithm.
• Propose fixed-point data types.
• Compare the behavior of the fixed-point versions of your algorithm to the floating-
point baseline.
• Help you determine initial values for static ranges.

By default, the MATLAB Coder app shows code coverage results. Your test files should
exercise the algorithm over its full operating range so that the simulation ranges are
accurate. For example, for a filter, realistic inputs are impulses, sums of sinusoids, and
chirp signals. With these inputs, using linear theory, you can verify that the outputs are
correct. Signals that produce maximum output are useful for verifying that your system
does not overflow. The quality of the proposed fixed-point data types depends on how
well the test files cover the operating range of the algorithm with the accuracy that you
want. Reviewing code coverage results help you verify that your test file is exercising
the algorithm adequately. Review code flagged with a red code coverage bar because this
code is not executed. If the code coverage is inadequate, modify the test file or add more
test files to increase coverage. See “Code Coverage” on page 15-87.

Prepare Your Algorithm for Code Acceleration or Code Generation


The automated conversion process instruments your code and provides data type
proposals to help you convert your algorithm to fixed point.

MATLAB algorithms that you want to convert to fixed point automatically must comply
with code generation requirements and rules. To view the subset of the MATLAB

15-120
Automated Fixed-Point Conversion Best Practices

language that is supported for code generation, see “Functions and Objects Supported for
C and C++ Code Generation — Alphabetical List” on page 4-2.

To help you identify unsupported functions or constructs in your MATLAB code, add
the %#codegen pragma to the top of your MATLAB file. The MATLAB Code Analyzer
flags functions and constructs that are not available in the subset of the MATLAB
language supported for code generation. This advice appears in real time as you edit
your code in the MATLAB editor. For more information, see “Check Code With the Code
Analyzer” on page 19-6. The software provides a link to a report that identifies calls
to functions and the use of data types that are not supported for code generation. For
more information, see “Check Code Using the Code Generation Readiness Tool” on page
19-8.

Check for Fixed-Point Support for Functions Used in Your Algorithm


The app flags unsupported function calls found in your algorithm on the Function
Replacements tab. For example, if you use the fft function, which is not supported for
fixed point, the tool adds an entry to the table on this tab and indicates that you need to
specify a replacement function to use for fixed-point operations.

You can specify additional replacement functions. For example, functions like sin,
cos,and sqrt might support fixed point, but for better efficiency, you might want to
consider an alternative implementation like a lookup table or CORDIC-based algorithm.
The app provides an option to generate lookup table approximations for continuous
and stateless single-input, single-output functions in your original MATLAB code. See
“Replacing Functions Using Lookup Table Approximations” on page 15-127.

Manage Data Types and Control Bit Growth


The automated fixed-point conversion process automatically manages data types and
controls bit growth. It controls bit growth by using subscripted assignments, that

15-121
15 Fixed-Point Conversion

is, assignments that use the colon (:) operator, in the generated code. When you use
subscripted assignments, MATLAB overwrites the value of the left-hand side argument
but retains the existing data type and array size. In addition to preventing bit growth,
subscripted assignment reduces the number of casts in the generated fixed-point code
and makes the code more readable.

Convert to Fixed Point


What Are Your Goals for Converting to Fixed Point?

Before you start the conversion, consider your goals for converting to fixed point. Are
you implementing your algorithm in C or HDL? What are your target constraints? The
answers to these questions determine many fixed-point properties such as the available
word length, fraction length, and math modes, as well as available math libraries.

To set up these properties, use the Advanced settings.

For more information, see “Specify Type Proposal Options” on page 15-36.

Run With Fixed-Point Types and Compare Results

Create a test file to validate that the floating-point algorithm works as expected
before converting it to fixed point. You can use the same test file to propose fixed-point
data types, and to compare fixed-point results to the floating-point baseline after the

15-122
Automated Fixed-Point Conversion Best Practices

conversion. For more information, see “Running a Simulation” on page 15-91 and “Log
Data for Histogram” on page 15-102 .

Use the Histogram to Fine-Tune Data Type Settings


To fine-tune fixed-point type settings, use the histogram. To log data for histograms, in
the app, click the Simulate arrow and select Log data for histogram.

After simulation and static analysis:

• To view the histogram for a variable, on the Variables tab, click the Proposed Type
field for that variable.

You can view the effect of changing the proposed data types by dragging the edges
of the bounding box in the histogram window to change the proposed data type and
selecting or clearing the Signed option.
• If the values overflow and the range cannot fit the proposed type, the table shows
proposed types in red.

15-123
15 Fixed-Point Conversion

When the tool applies data types, it generates an html report that provides overflow
information and highlights overflows in red. Review the proposed data types.

Optimize Your Algorithm


Use fimath to Get Optimal Types for C or HDL

fimath properties define the rules for performing arithmetic operations on fi


objects, including math, rounding, and overflow properties. You can use the fimath
ProductMode and SumMode properties to retain optimal data types for C or HDL. HDL
can have arbitrary word length types in the generated HDL code whereas C requires
container types (uint8, uint16, uint32). Use the Advanced settings, see “Specify
Type Proposal Options” on page 15-36.
C

The KeepLSB setting for ProductMode and SumMode models the behavior of integer
operations in the C language, while KeepMSB models the behavior of many DSP devices.
Different rounding methods require different amounts of overhead code. Setting
the RoundingMethod property to Floor, which is equivalent to two's complement
truncation, provides the most efficient rounding implementation. Similarly, the standard
method for handling overflows is to wrap using modulo arithmetic. Other overflow
handling methods create costly logic. Whenever possible, set OverflowAction to Wrap.

MATLAB Code Best Practice Generated C Code


Code being compiled Issue int adder(short a, short b)
{
function y = adder(a,b) With the default word length set to int y;
y = a + b; 16 and the default fimath settings, int i0;
end int i1;
additional code is generated to
int i2;
implement saturation overflow, nearest
int i3;
Note: In the app, set rounding, and full-precision arithmetic. i0 = a;
Default word length to i1 = b;
16. if ((i0 & 65536) != 0) {
i2 = i0 | -65536;
} else {
i2 = i0 & 65535;
}

if ((i1 & 65536) != 0) {


i3 = i1 | -65536;

15-124
Automated Fixed-Point Conversion Best Practices

MATLAB Code Best Practice Generated C Code


} else {
i3 = i1 & 65535;
}

i0 = i2 + i3;
if ((i0 & 65536) != 0) {
y = i0 | -65536;
} else {
y = i0 & 65535;
}

return y;
}
Fix int adder(short a, short b)
{
To make the generated C code more return a + b;
efficient, choose fixed-point math }
settings that match your processor
types.

To customize fixed-point type proposals,


use the app Settings. Select fimath and
then set:
Rounding method Floor
Overflow action Wrap
Product mode KeepLSB
Sum mode KeepLSB
Product word 32
length
Sum word length 32

HDL

For HDL code generation, set:

• ProductMode and SumMode to FullPrecision


• Overflow action to Wrap
• Rounding method to Floor

15-125
15 Fixed-Point Conversion

Replace Built-in Functions with More Efficient Fixed-Point Implementations

Some MATLAB built-in functions can be made more efficient for fixed-point
implementation. For example, you can replace a built-in function with a Lookup table
implementation, or a CORDIC implementation, which requires only iterative shift-add
operations. For more information, see “Function Replacements” on page 15-104.

Reimplement Division Operations Where Possible

Often, division is not fully supported by hardware and can result in slow processing.
When your algorithm requires a division, consider replacing it with one of the following
options:

• Use bit shifting when the denominator is a power of two. For example, bitsra(x,3)
instead of x/8.
• Multiply by the inverse when the denominator is constant. For example, x*0.2
instead of x/5.
• If the divisor is not constant, use a temporary variable for the division. Doing so
results in a more efficient data type proposal and, if overflows occur, makes it easier
to see which expression is overflowing.

Eliminate Floating-Point Variables

For more efficient code, the automated fixed-point conversion process eliminates floating-
point variables. The one exception to this is loop indices because they usually become
integer types. It is good practice to inspect the fixed-point code after conversion to verify
that there are no floating-point variables in the generated fixed-point code.

Avoid Explicit Double and Single Casts


For the automated workflow, do not use explicit double or single casts in your MATLAB
algorithm to insulate functions that do not support fixed-point data types. The automated
conversion tool does not support these casts.

Instead of using casts, supply a replacement function. For more information, see
“Function Replacements” on page 15-104.

15-126
Replacing Functions Using Lookup Table Approximations

Replacing Functions Using Lookup Table Approximations


The MATLAB Coder software provides an option to generate lookup table
approximations for continuous and stateless single-input, single-output functions in your
original MATLAB code. These functions must be on the MATLAB path.

You can use this capability to handle functions that are not supported for fixed point
and to replace your own custom functions. The fixed-point conversion process infers
the ranges for the function and then uses an interpolated lookup table to replace the
function. You can control the interpolation method and number of points in the lookup
table. By adjusting these settings, you can tune the behavior of replacement function to
match the behavior of the original function as closely as possible.

The fixed-point conversion process generates one lookup table approximation per call site
of the function that needs replacement.

To use lookup table approximations in a MATLAB Coder project, see “Replace the exp
Function with a Lookup Table” on page 15-50 and “Replace a Custom Function with a
Lookup Table” on page 15-59.

To use lookup table approximations in the programmatic workflow, see


coder.approximation, “Replace the exp Function with a Lookup Table” on page
16-24, and “Replace a Custom Function with a Lookup Table” on page 16-26.

15-127
15 Fixed-Point Conversion

MATLAB Language Features Supported for Automated Fixed-Point


Conversion
Fixed-Point Designer supports the following MATLAB language features in automated
fixed-point conversion:

• N-dimensional arrays
• Matrix operations, including deletion of rows and columns
• Variable-sized data (see “Generate Code for Variable-Size Data” on page 21-105).
Range computation for variable–sized data is supported via simulation mode only.
Variable-sized data is not supported for comparison plotting.
• Subscripting (see “Incompatibility with MATLAB in Matrix Indexing Operations for
Code Generation”)
• Complex numbers (see “Code Generation for Complex Data”)
• Numeric classes (see “Supported Variable Types”)
• Double-precision, single-precision, and integer math
• Fixed-point arithmetic (see “Code Acceleration and Code Generation from MATLAB”)
• Program control statements if, switch, for, while, and break
• Arithmetic, relational, and logical operators
• Local functions
• Global variables
• Persistent variables (see “Define and Initialize Persistent Variables”)
• Structures, including arrays of structures. Range computation for structures is
supported via simulation mode only.
• Characters

The complete set of Unicode characters is not supported for code generation.
Characters are restricted to 8 bits of precision in generated code. Because many
mathematical operations require more than 8 bits of precision, it is recommended that
you do not perform arithmetic with characters if you intend to convert your MATLAB
algorithm to fixed point.
• MATLAB classes. Range computation for MATLAB classes is supported via
simulation mode only.

Automated conversion supports:

15-128
MATLAB Language Features Supported for Automated Fixed-Point Conversion

• Class properties
• Constructors
• Methods
• Specializations

It does not support class inheritance or packages. For more information, see “Fixed-
Point Code for MATLAB Classes”.
• Ability to call functions (see “Resolution of Function Calls for Code Generation” on
page 14-2)
• Subset of MATLAB toolbox functions (see “Functions Supported for Code Acceleration
or C Code Generation”).
• Subset of DSP System Toolbox System objects.

The DSP System Toolbox System objects supported for automated conversion are:

• dsp.ArrayVectorAdder
• dsp.BiquadFilter
• dsp.FIRDecimator
• dsp.FIRInterpolator
• dsp.FIRFilter (Direct Form and Direct Form Transposed only)
• dsp.FIRRateConverter
• dsp.LowerTriangularSolver
• dsp.LUFactor
• dsp.UpperTriangularSolver
• dsp.VariableFractionalDelay
• dsp.Window

15-129
15 Fixed-Point Conversion

Inspecting Data Using the Simulation Data Inspector

In this section...
“What Is the Simulation Data Inspector?” on page 15-130
“Import Logged Data” on page 15-130
“Export Logged Data” on page 15-130
“Group Signals” on page 15-131
“Run Options” on page 15-131
“Create Report” on page 15-131
“Comparison Options” on page 15-131
“Enabling Plotting Using the Simulation Data Inspector” on page 15-131
“Save and Load Simulation Data Inspector Sessions” on page 15-132

What Is the Simulation Data Inspector?


The Simulation Data Inspector allows you to view data logged during the fixed-point
conversion process. You can use it to inspect and compare the inputs and outputs to the
floating-point and fixed-point versions of your algorithm.

For fixed-point conversion, there is no programmatic interface for the Simulation Data
Inspector.

Import Logged Data


Before importing data into the Simulation Data Inspector, you must have previously
logged data to the base workspace or to a MAT-file.

Export Logged Data


The Simulation Data Inspector provides the capability to save data collected by the fixed-
point conversion process to a MAT-file that you can later reload. The format of the MAT-
file is different from the format of a MAT-file created from the base workspace.

15-130
Inspecting Data Using the Simulation Data Inspector

Group Signals
You can customize the organization of your logged data in the Simulation Data Inspector
Runs pane. By default, data is first organized by run. You can then organize your data
by logged variable or no hierarchy.

Run Options
You can configure the Simulation Data Inspector to:

• Append New Runs

In the Run Options dialog box, the default is set to add new runs to the bottom of the
run list. To append new runs to the top of the list, select Add new runs at top.
• Specify a Run Naming Rule

To specify run naming rules, in the Simulation Data Inspector toolbar, click Run
Options.

Create Report
You can create a report of the runs or comparison plots. Specify the name and location
of the report file. By default, the Simulation Data Inspector overwrites existing files. To
preserve existing reports, select If report exists, increment file name to prevent
overwriting.

Comparison Options
To change how signals are matched when runs are compared, specify the Align by and
Then by parameters and then click OK.

Enabling Plotting Using the Simulation Data Inspector


To enable the Simulation Data Inspector in the Fixed-Point Conversion tool, see “Enable
Plotting Using the Simulation Data Inspector” on page 15-68.

To enable the Simulation Data Inspector in the programmatic workflow, see “Enable
Plotting Using the Simulation Data Inspector” on page 16-28.

15-131
15 Fixed-Point Conversion

Save and Load Simulation Data Inspector Sessions


If you have data in the Simulation Data Inspector and you want to archive or share the
data to view in the Simulation Data Inspector later, save the Simulation Data Inspector
session. When you save a Simulation Data Inspector session, the MAT-file contains:

• All runs, data, and properties from the Runs and Comparisons panes.
• Check box selection state for data in the Runs pane.

Save a Session to a MAT-File

1 On the Visualize tab, click Save.


2 Browse to where you want to save the MAT-file to, name the file, and click Save.

Load a Saved Simulation Data Inspector Simulation

1 On the Visualize tab, click Open.


2 Browse, select the MAT-file saved from the Simulation Data Inspector, and click
Open.
3 If data in the session is plotted on multiple subplots, on the Format tab, click
Subplots and select the subplot layout.

15-132
Custom Plot Functions

Custom Plot Functions


The Fixed-Point Conversion tool provides a default time series based plotting function.
The conversion process uses this function at the test numerics step to show the floating-
point and fixed-point results and the difference between them. However, during fixed-
point conversion you might want to visualize the numerical differences in a view that is
more suitable for your application domain. For example, plots that show eye diagrams
and bit error differences are more suitable in the communications domain and histogram
difference plots are more suitable in image processing designs.

You can choose to use a custom plot function at the test numerics step. The Fixed-Point
Conversion tool facilitates custom plotting by providing access to the raw logged input
and output data before and after fixed-point conversion. You supply a custom plotting
function to visualize the differences between the floating-point and fixed-point results. If
you specify a custom plot function, the fixed-point conversion process calls the function
for each input and output variable, passes in the name of the variable and the function
that uses it, and the results of the floating-point and fixed-point simulations.

Your function should accept three inputs:

• A structure that holds the name of the variable and the function that uses it.

Use this information to:

• Customize plot headings and axes.


• Choose which variables to plot.
• Generate different error metrics for different output variables.
• A cell array to hold the logged floating-point values for the variable.

This cell array contains values observed during floating-point simulation of the
algorithm during the test numerics phase. You might need to reformat this raw data.
• A cell array to hold the logged values for the variable after fixed-point conversion.

This cell array contains values observed during fixed-point simulation of the
converted design.

For example, function customComparisonPlot(varInfo, floatVarVals,


fixedPtVarVals).

To use a custom plot function, in the Fixed-Point Conversion tool, select Advanced, and
then set Custom plot function to the name of your plot function.

15-133
15 Fixed-Point Conversion

In the programmatic workflow, set the coder.FixptConfig configuration object


PlotFunction property to the name of your plot function. See “Visualize Differences
Between Floating-Point and Fixed-Point Results” on page 16-29.

15-134
Data Type Issues in Generated Code

Data Type Issues in Generated Code


Within the fixed-point conversion HTML report, you have the option to highlight
MATLAB code that results in double, single, or expensive fixed-point operations.
Consider enabling these checks when trying to achieve a strict single, or fixed-point
design.

These checks are disabled by default.

Enable the Highlight Option in the MATLAB Coder App


1 On the Convert to Fixed Point page, to open the Settings dialog box, click the
Settings arrow .
2 Under Plotting and Reporting, set Highlight potential data type issues to
Yes.

When conversion is complete, open the fixed-point conversion HTML report to view the
highlighting. Click View report in the Type Validation Output tab.

Enable the Highlight Option at the Command Line


1 Create a fixed-point code configuration object:

cfg = coder.config('fixpt');
2 Set the HighlightPotentialDataTypeIssues property of the configuration object
to true.

cfg.HighlightPotentialDataTypeIssues = true;

Stowaway Doubles
When trying to achieve a strict-single or fixed-point design, manual inspection of code
can be time-consuming and error prone. This check highlights all expressions that result
in a double operation.

For a strict-single precision design, specify a standard math library that supports single-
precision implementations. To change the library for a project, during the Generate Code
step, in the project settings dialog box, on the Custom Code tab, set the Standard
math library to C99 (ISO).

15-135
15 Fixed-Point Conversion

Stowaway Singles
This check highlights all expressions that result in a single operation.

Expensive Fixed-Point Operations


The expensive fixed-point operations check identifies optimization opportunities for
fixed-point code. It highlights expressions in the MATLAB code that require cumbersome
multiplication or division, expensive rounding, expensive comparison, or multiword
operations. For more information on optimizing generated fixed-point code, see “Tips for
Making Generated Code More Efficient”.

Cumbersome Operations

Cumbersome operations most often occur due to insufficient range of output. Avoid
inputs to a multiply or divide operation that has word lengths larger than the base
integer type of your processor. Operations with larger word lengths can be handled in
software, but this approach requires much more code and is much slower.

Expensive Rounding

Traditional handwritten code, especially for control applications, almost always uses
"no effort" rounding. For example, for unsigned integers and two's complement signed
integers, shifting right and dropping the bits is equivalent to rounding to floor. To get
results comparable to, or better than, what you expect from traditional handwritten code,
use the floor rounding method. This check identifies expensive rounding operations in
multiplication and division.

Expensive Comparison Operations

Comparison operations generate extra code when a casting operation is required to do


the comparison. For example, when comparing an unsigned integer to a signed integer,
one of the inputs must first be cast to the signedness of the other before the comparison
operation can be performed. Consider optimizing the data types of the input arguments
so that a cast is not required in the generated code.

Multiword Operations

Multiword operations can be inefficient on hardware. When an operation has an input or


output data type larger than the largest word size of your processor, the generated code
contains multiword operations. You can avoid multiword operations in the generated

15-136
Data Type Issues in Generated Code

code by specifying local fimath properties for variables. You can also manually specify
input and output word lengths of operations that generate multiword code.

15-137
16

Automated Fixed-Point Conversion


Using Programmatic Workflow

• “Convert MATLAB Code to Fixed-Point C Code” on page 16-2


• “Propose Fixed-Point Data Types Based on Simulation Ranges” on page 16-5
• “Propose Fixed-Point Data Types Based on Derived Ranges” on page 16-11
• “Detect Overflows” on page 16-20
• “Replace the exp Function with a Lookup Table” on page 16-24
• “Replace a Custom Function with a Lookup Table” on page 16-26
• “Enable Plotting Using the Simulation Data Inspector” on page 16-28
• “Visualize Differences Between Floating-Point and Fixed-Point Results” on page
16-29
16 Automated Fixed-Point Conversion Using Programmatic Workflow

Convert MATLAB Code to Fixed-Point C Code


This example shows how to generate fixed-point C code from floating-point MATLAB
code using the programmatic workflow.

Set Up the Fixed-Point Configuration Object

Create a fixed-point configuration object and configure the test file name. For example:
fixptcfg = coder.config('fixpt');
fixptcfg.TestBenchName = 'fun_with_matlab_test';

Configure the Fixed-Point Configuration Object for Type Proposal

The fixed-point conversion software can propose types based on simulation ranges,
derived ranges, or both.

• For type proposal using only simulation ranges, enable the collection and reporting of
simulation range data. By default, derived range analysis is disabled.
fixptcfg.ComputeSimulationRanges = true;
• For type proposal using only derived ranges:

1 Specify the design range for input parameters. For example:


fixptcfg.addDesignRangeSpecification('dti', 'u_in', -1.0, 1.0);
2 Enable derived range analysis. Disable collection and reporting of simulation
range data.
fixptcfg.ComputeDerivedRanges = true;
fixptcfg.ComputeSimulationRanges = false;

Enable Numerics Testing

Select to run the test file to verify the generated fixed-point MATLAB code.
fixptcfg.TestNumerics = true;

Enable Plotting

Log inputs and outputs for comparison plotting. Select to plot using a custom function or
Simulation Data Inspector. For example, to plot using Simulation Data Inspector:
fixptcfg.LogIOForComparisonPlotting = true;
fixptcfg.PlotWithSimulationDataInspector = true;

16-2
Convert MATLAB Code to Fixed-Point C Code

Configure Additional Fixed-Point Configuration Object Properties


Configure additional fixed-point configuration object properties as necessary. For
example, define the default fixed-point word length:
fixptcfg.DefaultWordLength = 16;

Set Up the C Code Generation Configuration Object


Create a code configuration object for generation of a C static library, dynamic library, or
executable. Enable the code generation report. For example:
cfg = coder.config('lib');
cfg.GenerateReport = true;

Generate Fixed-Point C Code


Use the codegen function to convert the floating-point MATLAB function to fixed-point
C code. For example:
codegen -float2fixed fixptcfg -config cfg fun_with_matlab

View the Type Proposal Report


Click the link to the type proposal report for the entry-point function.

View the Comparison Plots


If you selected to log inputs and outputs for comparison plots, the conversion process
generates comparison plots.

• If you selected to use Simulation Data Inspector for these plots, the Simulation Data
Inspector opens. Use Simulation Data Inspector to view and compare the floating-
point and fixed-point run information.
• If you selected to use a custom plotting function for these plots, the conversion process
uses the custom function to generate the plots.

View the Generated Fixed-Point MATLAB and Fixed-Point C Code


Click the View Report link that follows the type proposal report. To view the fixed-point
MATLAB code, click the MATLAB code tab. To view the fixed-point C code, click the C
code tab.

See Also
coder.FixptConfig

16-3
16 Automated Fixed-Point Conversion Using Programmatic Workflow

Related Examples
• “Propose Fixed-Point Data Types Based on Simulation Ranges” on page 16-5
• “Propose Fixed-Point Data Types Based on Derived Ranges” on page 16-11
• “Enable Plotting Using the Simulation Data Inspector” on page 16-28

More About
• “Automated Fixed-Point Conversion” on page 15-86

16-4
Propose Fixed-Point Data Types Based on Simulation Ranges

Propose Fixed-Point Data Types Based on Simulation Ranges


This example shows how to propose fixed-point data types based on simulation range
data using the codegen function.

Prerequisites

To complete this example, you must install the following products:

• MATLAB
• MATLAB Coder
• Fixed-Point Designer
• C compiler (for most platforms, a default C compiler is supplied with MATLAB)
For a list of supported compilers, see http://www.mathworks.com/support/
compilers/current_release/.

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

Create a New Folder and Copy Relevant Files

1 Create a local working folder, for example, c:\ex_2ndOrder_filter.


2 Change to the docroot\toolbox\fixpoint\examples folder. At the MATLAB
command line, enter:
cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples'))
3 Copy the ex_2ndOrder_filter.m and ex_2ndOrder_filter_test.m files to
your local working folder.

Type Name Description


Function code ex_2ndOrder_filter.m Entry-point MATLAB function
Test file ex_2ndOrder_filter_test.m MATLAB script that tests
ex_2ndOrder_filter.m

The ex_2ndOrder_filter Function


function y = ex_2ndOrder_filter(x) %#codegen
persistent z
if isempty(z)
z = zeros(2,1);

16-5
16 Automated Fixed-Point Conversion Using Programmatic Workflow

end
% [b,a] = butter(2, 0.25)
b = [0.0976310729378175, 0.195262145875635, 0.0976310729378175];
a = [1, -0.942809041582063, 0.3333333333333333];

y = zeros(size(x));
for i = 1:length(x)
y(i) = b(1)*x(i) + z(1);
z(1) = b(2)*x(i) + z(2) - a(2) * y(i);
z(2) = b(3)*x(i) - a(3) * y(i);
end
end

The ex_2ndOrder_filter_test Script

The test script runs the ex_2ndOrder_filter function with three input signals: chirp,
step, and impulse to cover the full intended operating range of the system. The script
then plots the outputs.
% ex_2ndOrder_filter_test
%
% Define representative inputs
N = 256; % Number of points
t = linspace(0,1,N); % Time vector from 0 to 1 second
f1 = N/2; % Target frequency of chirp set to Nyquist
x_chirp = sin(pi*f1*t.^2); % Linear chirp from 0 to Fs/2 Hz in 1 second
x_step = ones(1,N); % Step
x_impulse = zeros(1,N); % Impulse
x_impulse(1) = 1;

% Run the function under test


x = [x_chirp;x_step;x_impulse];
y = zeros(size(x));
for i = 1:size(x,1)
y(i,:) = ex_2ndOrder_filter(x(i,:));
end

% Plot the results


titles = {'Chirp','Step','Impulse'}
clf
for i = 1:size(x,1)
subplot(size(x,1),1,i)
plot(t,x(i,:),t,y(i,:))
title(titles{i})

16-6
Propose Fixed-Point Data Types Based on Simulation Ranges

legend('Input','Output')
end
xlabel('Time (s)')
figure(gcf)

disp('Test complete.')

Set Up the Fixed-Point Configuration Object

Create a fixed-point configuration object and configure the test file name.

fixptcfg = coder.config('fixpt');
fixptcfg.TestBenchName = 'ex_2ndOrder_filter_test';

Set Up the C Code Generation Configuration Object

Create a code configuration object to generate a C static library. Enable the code
generation report.

cfg = coder.config('lib');
cfg.GenerateReport = true;

Collect Simulation Ranges and Generate Fixed-Point Code

Use the codegen function to convert the floating-point MATLAB function,


ex_2ndOrder_filter, to fixed-point C code. Set the default word length for the fixed-
point data types to 16.

fixptcfg.ComputeSimulationRanges = true;
fixptcfg.DefaultWordLength = 16;

% Derive ranges and generate fixed-point code


codegen -float2fixed fixptcfg -config cfg ex_2ndOrder_filter

codegen analyzes the floating-point code. Because you did not specify the input types for
the ex_2ndOrder_filter function, the conversion process infers types by simulating
the test file. The conversion process then derives ranges for variables in the algorithm.
It uses these derived ranges to propose fixed-point types for these variables. When the
conversion is complete, it generates a type proposal report.

View Range Information

Click the link to the type proposal report for the ex_2ndOrder_filter function,
ex_2ndOrder_filter_report.html.

16-7
16 Automated Fixed-Point Conversion Using Programmatic Workflow

The report opens in a web browser.

View Generated Fixed-Point MATLAB Code

codegen generates a fixed-point version of the ex_2ndOrder_filter.m


function, ex_2ndOrder_filter_fixpt.m, and a wrapper function that calls
ex_2ndOrder_filter_fixpt. These files are generated in the codegen
\ex_2ndOrder_filter\fixpt folder in your local working folder.

function y = ex_2ndOrder_filter_fixpt(x) %#codegen


fm = get_fimath();

persistent z
if isempty(z)
z = fi(zeros(2,1), 1, 16, 15, fm);

16-8
Propose Fixed-Point Data Types Based on Simulation Ranges

end
% [b,a] = butter(2, 0.25)
b = fi([0.0976310729378175, 0.195262145875635,...
0.0976310729378175], 0, 16, 18, fm);
a = fi([ 1, -0.942809041582063,...
0.3333333333333333], 1, 16, 14, fm);

y = fi(zeros(size(x)), 1, 16, 14, fm);


for i=1:length(x)
y(i) = b(1)*x(i) + z(1);
z(1) = fi_signed(b(2)*x(i) + z(2)) - a(2) * y(i);
z(2) = fi_signed(b(3)*x(i)) - a(3) * y(i);
end
end

function y = fi_signed(a)
coder.inline( 'always' );
if isfi( a ) && ~(issigned( a ))
nt = numerictype( a );
new_nt = numerictype( 1, nt.WordLength + 1, nt.FractionLength );
y = fi( a, new_nt, fimath( a ) );
else
y = a;
end
end

function fm = get_fimath()
fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap', 'ProductMode',...
'FullPrecision', 'MaxProductWordLength', 128, 'SumMode', 'FullPrecision',...
'MaxSumWordLength', 128);
end

View Generated Fixed-Point C Code

To view the code generation report for the C code generation, click the View Report link
that follows the type proposal report.

16-9
16 Automated Fixed-Point Conversion Using Programmatic Workflow

The code generation report opens and displays the generated code for
ex_2ndOrder_filter_fixpt.c.

See Also
coder.FixptConfig | codegen

Related Examples
• “Convert MATLAB Code to Fixed-Point C Code” on page 15-7
• “Propose Fixed-Point Data Types Based on Derived Ranges” on page 16-11

16-10
Propose Fixed-Point Data Types Based on Derived Ranges

Propose Fixed-Point Data Types Based on Derived Ranges


This example shows how to propose fixed-point data types based on static ranges using
the codegen function. The advantage of proposing data types based on derived ranges
is that you do not have to provide test files that exercise your algorithm over its full
operating range. Running such test files often takes a very long time so you can save
time by deriving ranges instead.

Prerequisites

To complete this example, you must install the following products:

• MATLAB
• MATLAB Coder
• Fixed-Point Designer
• C compiler (for most platforms, a default C compiler is supplied with MATLAB)
For a list of supported compilers, see http://www.mathworks.com/support/
compilers/current_release/

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

Create a New Folder and Copy Relevant Files

1 Create a local working folder, for example, c:\dti.


2 Change to the docroot\toolbox\fixpoint\examples folder. At the MATLAB
command line, enter:

cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples'))


3 Copy the dti.m and dti_test.m files to your local working folder.

Type Name Description


Function code dti.m Entry-point MATLAB function
Test file dti_test.m MATLAB script that tests
dti.m

The dti Function

The dti function implements a Discrete Time Integrator in MATLAB.

16-11
16 Automated Fixed-Point Conversion Using Programmatic Workflow

function [y, clip_status] = dti(u_in) %#codegen


% Discrete Time Integrator in MATLAB
%
% Forward Euler method, also known as Forward Rectangular, or left-hand
% approximation. The resulting expression for the output of the block at
% step 'n' is y(n) = y(n-1) + K * u(n-1)
%
init_val = 1;
gain_val = 1;
limit_upper = 500;
limit_lower = -500;

% variable to hold state between consecutive calls to this block


persistent u_state
if isempty(u_state)
u_state = init_val+1;
end

% Compute Output
if (u_state > limit_upper)
y = limit_upper;
clip_status = -2;
elseif (u_state >= limit_upper)
y = limit_upper;
clip_status = -1;
elseif (u_state < limit_lower)
y = limit_lower;
clip_status = 2;
elseif (u_state <= limit_lower)
y = limit_lower;
clip_status = 1;
else
y = u_state;
clip_status = 0;
end

% Update State
tprod = gain_val * u_in;
u_state = y + tprod;

function b = subFunction(a)
b = a*a;

16-12
Propose Fixed-Point Data Types Based on Derived Ranges

The dti_test Function

The test script runs the dti function with a sine wave input. The script then plots the
input and output signals.

% dti_test
% cleanup
clear dti

% input signal
x_in = sin(2.*pi.*(0:0.001:2)).';

pause(10)

len = length(x_in);
y_out = zeros(1,len);
is_clipped_out = zeros(1,len);

for ii=1:len
data = x_in(ii);
% call to the dti function
init_val = 0;
gain_val = 1;
upper_limit = 500;
lower_limit = -500;

% call to the design that does DTI


[y_out(ii), is_clipped_out(ii)] = dti(data);

end

figure('Name', [mfilename, '_plot'])


subplot(2,1,1)
plot(1:len,x_in)
xlabel('Time')
ylabel('Amplitude')
title('Input Signal (Sin)')

subplot(2,1,2)
plot(1:len,y_out)
xlabel('Time')
ylabel('Amplitude')
title('Output Signal (DTI)')

16-13
16 Automated Fixed-Point Conversion Using Programmatic Workflow

disp('Test complete.')

Set Up the Fixed-Point Configuration Object

Create a fixed-point configuration object and configure the test file name.

fixptcfg = coder.config('fixpt');
fixptcfg.TestBenchName = 'dti_test';

Specify Design Ranges

Specify design range information for the dti function input parameter u_in.

fixptcfg.addDesignRangeSpecification('dti', 'u_in', -1.0, 1.0)

Enable Plotting Using the Simulation Data Inspector

Select to run the test file to verify the generated fixed-point MATLAB code. Log inputs
and outputs for comparison plotting and select to use the Simulation Data Inspector to
plot the results.

fixptcfg.TestNumerics = true;
fixptcfg.LogIOForComparisonPlotting = true;
fixptcfg.PlotWithSimulationDataInspector = true;

Set Up the C Code Generation Configuration Object

Create a code configuration object to generate a C static library. Enable the code
generation report.

cfg = coder.config('lib');
cfg.GenerateReport = true;

Derive Ranges and Generate Fixed-Point Code

Use the codegen function to convert the floating-point MATLAB function, dti, to fixed-
point C code. Set the default word length for the fixed-point data types to 16.

fixptcfg.ComputeDerivedRanges = true;
fixptcfg.ComputeSimulationRanges = false;
fixptcfg.DefaultWordLength = 16;

% Derive ranges and generate fixed-point code

16-14
Propose Fixed-Point Data Types Based on Derived Ranges

codegen -float2fixed fixptcfg -config cfg dti

codegen analyzes the floating-point code. Because you did not specify the input types
for the dti function, the conversion process infers types by simulating the test file.
The conversion process then derives ranges for variables in the algorithm. It uses these
derived ranges to propose fixed-point types for these variables. When the conversion is
complete, it generates a type proposal report.

View Derived Range Information

Click the link to the type proposal report for the dti function, dti_report.html.

The report opens in a web browser.

16-15
16 Automated Fixed-Point Conversion Using Programmatic Workflow

View Generated Fixed-Point MATLAB Code

codegen generates a fixed-point version of the dti function, dti_fxpt.m, and a


wrapper function that calls dti_fxpt. These files are generated in the codegen\dti
\fixpt folder in your local working folder.

function [y, clip_status] = dti_fixpt(u_in) %#codegen


% Discrete Time Integrator in MATLAB
%
% Forward Euler method, also known as Forward Rectangular, or left-hand
% approximation. The resulting expression for the output of the block at
% step 'n' is y(n) = y(n-1) + K * u(n-1)
%
fm = get_fimath();

init_val = fi(1, 0, 1, 0, fm);


gain_val = fi(1, 0, 1, 0, fm);
limit_upper = fi(500, 0, 9, 0, fm);
limit_lower = fi(-500, 1, 10, 0, fm);

% variable to hold state between consecutive calls to this block


persistent u_state;
if isempty(u_state)
u_state = fi(init_val+fi(1, 0, 1, 0, fm), 1, 16, 6, fm);
end

% Compute Output
if (u_state > limit_upper)
y = fi(limit_upper, 1, 16, 6, fm);
clip_status = fi(-2, 1, 16, 13, fm);
elseif (u_state >= limit_upper)
y = fi(limit_upper, 1, 16, 6, fm);
clip_status = fi(-1, 1, 16, 13, fm);
elseif (u_state < limit_lower)
y = fi(limit_lower, 1, 16, 6, fm);
clip_status = fi(2, 1, 16, 13, fm);
elseif (u_state <= limit_lower)
y = fi(limit_lower, 1, 16, 6, fm);
clip_status = fi(1, 1, 16, 13, fm);
else
y = fi(u_state, 1, 16, 6, fm);
clip_status = fi(0, 1, 16, 13, fm);
end

16-16
Propose Fixed-Point Data Types Based on Derived Ranges

% Update State
tprod = fi(gain_val * u_in, 1, 16, 14, fm);
u_state(:) = y + tprod;
end

function fm = get_fimath()
fm = fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap', 'ProductMode',...
'FullPrecision', 'MaxProductWordLength', 128, 'SumMode', 'FullPrecision',...
'MaxSumWordLength', 128);
end

Compare Floating-Point and Fixed-Point Runs

Because you selected to log inputs and outputs for comparison plots and to use the
Simulation Data Inspector for these plots, the Simulation Data Inspector opens.

You can use the Simulation Data Inspector to view floating-point and fixed-point run
information and compare results. For example, to compare the floating-point and fixed-
point values for the output y, on the Compare tab, select y, and then click Compare
Runs.

The Simulation Data Inspector displays a plot of the baseline floating-point run against
the fixed-point run and the difference between them.

16-17
16 Automated Fixed-Point Conversion Using Programmatic Workflow

View Generated Fixed-Point C Code

To view the code generation report for the C code generation, click the View Report link
that follows the type proposal report.

16-18
Propose Fixed-Point Data Types Based on Derived Ranges

The code generation report opens and displays the generated code for dti_fixpt.c.

See Also
coder.FixptConfig | codegen

Related Examples
• “Convert MATLAB Code to Fixed-Point C Code” on page 15-7
• “Propose Fixed-Point Data Types Based on Simulation Ranges” on page 16-5

16-19
16 Automated Fixed-Point Conversion Using Programmatic Workflow

Detect Overflows
This example shows how to detect overflows at the command line. At the numerical
testing stage in the conversion process, the tool simulates the fixed-point code using
scaled doubles. It then reports which expressions in the generated code produce values
that would overflow the fixed-point data type.

Prerequisites

To complete this example, you must install the following products:

• MATLAB
• MATLAB Coder
• Fixed-Point Designer

In a local, writable folder, create a function, overflow.

function y = overflow(b,x,reset)
if nargin<3, reset = true; end
persistent z p
if isempty(z) || reset
p = 0;
z = zeros(size(b));
end
[y,z,p] = fir_filter(b,x,z,p);
end
function [y,z,p] = fir_filter(b,x,z,p)
y = zeros(size(x));
nx = length(x);
nb = length(b);
for n = 1:nx
p=p+1; if p>nb, p=1; end
z(p) = x(n);
acc = 0;
k = p;
for j=1:nb
acc = acc + b(j)*z(k);
k=k-1; if k<1, k=nb; end
end
y(n) = acc;
end
end

16-20
Detect Overflows

Create a test file, overflow_test.m to exercise the overflow algorithm.

function overflow_test
% The filter coefficients were computed using the FIR1 function from
% Signal Processing Toolbox.
% b = fir1(11,0.25);
b = [-0.004465461051254
-0.004324228005260
+0.012676739550326
+0.074351188907780
+0.172173206073645
+0.249588554524763
+0.249588554524763
+0.172173206073645
+0.074351188907780
+0.012676739550326
-0.004324228005260
-0.004465461051254]';

% Input signal
nx = 256;
t = linspace(0,10*pi,nx)';

% Impulse
x_impulse = zeros(nx,1); x_impulse(1) = 1;

% Max Gain
% The maximum gain of a filter will occur when the inputs line up with the
% signs of the filter's impulse response.
x_max_gain = sign(b)';
x_max_gain = repmat(x_max_gain,ceil(nx/length(b)),1);
x_max_gain = x_max_gain(1:nx);

% Sums of sines
f0=0.1; f1=2;
x_sines = sin(2*pi*t*f0) + 0.1*sin(2*pi*t*f1);

% Chirp
f_chirp = 1/16; % Target frequency
x_chirp = sin(pi*f_chirp*t.^2); % Linear chirp

x = [x_impulse, x_max_gain, x_sines, x_chirp];


titles = {'Impulse', 'Max gain', 'Sum of sines', 'Chirp'};

16-21
16 Automated Fixed-Point Conversion Using Programmatic Workflow

y = zeros(size(x));

for i=1:size(x,2)
reset = true;
y(:,i) = overflow(b,x(:,i),reset);
end

test_plot(1,titles,t,x,y)

end
function test_plot(fig,titles,t,x,y1)
figure(fig)
clf
sub_plot = 1;
font_size = 10;
for i=1:size(x,2)
subplot(4,1,sub_plot)
sub_plot = sub_plot+1;
plot(t,x(:,i),'c',t,y1(:,i),'k')
axis('tight')
xlabel('t','FontSize',font_size);
title(titles{i},'FontSize',font_size);
ax = gca;
ax.FontSize = 10;
end
figure(gcf)
end

Create a coder.FixptConfig object, fixptcfg, with default settings.

fixptcfg = coder.config('fixpt');

Set the test bench name. In this example, the test bench function name is
overflow_test.

fixptcfg.TestBenchName = 'overflow_test';

Set the default word length to 16.

fixptcfg.DefaultWordLength = 16;

Enable overflow detection.

fixptcfg.TestNumerics = true;
fixptcfg.DetectFixptOverflows = true;

16-22
Detect Overflows

Set the fimath Product mode and Sum mode to KeepLSB. These settings models the
behavior of integer operations in the C language.
fixptcfg.fimath = ...
['fimath(''RoundingMethod'',''Floor'',''OverflowAction'',' ...
'''Wrap'',''ProductMode'',''KeepLSB'',''SumMode'',''KeepLSB'')'];

Create a code generation configuration object to generate a standalone C static library.


cfg = coder.config('lib');

Convert the floating-point MATLAB function, overflow, to fixed-point C code. You do


not need to specify input types for the codegen command because it infers the types
from the test file.
codegen -float2fixed fixptcfg -config cfg overflow

The numerics testing phase reports an overflow.


Overflow error in expression 'acc + b( j )*z( k )'. Percentage of Current Range = 104%.

Determine if the addition or the multiplication in this expression overflowed. Set the
fimath ProductMode to FullPrecision so that the multiplication will not overflow,
and then run the codegen command again.

fixptcfg.fimath = ['fimath(''RoundingMethod'',''Floor'',''OverflowAction'',' ...


'''Wrap'',''ProductMode'',''FullPrecision'',''SumMode'',''KeepLSB'')'];
codegen -float2fixed fixptcfg -config cfg overflow

The numerics testing phase still reports an overflow, indicating that it is the addition in
the expression that is overflowing.

16-23
16 Automated Fixed-Point Conversion Using Programmatic Workflow

Replace the exp Function with a Lookup Table


This example shows how to replace the exp function with a lookup table approximation
in the generated fixed-point code using the codegen function.

Prerequisites

To complete this example, you must install the following products:

• MATLAB
• MATLAB Coder
• Fixed-Point Designer
• C compiler (for most platforms, a default C compiler is supplied with MATLAB).
For a list of supported compilers, see http://www.mathworks.com/support/
compilers/current_release/ .

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

Create Algorithm and Test Files

1 Create a MATLAB function, my_fcn.m, that calls the exp function.

function y = my_fcn(x)
y = exp(x);
end
2 Create a test file, my_fcn_test.m, that uses my_fcn.m.

close all

x = linspace(-10,10,1e3);
for itr = 1e3:-1:1
y(itr) = my_fcn( x(itr) );
end
plot( x, y );

Configure Approximation

Create a function replacement configuration object to approximate the exp function,


using the default settings of linear interpolation and 1000 points in the lookup table.
q = coder.approximation('exp');

16-24
Replace the exp Function with a Lookup Table

Set Up Configuration Object

Create a coder.FixptConfig object, fixptcfg. Specify the test file name and enable
numerics testing. Associate the function replacement configuration object with the fixed-
point configuration object.
fixptcfg = coder.config('fixpt');
fixptcfg.TestBenchName = 'my_fcn_test';
fixptcfg.TestNumerics = true;
fixptcfg.DefaultWordLength = 16;
fixptcfg.addApproximation(q);

Convert to Fixed Point

Generate fixed-point MATLAB code.


codegen -float2fixed fixptcfg my_fcn

View Generated Fixed-Point Code

To view the generated fixed-point code, click the link to my_fcn_fixpt.

The generated code contains a lookup table approximation, replacement_exp, for the
exp function. The fixed-point conversion process infers the ranges for the function and
then uses an interpolated lookup table to replace the function. By default, the lookup
table uses linear interpolation, 1000 points, and the minimum and maximum values
detected by running the test file.

The generated fixed-point function, my_fcn_fixpt, calls this approximation instead of


calling exp.

function y = my_fcn_fixpt(x)
fm = get_fimath();

y = fi(replacement_exp(x), 0, 16, 1, fm);


end

You can now test the generated fixed-point code and compare the results against the
original MATLAB function. If the behavior of the generated fixed-point code does not
match the behavior of the original code closely enough, modify the interpolation method
or number of points used in the lookup table and then regenerate code.

16-25
16 Automated Fixed-Point Conversion Using Programmatic Workflow

Replace a Custom Function with a Lookup Table


This example shows how to replace a custom function with a lookup table approximation
function using the codegen function.

Prerequisites

To complete this example, you must install the following products:

• MATLAB
• MATLAB Coder
• Fixed-Point Designer
• C compiler (for most platforms, a default C compiler is supplied with MATLAB)
For a list of supported compilers, see http://www.mathworks.com/support/
compilers/current_release/

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

Create a MATLAB function, custom_fcn.m. This is the function that you want to
replace.

function y = custom_fcn(x)
y = 1./(1+exp(-x));
end

Create a wrapper function that calls custom_fcn.m.

function y = call_custom_fcn(x)
y = custom_fcn(x);
end

Create a test file, custom_test.m, that uses call_custom_fcn.m.

close all

x = linspace(-10,10,1e3);
for itr = 1e3:-1:1
y(itr) = call_custom_fcn( x(itr) );
end
plot( x, y );

16-26
Replace a Custom Function with a Lookup Table

Create a function replacement configuration object to approximate custom_fcn. Specify


the function handle of the custom function and set the number of points to use in the
lookup table to 50.
q = coder.approximation('Function','custom_fcn',...
'CandidateFunction',@custom_fcn, 'NumberOfPoints',50);

Create a coder.FixptConfig object, fixptcfg. Specify the test file name and enable
numerics testing. Associate the function replacement configuration object with the fixed-
point configuration object.
fixptcfg = coder.config('fixpt');
fixptcfg.TestBenchName = 'custom_test';
fixptcfg.TestNumerics = true;
fixptcfg.addApproximation(q);

Generate fixed-point MATLAB code.


codegen -float2fixed fixptcfg call_custom_fcn

codegen generates fixed-point MATLAB code in call_custom_fcn_fixpt.m.

To view the generated fixed-point code, click the link to call_custom_fcn_fixpt.

The generated code contains a lookup table approximation, replacement_custom_fcn,


for the custom_fcn function. The fixed-point conversion process infers the ranges for
the function and then uses an interpolated lookup table to replace the function. The
lookup table uses 50 points as specified. By default, it uses linear interpolation and the
minimum and maximum values detected by running the test file.

The generated fixed-point function, call_custom_fcn_fixpt, calls this approximation


instead of calling custom_fcn.

function y = call_custom_fcn_fixpt(x)
fm = get_fimath();

y = fi(replacement_custom_fcn(x), 0, 14, 14, fm);


end

You can now test the generated fixed-point code and compare the results against the
original MATLAB function. If the behavior of the generated fixed-point code does not
match the behavior of the original code closely enough, modify the interpolation method
or number of points used in the lookup table and then regenerate code.

16-27
16 Automated Fixed-Point Conversion Using Programmatic Workflow

Enable Plotting Using the Simulation Data Inspector


You can use the Simulation Data Inspector to inspect and compare floating-point and
fixed-point input and output data logged using the codegen function. At the MATLAB
command line:

1 Create a fixed-point configuration object and configure the test file name.
fixptcfg = coder.config('fixpt');
fixptcfg.TestBenchName = 'dti_test';
2 Select to run the test file to verify the generated fixed-point MATLAB code. Log
inputs and outputs for comparison plotting and select to use the Simulation Data
Inspector to plot the results.
fixptcfg.TestNumerics = true;
fixptcfg.LogIOForComparisonPlotting = true;
fixptcfg.PlotWithSimulationDataInspector = true;
3 Generate fixed-point MATLAB code using codegen.

codegen -float2fixed fixptcfg -config cfg dti

For an example, see “Propose Fixed-Point Data Types Based on Derived Ranges” on page
16-11.

16-28
Visualize Differences Between Floating-Point and Fixed-Point Results

Visualize Differences Between Floating-Point and Fixed-Point


Results
This example shows how to configure the codegen function to use a custom plot function
to compare the behavior of the generated fixed-point code against the behavior of the
original floating-point MATLAB code.

By default, when the LogIOForComparisonPlotting option is enabled, the conversion


process uses a time series based plotting function to show the floating-point and fixed-
point results and the difference between them. However, during fixed-point conversion
you might want to visualize the numerical differences in a view that is more suitable
for your application domain. This example shows how to customize plotting and produce
scatter plots at the test numerics step of the fixed-point conversion.

Prerequisites

To complete this example, you must install the following products:

• MATLAB
• MATLAB Coder
• Fixed-Point Designer
• C compiler (for most platforms, a default C compiler is supplied with MATLAB)
For a list of supported compilers, see http://www.mathworks.com/support/
compilers/current_release/

You can use mex -setup to change the default compiler. See “Change Default
Compiler”.

Create a New Folder and Copy Relevant Files

1 Create a local working folder, for example, c:\custom_plot.


2 Change to the docroot\toolbox\fixpoint\examples folder. At the MATLAB
command line, enter:

cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples'))


3 Copy the myFilter.m, myFilterTest.m, plotDiff.m, and filterData.mat files
to your local working folder.

16-29
16 Automated Fixed-Point Conversion Using Programmatic Workflow

Type Name Description


Function code myFilter.m Entry-point MATLAB function
Test file myFilterTest.m MATLAB script that tests
myFilter.m
Plotting function plotDiff.m Custom plot function
MAT-fiile filterData.mat Data to filter.

The myFilter Function

function [y, ho] = myFilter(in)

persistent b h;
if isempty(b)
b = complex(zeros(1,16));
h = complex(zeros(1,16));
h(8) = 1;
end

b = [in, b(1:end-1)];
y = b*h.';

errf = 1-sqrt(real(y)*real(y) + imag(y)*imag(y));


update = 0.001*conj(b)*y*errf;

h = h + update;
h(8) = 1;
ho = h;

end

The myFilterTest File

% load data
data = load('filterData.mat');
d = data.symbols;

for idx = 1:4000


y = myFilter(d(idx));
end

16-30
Visualize Differences Between Floating-Point and Fixed-Point Results

The plotDiff Function

% varInfo - structure with information about the variable. It has the following fields
% i) name
% ii) functionName
% floatVals - cell array of logged original values for the 'varInfo.name' variable
% fixedVals - cell array of logged values for the 'varInfo.name' variable after
% Fixed-Point conversion.
function plotDiff(varInfo, floatVals, fixedVals)
varName = varInfo.name;
fcnName = varInfo.functionName;

% convert from cell to matrix


floatVals = cell2mat(floatVals);
fixedVals = cell2mat(fixedVals);

% escape the '_'s because plot titles treat these as subscripts


escapedVarName = regexprep(varName,'_','\\_');
escapedFcnName = regexprep(fcnName,'_','\\_');

% flatten the values


flatFloatVals = floatVals(1:end);
flatFixedVals = fixedVals(1:end);

% build Titles
floatTitle = [ escapedFcnName ' > ' 'float : ' escapedVarName ];
fixedTitle = [ escapedFcnName ' > ' 'fixed : ' escapedVarName ];

data = load('filterData.mat');

switch varName
case 'y'
x_vec = data.symbols;

figure('Name', 'Comparison plot', 'NumberTitle', 'off');

% plot floating point values


y_vec = flatFloatVals;
subplot(1, 2, 1);
plotScatter(x_vec, y_vec, 100, floatTitle);

% plot fixed point values


y_vec = flatFixedVals;
subplot(1, 2, 2);

16-31
16 Automated Fixed-Point Conversion Using Programmatic Workflow

plotScatter(x_vec, y_vec, 100, fixedTitle);

otherwise
% Plot only output 'y' for this example, skip the rest
end

end

function plotScatter(x_vec, y_vec, n, figTitle)


% plot the last n samples
x_plot = x_vec(end-n+1:end);
y_plot = y_vec(end-n+1:end);

hold on
scatter(real(x_plot),imag(x_plot), 'bo');

hold on
scatter(real(y_plot),imag(y_plot), 'rx');

title(figTitle);
end

Set Up Configuration Object

1 Create a coder.FixptConfig object.

fxptcfg = coder.config('fixpt');
2 Specify the test file name and custom plot function name. Enable logging and
numerics testing.

fxptcfg.TestBenchName = 'myFilterTest';
fxptcfg.PlotFunction = 'plotDiff';
fxptcfg.TestNumerics = true;
fxptcfg. LogIOForComparisonPlotting = true;
fxptcfg.DefaultWordLength = 16;

Convert to Fixed Point

Convert the floating-point MATLAB function, myFilter, to fixed-point MATLAB code.


You do not need to specify input types for the codegen command because it infers the
types from the test file.

codegen -args {complex(0, 0)} -float2fixed fxptcfg myFilter

16-32
Visualize Differences Between Floating-Point and Fixed-Point Results

The conversion process generates fixed-point code using a default word length of 16 and
then runs a fixed-point simulation by running the myFilterTest.m function and calling
the fixed-point version of myFilter.m.

Because you selected to log inputs and outputs for comparison plots and to use the
custom plotting function, plotDiff.m, for these plots, the conversion process uses this
function to generate the comparison plot.

The plot shows that the fixed-point results do not closely match the floating-point results.

Increase the word length to 24 and then convert to fixed point again.

fxptcfg.DefaultWordLength = 24;
codegen -args {complex(0, 0)} -float2fixed fxptcfg myFilter

16-33
16 Automated Fixed-Point Conversion Using Programmatic Workflow

The increased word length improved the results. This time, the plot shows that the fixed-
point results match the floating-point results.

16-34
17

Single-Precision Conversion

• “Generate Single-Precision C Code at the Command Line” on page 17-2


• “Generate Single-Precision C Code Using the MATLAB Coder App” on page 17-8
• “Generate Single-Precision MATLAB Code” on page 17-14
• “Choose a Single-Precision Conversion Workflow” on page 17-23
• “Single-Precision Conversion Best Practices” on page 17-24
• “Warnings from Conversion to Single-Precision C/C++ Code” on page 17-28
• “Combining Integers and Double-Precision Numbers” on page 17-32
• “MATLAB Language Features Supported for Single-Precision Conversion” on page
17-33
17 Single-Precision Conversion

Generate Single-Precision C Code at the Command Line

In this section...
“Prerequisites” on page 17-2
“Create a Folder and Copy Relevant Files” on page 17-2
“Determine the Type of the Input Argument” on page 17-4
“Generate and Run Single-Precision MEX to Verify Numerical Behavior” on page
17-5
“Generate Single-Precision C Code” on page 17-5
“View the Generated Single-Precision C Code” on page 17-6
“View Potential Data Type Issues” on page 17-6

This example shows how to generate single-precision C code from double-precision


MATLAB code at the command line.

Prerequisites
To complete this example, install the following products:

• MATLAB
• MATLAB Coder
• Fixed-Point Designer
• C compiler (for most platforms, a default C compiler is supplied with MATLAB).
For a list of supported compilers, see http://www.mathworks.com/support/
compilers/current_release/.

To change the default compiler, you can use mex -setup. See “Change Default
Compiler”.

Create a Folder and Copy Relevant Files


1 Create a local working folder, for example, c:\ex_2ndOrder_filter.
2 Change to the docroot\toolbox\fixpoint\examples folder. At the MATLAB
command line, enter:

17-2
Generate Single-Precision C Code at the Command Line

cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples'))


3 Copy the ex_2ndOrder_filter.m and ex_2ndOrder_filter_test.m files to
your local working folder.

Type Name Description


Function code ex_2ndOrder_filter.m Entry-point MATLAB function
Test file ex_2ndOrder_filter_test.m MATLAB script that tests
ex_2ndOrder_filter.m

The ex_2ndOrder_filter Function

function y = ex_2ndOrder_filter(x) %#codegen


persistent z
if isempty(z)
z = zeros(2,1);
end
% [b,a] = butter(2, 0.25)
b = [0.0976310729378175, 0.195262145875635, 0.0976310729378175];
a = [1, -0.942809041582063, 0.3333333333333333];

y = zeros(size(x));
for i = 1:length(x)
y(i) = b(1)*x(i) + z(1);
z(1) = b(2)*x(i) + z(2) - a(2) * y(i);
z(2) = b(3)*x(i) - a(3) * y(i);
end
end

The ex_2ndOrder_filter_test Script

It is a best practice to create a separate test script for preprocessing and


postprocessing such as:

• Setting up input values.


• Calling the function under test.
• Outputting the test results.

17-3
17 Single-Precision Conversion

To cover the full intended operating range of the system, the test script runs the
ex_2ndOrder_filter function with three input signals: chirp, step, and impulse.
The script then plots the outputs.

% ex_2ndOrder_filter_test
%
% Define representative inputs
N = 256; % Number of points
t = linspace(0,1,N); % Time vector from 0 to 1 second
f1 = N/2; % Target frequency of chirp set to Nyquist
x_chirp = sin(pi*f1*t.^2); % Linear chirp from 0 to Fs/2 Hz in 1 second
x_step = ones(1,N); % Step
x_impulse = zeros(1,N); % Impulse
x_impulse(1) = 1;

% Run the function under test


x = [x_chirp;x_step;x_impulse];
y = zeros(size(x));
for i = 1:size(x,1)
y(i,:) = ex_2ndOrder_filter(x(i,:));
end

% Plot the results


titles = {'Chirp','Step','Impulse'}
clf
for i = 1:size(x,1)
subplot(size(x,1),1,i)
plot(t,x(i,:),t,y(i,:))
title(titles{i})
legend('Input','Output')
end
xlabel('Time (s)')
figure(gcf)

disp('Test complete.')

Determine the Type of the Input Argument


To determine the type of the input argument x, use coder.getArgTypes to run the test
file ex_2ndOrder_filter_test.m

types = coder.getArgTypes('ex_2ndOrder_filter_test', 'ex_2ndOrder_filter');

17-4
Generate Single-Precision C Code at the Command Line

The test file runs and displays the outputs of the filter for each of the input signals.
coder.getArgTypes determines that the input type of x is 1x256 double.

Generate and Run Single-Precision MEX to Verify Numerical Behavior


1 Before you generate single-precision C code, generate a single-precision MEX
function that you can use to verify the behavior of the generated single-precision
code. To indicate that you want the single-precision MEX code, use the -singleC
option.

codegen -singleC ex_2ndOrder_filter -args types -report

During MEX generation, the code generation software detects single-precision


conversion issues. Before you generate C/C++ code, fix these issues. This example
does not have single-precision conversion issues.

The generated MEX accepts single-precision and double-precision input. You can
use the same test file to run the double-precision MATLAB function and the single-
precision MEX function. You do not have to modify the test file to call the single-
precision MEX function.
2 Run the test file ex_2ndOrder_filter_test.m. This file calls the double-precision
MATLAB function ex_2ndOrder_filter.m.

ex_2ndOrder_filter_test
3 The test file runs and displays the outputs of the filter for each of the input signals.
4 Run the test file ex_2ndOrder_filter_test, replacing calls to the double-
precision ex_2ndOrder_filter function with calls to the single-precision
ex_2ndOrder_filter_mex function.

coder.runTest('ex_2ndOrder_filter_test', 'ex_2ndOrder_filter')
5 The test file runs and displays the outputs of the filter for each of the input signals.
The single-precision MEX function produces the same results as the double-precision
MATLAB function.

Generate Single-Precision C Code


1 Create a code configuration object for generation of a C static library, dynamic
library, or executable. To avoid use of double-precision implementations of math
functions, specify 'C99' for the standard math library.

17-5
17 Single-Precision Conversion

cfg = coder.config('lib');
cfg.TargetLangStandard = 'C99 (ISO)'
2 To generate single-precision C code, call codegen with the -singleC option. Enable
generation of the code generation report.

codegen -config cfg -singleC ex_2ndOrder_filter -args {types{1}} -report

View the Generated Single-Precision C Code


To view the code generation report for the C code generation, click the View Report
link.

The code generation report displays the generated code for ex_2ndOrder_filter.c.

• Double-precision variables have type float in the C code.


• The index i is an integer.

View Potential Data Type Issues


When you generate single-precision code, codegen enables highlighting of potential data
type issues in the code generation report. If codegen cannot remove a double-precision
operation, the report highlights the MATLAB expression that results in the operation.

Click the MATLAB code tab. Under Highlight, the report shows that no double-
precision operations remain.

See Also
codegen | coder.config | coder.getArgTypes | coder.runTest

Related Examples
• “Generate Single-Precision C Code Using the MATLAB Coder App” on page
17-8
• “Generate Single-Precision MATLAB Code” on page 17-14

More About
• “Single-Precision Conversion Best Practices” on page 17-24

17-6
Generate Single-Precision C Code at the Command Line

• “Warnings from Conversion to Single-Precision C/C++ Code” on page 17-28

17-7
17 Single-Precision Conversion

Generate Single-Precision C Code Using the MATLAB Coder App


In this section...
“Prerequisites” on page 17-8
“Create a Folder and Copy Relevant Files” on page 17-8
“Open the MATLAB Coder App” on page 17-10
“Enable Single-Precision Conversion” on page 17-11
“Select the Source Files” on page 17-11
“Define Input Types” on page 17-12
“Check for Run-Time Issues” on page 17-12
“Generate Single-Precision C Code” on page 17-12
“View the Generated C Code” on page 17-13
“View Potential Data Type Issues” on page 17-13

This example shows how to generate single-precision C code from double-precision


MATLAB code by using the MATLAB Coder app.

Prerequisites
To complete this example, install the following products:

• MATLAB
• MATLAB Coder
• Fixed-Point Designer
• C compiler (for most platforms, a default C compiler is supplied with MATLAB).
For a list of supported compilers, see http://www.mathworks.com/support/
compilers/current_release/.

To change the default compiler, you can use mex -setup. See “Change Default
Compiler”.

Create a Folder and Copy Relevant Files


1 Create a local working folder, for example, c:\ex_2ndOrder_filter.

17-8
Generate Single-Precision C Code Using the MATLAB Coder App

2 Change to the docroot\toolbox\fixpoint\examples folder. At the MATLAB


command line, enter:

cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples'))


3 Copy the ex_2ndOrder_filter.m and ex_2ndOrder_filter_test.m files to
your local working folder.

Type Name Description


Function code ex_2ndOrder_filter.m Entry-point MATLAB function
Test file ex_2ndOrder_filter_test.m MATLAB script that tests
ex_2ndOrder_filter.m

The ex_2ndOrder_filter Function

function y = ex_2ndOrder_filter(x) %#codegen


persistent z
if isempty(z)
z = zeros(2,1);
end
% [b,a] = butter(2, 0.25)
b = [0.0976310729378175, 0.195262145875635, 0.0976310729378175];
a = [1, -0.942809041582063, 0.3333333333333333];

y = zeros(size(x));
for i = 1:length(x)
y(i) = b(1)*x(i) + z(1);
z(1) = b(2)*x(i) + z(2) - a(2) * y(i);
z(2) = b(3)*x(i) - a(3) * y(i);
end
end

The ex_2ndOrder_filter_test Script

It is a best practice to create a separate test script for preprocessing and


postprocessing such as:

• Setting up input values.


• Calling the function under test.
• Outputting the test results.

17-9
17 Single-Precision Conversion

To cover the full intended operating range of the system, the test script runs the
ex_2ndOrder_filter function with three input signals: chirp, step, and impulse.
The script then plots the outputs.

% ex_2ndOrder_filter_test
%
% Define representative inputs
N = 256; % Number of points
t = linspace(0,1,N); % Time vector from 0 to 1 second
f1 = N/2; % Target frequency of chirp set to Nyquist
x_chirp = sin(pi*f1*t.^2); % Linear chirp from 0 to Fs/2 Hz in 1 second
x_step = ones(1,N); % Step
x_impulse = zeros(1,N); % Impulse
x_impulse(1) = 1;

% Run the function under test


x = [x_chirp;x_step;x_impulse];
y = zeros(size(x));
for i = 1:size(x,1)
y(i,:) = ex_2ndOrder_filter(x(i,:));
end

% Plot the results


titles = {'Chirp','Step','Impulse'}
clf
for i = 1:size(x,1)
subplot(size(x,1),1,i)
plot(t,x(i,:),t,y(i,:))
title(titles{i})
legend('Input','Output')
end
xlabel('Time (s)')
figure(gcf)

disp('Test complete.')

Open the MATLAB Coder App


1 Navigate to the work folder that contains the file for this example.
2 On the MATLAB Toolstrip Apps tab, under Code Generation, click the app icon.

17-10
Generate Single-Precision C Code Using the MATLAB Coder App

Enable Single-Precision Conversion


Set Numeric Conversion to Convert to single precision.

Select the Source Files


1 To add the entry-point function ex_2ndOrder_filter to the project, browse
to the file ex_2ndOrder_filter.m, and then click Open. By default, the app
saves information and settings for this project in the current folder in a file named
ex_2ndOrder_filter.prj.
2 Click Next to go to the Define Input Types step.

17-11
17 Single-Precision Conversion

The app screens ex_2ndOrder_filter.m for code violations and code generation
readiness issues. The app does not find issues in ex_2ndOrder_filter.m.

Define Input Types


1 On the Define Input Types page, to add ex_2ndOrder_filter_test as a test
file, browse to ex_2ndOrder_filter_test. Click Open.
2 Click Autodefine Input Types.

The test file runs and displays the outputs of the filter for each of the input signals.
The app determines that the input type of x is double(1x256).
3 Click Next to go to the Check for Run-Time Issues step.

Check for Run-Time Issues


To detect and fix single-precision conversion issues, perform the Check for Run-Time
Issues step.

1 On the Check for Run-Time Issues page, the app populates the test file field with
ex_2ndOrder_filter_test, the test file that you used to define the input types.
2 Click Check for Issues.

The app generates a single-precision MEX function from ex_2ndOrder_filter.


It runs the test file ex_2ndOrder_filter_test replacing calls to
ex_2ndOrder_filter with calls to the generated MEX function. If the app finds
issues, it provides warning and error messages. Click a message to highlight the
problematic code in a window where you can edit the code. In this example, the app
does not detect issues.
3 Click Next to go to the Generate Code page.

Generate Single-Precision C Code


1 In the Generate dialog box, set Build type to Static Library.
2 Set Language to C.
3 To avoid use of double-precision standard math functions, set the standard
math library to C99 (ISO). Click More Settings. Then, click Custom Code. Set
Standard math library to C99 (ISO).

17-12
Generate Single-Precision C Code Using the MATLAB Coder App

4 For other settings, use the default values.


5 To generate the code, click Generate.

MATLAB Coder builds the project and generates a C static library and supporting
files in the default subfolder, codegen/lib/ex_2ndOrder_filter.

View the Generated C Code


The app displays the generated code for ex_2ndOrder_filter.c.

• Double-precision variables have type float in the C code.


• The index i is an integer.

View Potential Data Type Issues


When you generate single-precision code, the app enables highlighting of potential data
type issues in the code generation report. If the app cannot remove a double-precision
operation, the report highlights the MATLAB expression that results in the operation.

To open the code generation report, click the View Report link. Click the MATLAB
code tab. Under Highlight, the report shows that no double-precision operations
remain.

Related Examples
• “Generate Single-Precision C Code at the Command Line” on page 17-2

More About
• “Single-Precision Conversion Best Practices” on page 17-24
• “Warnings from Conversion to Single-Precision C/C++ Code” on page 17-28

17-13
17 Single-Precision Conversion

Generate Single-Precision MATLAB Code


This example shows how to generate single-precision MATLAB code from double-
precision MATLAB code. This example shows the single-precision conversion workflow
that you use when you want to see single-precision MATLAB code or use verification
options. Optionally, you can also generate single-precision C/C++ code.

Prerequisites
To complete this example, install the following products:

• MATLAB
• MATLAB Coder
• Fixed-Point Designer
• C compiler (for most platforms, a default C compiler is supplied with MATLAB).
For a list of supported compilers, see http://www.mathworks.com/support/
compilers/current_release/.

To change the default compiler, you can use mex -setup. See “Change Default
Compiler”.

Create a Folder and Copy Relevant Files


1 Create a local working folder, for example, c:\ex_2ndOrder_filter.
2 Change to the docroot\toolbox\fixpoint\examples folder. At the MATLAB
command line, enter:

cd(fullfile(docroot, 'toolbox', 'fixpoint', 'examples'))


3 Copy the ex_2ndOrder_filter.m and ex_2ndOrder_filter_test.m files to
your local working folder.

Type Name Description


Function code ex_2ndOrder_filter.m Entry-point MATLAB function
Test file ex_2ndOrder_filter_test.m MATLAB script that tests
ex_2ndOrder_filter.m

17-14
Generate Single-Precision MATLAB Code

The ex_2ndOrder_filter Function

function y = ex_2ndOrder_filter(x) %#codegen


persistent z
if isempty(z)
z = zeros(2,1);
end
% [b,a] = butter(2, 0.25)
b = [0.0976310729378175, 0.195262145875635, 0.0976310729378175];
a = [1, -0.942809041582063, 0.3333333333333333];

y = zeros(size(x));
for i = 1:length(x)
y(i) = b(1)*x(i) + z(1);
z(1) = b(2)*x(i) + z(2) - a(2) * y(i);
z(2) = b(3)*x(i) - a(3) * y(i);
end
end

The ex_2ndOrder_filter_test Script

It is a best practice to create a separate test script for preprocessing and


postprocessing such as:

• Setting up input values.


• Calling the function under test.
• Outputting the test results.

To cover the full intended operating range of the system, the test script runs the
ex_2ndOrder_filter function with three input signals: chirp, step, and impulse.
The script then plots the outputs.

% ex_2ndOrder_filter_test
%
% Define representative inputs
N = 256; % Number of points
t = linspace(0,1,N); % Time vector from 0 to 1 second
f1 = N/2; % Target frequency of chirp set to Nyquist
x_chirp = sin(pi*f1*t.^2); % Linear chirp from 0 to Fs/2 Hz in 1 second
x_step = ones(1,N); % Step
x_impulse = zeros(1,N); % Impulse

17-15
17 Single-Precision Conversion

x_impulse(1) = 1;

% Run the function under test


x = [x_chirp;x_step;x_impulse];
y = zeros(size(x));
for i = 1:size(x,1)
y(i,:) = ex_2ndOrder_filter(x(i,:));
end

% Plot the results


titles = {'Chirp','Step','Impulse'}
clf
for i = 1:size(x,1)
subplot(size(x,1),1,i)
plot(t,x(i,:),t,y(i,:))
title(titles{i})
legend('Input','Output')
end
xlabel('Time (s)')
figure(gcf)

disp('Test complete.')

Set Up the Single-Precision Configuration Object


Create a single-precision configuration object. Specify the test file name. Verify the
single-precision code using the test file. Plot the error between the double-precision code
and single-precision code. Use the default values for the other properties.
scfg = coder.config('single');
scfg.TestBenchName = 'ex_2ndOrder_filter_test';
scfg.TestNumerics = true;
scfg.LogIOForComparisonPlotting = true;

Generate Single-Precision MATLAB Code


To convert the double-precision MATLAB function, ex_2ndOrder_filter, to single-
precision MATLAB code, use the codegen function with the -double2single option.
codegen -double2single scfg ex_2ndOrder_filter

codegen analyzes the double-precision code. The conversion process infers


types by running the test file because you did not specify the input types for the

17-16
Generate Single-Precision MATLAB Code

ex_2ndOrder_filter function. The conversion process selects single-precision types for


the double-precision variables. It selects int32 for index variables. When the conversion
is complete, codegen generates a type proposal report.

View the Type Proposal Report


To see the types that the conversion process selected for the variables, open
the type proposal report for the ex_2ndOrder_filter function. Click the link
ex_2ndOrder_filter_report.html.

The report opens in a web browser. The conversion process converted:

• Double-precision variables to single.


• The index i to int32. The conversion process casts index and dimension variables to
int32.

17-17
17 Single-Precision Conversion

View Generated Single-Precision MATLAB Code


To view the report for the generation of the single-precision MATLAB code, in the
Command Window:

1 Scroll to the Generate Single-Precision Code step. Click the View report
link.
2 On the MATLAB code tab, under Functions, click
ex_2ndOrder_filter_single.

17-18
Generate Single-Precision MATLAB Code

The code generation report displays the single-precision MATLAB code for
ex_2ndOrder_filter.

View Potential Data Type Issues


When you generate single-precision code, codegen enables highlighting of potential data
type issues in code generation reports. If codegen cannot remove a double-precision
operation, the report highlights the MATLAB expression that results in the operation.
Click the MATLAB code tab. Under Highlight, the report shows that no double-
precision operations remain.

Compare the Double-Precision and Single-Precision Variables


You can see the comparison plots for the input x and output y because you selected to log
inputs and outputs for comparison plots .

17-19
17 Single-Precision Conversion

17-20
Generate Single-Precision MATLAB Code

Optionally Generate Single-Precision C Code


If you also want to generate single-precision C code, create a code configuration object for
C code generation. Use this configuration object with the -config option of the codegen
function. For example:

17-21
17 Single-Precision Conversion

1 Create a code configuration object for generation of a C static library. Specify 'C99'
for the standard math library.
cfg = coder.config('lib');
cfg.TargetLangStandard = 'C99 (ISO)';
2 Generate the C code. Enable generation of the code generation report.
codegen -double2single scfg -config cfg ex_2ndOrder_filter -report
3 To view the code generation report for the C code generation, click the View Report
link.

The code generation report displays the generated code for


ex_2ndOrder_filter.c.

• Double-precision variables have type float in the C code.


• The index i is an integer.

When you generate single-precision code, codegen enables highlighting of potential


data type issues in the code generation report. If codegen cannot remove a double-
precision operation, the report highlights the MATLAB expression that results in the
operation.

Click the MATLAB code tab. Under Highlight, the report shows that no double-
precision operations remain.

See Also
coder.SingleConfig | codegen | coder.config

Related Examples
• “Generate Single-Precision C Code Using the MATLAB Coder App” on page 17-8
• “Generate Single-Precision C Code at the Command Line” on page 17-2

More About
• “Single-Precision Conversion Best Practices” on page 17-24
• “Warnings from Conversion to Single-Precision C/C++ Code” on page 17-28

17-22
Choose a Single-Precision Conversion Workflow

Choose a Single-Precision Conversion Workflow


The information in the following table helps you to decide which single-precision
workflow to use.

Goal Use
You want to generate single-precision C/ codegen with -singleC option. See
C++ code in the most direct way using the “Generate Single-Precision C Code at the
codegen function. Command Line” on page 17-2.
You want to generate single-precision C/ The MATLAB Coder app with Numeric
C++ code in the most direct way using the Conversion set to Convert to single
MATLAB Coder app. precision. See “Generate Single-
Precision C Code Using the MATLAB
Coder App” on page 17-8.
You want to generate only single-precision codegen with the -double2single option
MATLAB code. You want to see the single- and a coder.SingleConfig object. See
precision MATLAB code or use verification “Generate Single-Precision MATLAB Code”
options. on page 17-14.
You want to generate single-precision codegen with the -double2single
MATLAB code, and then generate single- option and a coder.SingleConfig object.
precision C/C++ code from the single- Also, use the -config object with a code
precision MATLAB code. configuration object for the output type
that you want. See “Generate Single-
Precision MATLAB Code” on page 17-14.

17-23
17 Single-Precision Conversion

Single-Precision Conversion Best Practices


In this section...
“Use Integers for Index Variables” on page 17-24
“Limit Use of assert Statements” on page 17-24
“Initialize MATLAB Class Properties in Constructor” on page 17-24
“Provide a Test File That Calls Your MATLAB Function” on page 17-24
“Prepare Your Code for Code Generation” on page 17-25
“Verify Double-Precision Code Before Single-Precision Conversion” on page 17-25
“Best Practices for Generation of Single-Precision C/C++ Code” on page 17-25
“Best Practices for Generation of Single-Precision MATLAB Code” on page 17-26

Use Integers for Index Variables


In MATLAB code that you want to convert to single precision, it is a best practice
to use integers for index variables. However, if the code does not use integers for
index variables, when possible single-precision conversion using codegen with -
double2single tries to detect the index variables and select int32 types for them.

Limit Use of assert Statements


• Do not use assert statements to define the properties of input arguments.
• Do not use assert statements to test the type of a variable. For example, do not use
assert(isa(a, 'double'))

Initialize MATLAB Class Properties in Constructor


Do not initialize MATLAB class properties in the properties block. Instead, use the
constructor to initialize the class properties.

Provide a Test File That Calls Your MATLAB Function


Separate your core algorithm from other code that you use to test and verify the results.
Create a test file that calls your double-precision MATLAB algorithm. You can use the
test file to:

17-24
Single-Precision Conversion Best Practices

• Automatically define properties of the top-level function inputs.


• Verify that the double-precision algorithm behaves as you expect. The double-
precision behavior is the baseline against which you compare the behavior of the
single-precision versions of your algorithm.
• Compare the behavior of the single-precision version of your algorithm to the double-
precision baseline.

For best results, the test file must exercise the algorithm over its full operating range.

Prepare Your Code for Code Generation


MATLAB code that you want to convert to single precision must comply with code
generation requirements. See “MATLAB Programming for Code Generation”.

To help you identify unsupported functions or constructs in your MATLAB code, add
the %#codegen pragma to the top of your MATLAB file. When you edit your code in the
MATLAB editor, the MATLAB Code Analyzer flags functions and constructs that are
not supported for code generation. See “Check Code With the Code Analyzer” on page
19-6. When you use the MATLAB Coder app, the app screens your code for code
generation readiness. At the function line, you can use the Code Generation Readiness
Tool. See “Check Code Using the Code Generation Readiness Tool” on page 19-8.

Verify Double-Precision Code Before Single-Precision Conversion


Before you begin the single-precision conversion process, verify that you can successfully
generate code from your double-precision MATLAB code. Generate and run a MEX
version of your double-precision MATLAB code so that you can:

• Detect and fix compilation issues.


• Verify that the generated single-precision code behaves the same as the double-
precision MATLAB code.

See “Why Test MEX Functions in MATLAB?” on page 20-2.

Best Practices for Generation of Single-Precision C/C++ Code


When you generate single-precision C/C++ code by using the MATLAB Coder app or
codegen with the -singleC option, follow these best practices:

17-25
17 Single-Precision Conversion

Set the Standard Math Library to C99

When you generate C/C++ libraries or executables, by default, the code generation
software uses the C89 /C90 (ANSI) standard math library. When you generate single-
precision C/C++ code using this library, the code generation software warns you if a
function in this library uses double precision. To avoid this warning, set the standard
math library to C99 (ISO). See “Warnings from Conversion to Single-Precision C/C++
Code” on page 17-28.

Cast Large Double Constant to Integer

For a constant greater than 2^24, in your original double-precision MATLAB function,
cast the constant to an integer type that is large enough for the constant value. For
example:
a = int32(2^24 + 1);

Generate and Run Single-Precision MEX Before Generating Single-Precision C/C++ Code

Before you generate single-precision C code, generate and run a single-precision MEX
version of your MATLAB code. When you follow this practice, you can detect and fix
compiler issues. You can verify that the single-precision MEX function has the same
functionality as the MATLAB code.

If you use codegen with -singleC:

1 Generate the single-precision MEX.


2 Call coder.runTest to run your test file, replacing calls to the double-precision
MATLAB code with calls to the single-precision MEX code.

If you use the MATLAB Coder app, perform the Check for Run-Time Issues step with
single-precision conversion enabled.

Best Practices for Generation of Single-Precision MATLAB Code


When you use codegen with the -double2single option to generate single-precision
MATLAB code, follow these best practices:

Use the -args Option to Specify Input Properties

When you generate single-precision MATLAB code, if you specify a test file, you do
not have to specify argument properties with the -args option. In this case, the code

17-26
Single-Precision Conversion Best Practices

generation software runs the test file to determine the properties of the input types.
However, running the test file can slow the code generation. It is a best practice to
determine the input properties one time with coder.getArgTypes. Then, pass the
properties to the -args option. For example:

types = coder.getArgTypes('myfun_test', 'myfun');


scfg = coder.config('single');
codegen -double2single scfg -args types myfun -report

When you repeat the code generation in the same MATLAB session, this practice saves
you time.

Test Numerics and Log I/O Data

When you use the codegen function with the -double2single option to generate
single-precision MATLAB code, enable numerics testing and I/O data logging for
comparison plots. To use numerics testing, you must provide a test file that calls
your MATLAB function. To enable numerics testing and I/O data logging, create
a coder.SingleConfig object. Set the TestBenchName, TestNumerics, and
LogIOForComparisonPlotting properties. For example:

scfg = coder.config('single');
scfg.TestBenchName = 'mytest';
scfg.TestNumerics = true;
scfg.LogIOForComparisonPlotting = true;

More About
• “Warnings from Conversion to Single-Precision C/C++ Code” on page 17-28

17-27
17 Single-Precision Conversion

Warnings from Conversion to Single-Precision C/C++ Code


When you generate single-precision C/C++ code by using the MATLAB Coder app or
codegen with the -singleC option, you can receive the following warnings.

Function Uses Double-Precision in the C89/C90 Standard


If the standard math library is C89/C90, the conversion process warns you when a
function uses double-precision code in the C89/C90 standard.

Consider the function mysine.

function c = mysine(a)
c = sin(a);
end

Generate single-precision code for mysine.

x = -pi:0.01:pi;
codegen -singleC mysine -args {x} -config:lib -report

codegen warns that sin uses double-precision in the C89/C90 (ANSI) standard.
Warning: The function sin uses double-precision in the C89/C90 (ANSI) standard. For single-precision
code, consider using the C99 (ISO) standard or use your own function.

To open the code generation report, click the View Report link.

To see that double-precision operations remain in the converted code, click the MATLAB
code tab. Under Highlight, select the Double-precision operations check box. Under
Functions, click mysine.

In the code pane, the report highlights the sin call.

17-28
Warnings from Conversion to Single-Precision C/C++ Code

To address this warning, specify use of the C99 (ISO) standard math library.

• At the command line:


cfg = coder.config('lib');
cfg.TargetLangStandard = 'C99 (ISO)'
• In the app, in the project build settings, on the Custom Code tab, set Standard
math library to C99 (ISO).

Built-In Function Is Implemented in Double-Precision


Some built-in MATLAB functions are implemented using double-precision operations.
The conversion process warns that the code generated for these functions contains
double-precision operations.

Consider the function geterf that calls the built-in function erf.

function y = geterf(x)
y = erf(x);
end

Generate single-precision code forgeterf.

codegen -singleC -config:lib -args {1} geterf -report

codegen warns that erf is implemented in double precision.

17-29
17 Single-Precision Conversion

Warning: The builtin function erf is implemented in double-precision. Code generated for this
function will contain doubles.

To open the code generation report, click the View Report link.

To see that double-precision operations remain in the converted code, click the MATLAB
code tab. Under Highlight, select the Double-precision operations check box. Under
Functions, click geterf.

In the code pane, the report highlights the erf call.

To address this warning, rewrite your code so that it does not use the function that is
implemented in double precision.

Built-In Function Returns Double-Precision


If a built-in MATLAB function returns a double-precision output, the conversion process
generates a warning.

Consider the function mysum that calls the built-in function sum.

function y = mysum(x)
y = sum(int32(x));
end

Generate single-precision code formysum.

17-30
Warnings from Conversion to Single-Precision C/C++ Code

A = 1:10;
codegen -singleC -config:lib -args {A} mysum -report

codegen warns that mysum is implemented in double precision.


Warning: The output of builtin function sum is double-precision and has been cast to
single-precision. The code generated for the builtin function may still contain doubles.

To open the code generation report, click the View Report link.

To see that double-precision operations remain in the converted code, click the MATLAB
code tab. Under Highlight, select the Double-precision operations check box. Under
Functions, click mysum.

In the code pane, the report highlights the sum call.

To address this warning, specify that you want the function to return the 'native'
class.
(sum(int32(1), 'native')

Using this option causes the function to return the same type as the input.

More About
• “Single-Precision Conversion Best Practices” on page 17-24

17-31
17 Single-Precision Conversion

Combining Integers and Double-Precision Numbers


MATLAB supports the combination of integers of the same class and scalar double-
precision numbers. MATLAB does not support the combination of integers and single-
precision numbers. If you use the MATLAB Coder app or codegen with the -singleC
option to generate single-precision C/C++ code, your MATLAB code cannot combine
integers and double-precision numbers. Converting an expression that combines integers
and doubles results in an illegal MATLAB expression. To work around this limitation,
cast the numbers so that the types of the numbers match. Either cast the integer
numbers to double-precision or cast the double-precision numbers to the integer class.

For example, consider the function dut that returns the sum of a and b.

function c = dut(a,b)
c = a + b;
end

Generate single-precision code using codegen with the -singleC option. Specify that
the first argument is double and the second argument is int32.
codegen -singleC -config:lib dut -args {0, int32(2)} -report

Code generation fails. The message suggests that you cast the operands so that they have
the same types.

Rewrite the code so that it cast a to the type of b.

function c = dut(a,b)
c = int32(a) + b;
end

17-32
MATLAB Language Features Supported for Single-Precision Conversion

MATLAB Language Features Supported for Single-Precision


Conversion
In this section...
“MATLAB Language Features Supported for Single-Precision Conversion” on page
17-33
“MATLAB Language Features Not Supported for Single-Precision Conversion” on page
17-34

MATLAB Language Features Supported for Single-Precision Conversion


Single-precision conversion supports the following MATLAB language features:

• N-dimensional arrays.
• Matrix operations, including deletion of rows and columns.
• Variable-size data (see “Generate Code for Variable-Size Data” on page 21-105).
Comparison plotting does not support variable-size data.
• Subscripting (see “Incompatibility with MATLAB in Matrix Indexing Operations for
Code Generation” on page 7-32).
• Complex numbers (see “Code Generation for Complex Data” on page 6-4).
• Numeric classes (see “Supported Variable Types” on page 5-17).
• Program control statements if, switch, for, while, and break.
• Arithmetic, relational, and logical operators.
• Local functions.
• Global variables.
• Persistent variables (see “Define and Initialize Persistent Variables” on page 5-10).
• Structures.
• Characters.

Single-precision conversion does not support the complete set of Unicode characters.
Characters are restricted to 8 bits of precision in generated code. Many mathematical
operations require more than 8 bits of precision. If you intend to convert your
MATLAB algorithm to single precision, it is a best practice not to perform arithmetic
with characters.

17-33
17 Single-Precision Conversion

• MATLAB classes. Single-precision conversion supports:

• Class properties
• Constructors
• Methods
• Specializations

It does not support class inheritance or packages.


• Function calls (see “Resolution of Function Calls for Code Generation” on page 14-2)
• varargin and varargout are supported when you use codegen with -singleC.
They are not supported when you use codegen with -double2single.

MATLAB Language Features Not Supported for Single-Precision


Conversion
Single-precision conversion does not support the following features:

• Anonymous functions
• Cell arrays
• Function handles
• Java
• Nested functions
• Recursion
• Sparse matrices
• try/catch statements
• varargin and varargout are not supported when you use codegen with -
double2single. They are supported when you use codegen with -singleC

17-34
18

Setting Up a MATLAB Coder Project

• “Set Up a MATLAB Coder Project” on page 18-2


• “Specify Properties of Entry-Point Function Inputs Using the App” on page 18-3
• “Automatically Define Input Types Using the App” on page 18-4
• “Define Input Parameters by Example Using the App” on page 18-5
• “Define or Edit Input Parameter Type Using the App” on page 18-12
• “Define Constant Input Parameters Using the App” on page 18-23
• “Define Inputs Programmatically in the MATLAB File” on page 18-24
• “Add Global Variables Using the App” on page 18-25
• “Specify Global Variable Type and Initial Value Using the App” on page 18-26
• “Undo and Redo Changes to Type Definitions in the App” on page 18-30
• “Changing Output Type” on page 18-31
• “Code Generation Readiness Screening in the MATLAB Coder App” on page 18-34
• “Slow Operations in MATLAB Coder App” on page 18-36
• “Unable to Open a MATLAB Coder Project” on page 18-37
18 Setting Up a MATLAB Coder Project

Set Up a MATLAB Coder Project


1 To open the app, on the MATLAB Toolstrip Apps tab, under Code Generation,
click the MATLAB Coder app icon.
2 Create a project or open an existing project. See “Create a Project” on page 18-2
and “Open an Existing Project” on page 18-2.
3 If the app detects code generation readiness issues in your entry-point functions,
address these issues.
4 Define the properties of the entry-point function input types. See “Specify Properties
of Entry-Point Function Inputs Using the App” on page 18-3.
5 Check for run-time issues. Provide code or a test file that the app can use to test your
code. The app generates a MEX function. It runs your test code or test file, replacing
calls to your MATLAB function with calls to the MEX function. This step is optional.
However, it is a best practice to perform this step. You can detect and fix run-time
errors that are harder to diagnose in the generated C code.
6 Configure the build settings. Select the build type, language, and production
hardware. Optionally, modify other build settings. See “Configure Build Settings” on
page 21-26.

You can now generate code.

Create a Project
On the Select Source Files page, specify the MATLAB files from which you want to
generate code. An entry-point function is a function that you call from MATLAB. Do not
add files that have spaces in their names.

The app creates a project that has the name of the first entry-point function.

Open an Existing Project


1
On the app toolbar, click and select Open existing project.
2 Type or select the project.

The app closes other open projects.

If the project is a Fixed-Point Converter project, and you have a Fixed-Point Designer
license, the project opens in the Fixed-Point Converter app.

18-2
Specify Properties of Entry-Point Function Inputs Using the App

Specify Properties of Entry-Point Function Inputs Using the App

Why Specify Input Properties?


Because C and C++ are statically typed languages, at compile time, MATLAB Coder
must determine the properties of all variables in the MATLAB files. To infer variable
properties in MATLAB files, MATLAB Coder must identify the properties of the inputs
to the primary function, also known as the top-level or entry-point function. Therefore,
if your primary function has inputs, you must specify the properties of these inputs to
MATLAB Coder. If your primary function has no input parameters, you do not need to
specify properties of inputs to local functions or external functions called by the primary
function.

Unless you use the tilde (~) character to specify unused function inputs, you must specify
the same number and order of inputs as the MATLAB function . If you use the tilde
character, the inputs default to real, scalar doubles.

See Also

• “Properties to Specify” on page 21-45

Specify an Input Definition Using the App


Specify an input definition using one of the following methods:

• Autodefine Input Types


• Define Type
• Define by Example
• Define Constant
• “Define Inputs Programmatically in the MATLAB File” on page 18-24

18-3
18 Setting Up a MATLAB Coder Project

Automatically Define Input Types Using the App


If you specify a test file that calls the project entry-point functions, the MATLAB Coder
app can infer the input parameter types by running the test file. If a test file calls an
entry-point function multiple times with different size inputs, the app takes the union of
the inputs. The app infers that the inputs are variable size, with an upper bound equal to
the size of the largest input.

Before using the app to automatically define function input parameter types, you must
add at least one entry-point file to your project. You must also specify code that calls your
entry-point functions with the expected input types. It is a best practice to provide a test
file that calls your entry-point functions. The test file can be either a MATLAB function
or a script. The test file must call the entry-point function at least once.

To automatically define input types:

1 On the Define Input Types page, specify a test file. Alternatively, you can enter
code directly.
2 Click Autodefine Input Types.

The app runs the test file and infers the types for entry-point input parameters. The
app displays the inferred types.

Note: If you automatically define the input types, the entry-point functions must be in a
writable folder.

18-4
Define Input Parameters by Example Using the App

Define Input Parameters by Example Using the App


In this section...
“Define an Input Parameter by Example” on page 18-5
“Specify Input Parameters by Example” on page 18-6
“Specify a Structure Type Input Parameter by Example” on page 18-7
“Specify a Cell Array Type Input Parameter by Example” on page 18-7
“Specify an Enumerated Type Input Parameter by Example” on page 18-9
“Specify a Fixed-Point Input Parameter by Example” on page 18-10

Define an Input Parameter by Example


1 On the Define Input Types page, click Let me enter input or global types
directly.
2 Click the field to the right of the input parameter that you want to define.

18-5
18 Setting Up a MATLAB Coder Project

3 Select Define by Example.


4 In the field to the right of the parameter, enter a MATLAB expression. The variable
has the class, size, and complexity of the value of the expression.

Specify Input Parameters by Example


This example shows how to specify a 1-by-4 vector of unsigned 16-bit integers.

1 On the Define Input Types page, click Let me enter input or global types
directly.
2 Click the field to the right of the input parameter that you want to define.
3 Select Define by Example.
4 In the field to the right of the parameter, enter:
zeros(1,4,'uint16')

The input type is uint16(1x4).


5 Optionally, after you specify the input type, you can specify that the input is variable
size. For example, select the second dimension.

6 To specify that the second dimension is variable size with an upper bound of 4, select
:4. Alternatively, to specify that the second dimension is unbounded, select :Inf.

Alternatively, you can specify that the input is variable size by using the
coder.newtype function. Enter the following MATLAB expression:

coder.newtype('uint16',[1 4],[0 1])

Note: To specify that an input is a double-precision scalar, enter 0.

18-6
Define Input Parameters by Example Using the App

Specify a Structure Type Input Parameter by Example


This example shows how to specify a structure with two fields a and b. The input type of
a is scalar double. The input type of b is scalar char.

1 On the Define Input Types page, click Let me enter input or global types
directly.
2 Click the field to the right of the input parameter that you want to define.
3 Select Define by Example.
4 In the field to the right of the parameter, enter:
struct('a', 1, 'b', 'x')

The type of the input parameter is struct(1x1). The type of field a is


double(1x1). The type of field b is char(1x1)
5 For an array of structures, to specify the size of each dimension, click the dimension
and specify the size. For example, enter 4 for the first dimension.
6 To specify that the second dimension is variable size with an upper bound of 4, select
:4. Alternatively, to specify that the second dimension is unbounded select :Inf.

Alternatively, specify the size of the array of structures in the struct function call.
For example, struct('a', { 1 2}, 'b', {'x', 'y'}) specifies a 1x2 array of
structures with fields a and b. The type of field a is double(1x1). The type of field b is
char(1x1).

To modify the type definition, see “Specify a Structure Input Parameter” on page
18-14.

Specify a Cell Array Type Input Parameter by Example


This example shows how to specify a cell array input by example. When you define a
cell array by example, the app determines whether the cell array is homogeneous or
heterogeneous. See “Homogeneous vs. Heterogeneous Cell Arrays” on page 9-2. If you
want to control whether the cell array is homogeneous or heterogeneous, specify the cell
array by type. See “Specify a Cell Array Input Parameter” on page 18-18.

1 On the Define Input Types page, click Let me enter input or global types
directly.
2 Click the field to the right of the input parameter that you want to define.

18-7
18 Setting Up a MATLAB Coder Project

3 Select Define by Example.


4 In the field to the right of the parameter, enter an example cell array.

• If all cell array elements have the same properties, the cell array is homogeneous.
For example, enter:

{1 2 3}
The input is a 1x3 cell array. The type of each element is double(1x1).

The colon inside curly braces{:} indicates that all elements have the same
properties.
• If elements of the cell array have different classes, the cell array is
heterogeneous. For example, enter:

{'a', 1}
The input is a 1x2 cell array. For a heterogeneous cell array, the app lists each
element. The type of the first element is char(1x1). The type of the second
element is double(1x1).

• For some example cell arrays. the classification as homogeneous or heterogeneous


is ambiguous. For these cell arrays, the app uses heuristics to determine whether
the cell array is homogeneous or heterogeneous. For example, for the example cell
array, enter:

{1 [2 3]}
The elements have the same class, but different sizes. The app determines that
the input is a 1x2 heterogeneous cell array. The type of the first element is
double(1x1). The type of the second element is double(1x2).
18-8
Define Input Parameters by Example Using the App

However, the example cell array, {1 [2 3]}, can also be a homogeneous


cell array whose elements are 1x:2 double. If you want this cell array to be
homogeneous, do one of the following:

• Specify the cell array input by type. Specify that the input is a homogeneous
cell array. Specify that the elements are 1x:2 double. See “Specify a Cell Array
Input Parameter” on page 18-18.
• Right-click the variable. Select Homogeneous. Specify that the elements are
1x:2 double.

If you use coder.typeof to specify that the example cell array is variable size,
the app makes the cell array homogeneous. For example, for the example input,
enter:
coder.typeof({1 [2 3]}, [1 3], [0 1])
The app determines that the input is a 1x:3 homogeneous cell array whose
elements are 1x:2 double.

To modify the type definition, see “Specify a Cell Array Input Parameter” on page
18-18.

Specify an Enumerated Type Input Parameter by Example


This example shows how to specify that an input uses the enumerated type MyColors.

Suppose that MyColors.m is on the MATLAB path.


classdef MyColors < int32
enumeration
green(1),
red(2),
end
end

To specify that an input has the enumerated type MyColors:

18-9
18 Setting Up a MATLAB Coder Project

1 On the Define Input Types page, click Let me enter input or global types
directly.
2 Click the field to the right of the input parameter that you want to define.

3 Select Define by Example.


4 In the field to the right of the parameter, enter the following MATLAB expression:
MyColors.red

Specify a Fixed-Point Input Parameter by Example


To specify fixed-point inputs, Fixed-Point Designer software must be installed.

This example shows how to specify a signed fixed-point type with a word length of eight
bits, and a fraction length of three bits.

1 On the Define Input Types page, click Let me enter input or global types
directly.
2 Click the field to the right of the input parameter that you want to define.

18-10
Define Input Parameters by Example Using the App

3 Select Define by Example.


4 In the field to the right of the parameter, enter:
fi(10, 1, 8, 3)

The app sets the type of input u to fi(1x1). By default, if you do not specify a
local fimath, the app uses the default fimath. See “fimath for Sharing Arithmetic
Rules”.

Optionally, modify the fixed-point properties or the size of the input. See “Specify a
Fixed-Point Input Parameter by Type” on page 18-14 and “Define or Edit Input
Parameter Type Using the App” on page 18-12.

18-11
18 Setting Up a MATLAB Coder Project

Define or Edit Input Parameter Type Using the App

In this section...
“Define or Edit an Input Parameter Type” on page 18-12
“Specify an Enumerated Type Input Parameter by Type” on page 18-13
“Specify a Fixed-Point Input Parameter by Type” on page 18-14
“Specify a Structure Input Parameter” on page 18-14
“Specify a Cell Array Input Parameter” on page 18-18

Define or Edit an Input Parameter Type


The following procedure shows you how to define or edit double, single, int64, int32,
int16, int8, uint64, uint32, uint16, uint8, logical, and char types.

For more information about defining other types, see the following table.

Input Type Link


A structure (struct) “Specify a Structure Input Parameter” on
page 18-14
A cell array (cell (Homogeneous) or cell “Specify a Cell Array Input Parameter” on
(Heterogeneous)) page 18-18
A fixed-point data type (embedded.fi) “Specify a Fixed-Point Input Parameter by
Type” on page 18-14
An input by example (Define by “Define Input Parameters by Example
Example) Using the App” on page 18-5
A constant (Define Constant) “Define Constant Input Parameters Using
the App” on page 18-23

1 Click the field to the right of the input parameter name.


2 Optionally, for numeric types, to make the parameter a complex type, select the
Complex number check box.
3 Select the input type.

18-12
Define or Edit Input Parameter Type Using the App

The app displays the selected type. It displays the size options.

4 From the list, select whether your input is a scalar, a 1 x n vector, a m x 1 vector,
or a m x n matrix. By default, if you do not select a size option, the app defines
inputs as scalars.
5 Optionally, if your input is not scalar, enter sizes m and n. You can specify:

• Fixed size, for example, 10.


• Variable size, up to a specified limit, by using the : prefix. For example, to specify
that your input can vary in size up to 10, enter :10.
• Unbounded variable size by entering :Inf.

You can edit the size of each dimension.

Specify an Enumerated Type Input Parameter by Type


To specify that an input uses the enumerated type MyColors:

1 Suppose that the enumeration MyColors is on the MATLAB path.

classdef MyColors < int32


enumeration
green(1),
red(2),
end
end
2 On the Define Input Types page, click Let me enter input or global types
directly.

18-13
18 Setting Up a MATLAB Coder Project

3 In the field to the right of the input parameter, enter MyColors.

Specify a Fixed-Point Input Parameter by Type


To specify fixed-point inputs, Fixed-Point Designer software must be installed.

1 On the Define Input Types page, click Let me enter input or global types
directly.
2 Click the field to the right of the input parameter that you want to define.
3 Select embedded.fi.
4 Select the size. If you do not specify the size, the size defaults to 1x1.
5 Specify the input parameter numerictype and fimath properties.

If you do not specify a local fimath, the app uses the default fimath. See “Default
fimath Usage to Share Arithmetic Rules”.

To modify the numerictype or fimath properties, open the properties dialog box.
To open the properties dialog box, click to the right of the fixed-point type definition.

Optionally, click .

Specify a Structure Input Parameter


When a primary input is a structure, the app treats each field as a separate input.
Therefore, you must specify properties for all fields of a primary structure input in the
order that they appear in the structure definition:

• For each field of an input structure, specify class, size, and complexity.
• For each field that is a fixed-point class, also specify numerictype, and fimath.

Specify Structures by Type

1 On the Define Input Types page, click Let me enter input or global types
directly.
2 Click the field to the right of the input parameter that you want to define.
3 Select struct.

The app displays the selected type, struct. The app displays the size options.

18-14
Define or Edit Input Parameter Type Using the App

4 Specify that your structure is a scalar, 1 x n vector, m x 1 vector, or m x n matrix.


By default, if you do not select a size option, the app defines inputs as scalars.
5 If your input is not scalar, enter sizes for each dimension. Click the dimension. Enter
the size. Select from the size options. For example, for size 10:

• To specify fixed size, select 10.


• To specify variable size with an upper bound of 10, select :10.
• To specify unbounded variable size, select :Inf.
6 Optionally, specify properties for the structure in the generated code. See “Set
Structure Properties” on page 18-15.
7 Add fields to the structure. Specify the class, size, and complexity of the fields. See
“Add a Field to a Structure” on page 18-17.

Set Structure Properties

1
Click to the right of the structure definition. Optionally, click .
2 In the dialog box, specify properties for the structure in the generated code.

Property Description
C type definition name Name for the structure type in the
generated code.
Type definition is externally defined Default: No — type definition is not
externally defined.

If you select Yes to declare an externally


defined structure, the app does not
generate the definition of the structure
type. You must provide it in a custom
include file.

Dependency: C type definition


name enables this option.
C type definition header file Name of the header file that contains the
external definition of the structure, for
example, "mystruct.h". Specify the
path to the file using the Additional
include directories parameter on the

18-15
18 Setting Up a MATLAB Coder Project

Property Description
project settings dialog box Custom Code
tab.

By default, the generated code contains


#include statements for custom header
files after the standard header files. If a
standard header file refers to the custom
structure type, then the compilation
fails. If you specify the C type definition
header file, the app includes that header
file exactly at the point where it is
required.

Must be a nonempty string.

Dependency: When Type definition


is externally defined is set to Yes,
this option is enabled.

18-16
Define or Edit Input Parameter Type Using the App

Property Description
Data alignment boundary The run-time memory alignment of
structures of this type in bytes.

If you have an Embedded Coder license


and use Code Replacement Libraries
(CRLs), the CRLs provide the ability
to align data objects passed into a
replacement function to a specified
boundary. You can take advantage of
target-specific function implementations
that require aligned data. By default, the
structure is not aligned on any specific
boundary so it is not matched by CRL
functions that require alignment.

Alignment must be either -1 or a power


of 2 that is no more than 128.

Default: 0

Dependency: When Type definition


is externally defined is set to Yes,
this option is enabled.

Rename a Field in a Structure

Select the name field of the structure that you want to rename. Enter the new name.

Add a Field to a Structure

1
To the right of the structure, click
2 Enter the field name. Specify the class, size, and complexity of the field.

Insert a Field into a Structure

1 Select the structure field below which you want to add another field.
2 Right-click the structure field.
3 Select Insert Field Below.

18-17
18 Setting Up a MATLAB Coder Project

The app adds the field after the field that you selected.
4 Enter the field name. Specify the class, size, and complexity of the field.

Remove a Field from a Structure

1 Right-click the field that you want to remove.


2 Select Remove Field.

Specify a Cell Array Input Parameter


For code generation, cell arrays are homogeneous or heterogeneous. See “Homogeneous
vs. Heterogeneous Cell Arrays” on page 9-2. A homogeneous cell array is represented as
an array in the generated code. All elements have the same properties. A heterogeneous
cell array is represented as a structure in the generated code. Elements can have
different properties.

Specify a Homogeneous Cell Array

1 On the Define Input Types page, click Let me enter input or global types
directly.
2 Click the field to the right of the input parameter that you want to define.
3 Select cell (Homogeneous).

The app displays the selected type, cell. The app displays the size options.
4 From the list, select whether your input is a scalar, a 1 x n vector, a m x 1 vector,
or a m x n matrix. By default, if you do not select a size option, the app defines
inputs as scalars.
5 If your input is not scalar, enter sizes for each dimension. Click the dimension. Enter
the size. Select from the size options. For example, for size 10:

• To specify fixed size, select 10.


• To specify variable size with an upper bound of 10, select :10.
• To specify unbounded variable size, select :Inf.

Below the cell array variable, a colon inside curly braces {:} indicates that the cell
array elements have the same properties (class, size, and complexity).
6 To specify the class, size, and complexity of the elements in the cell array, click the
field to the right of {:}.

18-18
Define or Edit Input Parameter Type Using the App

Specify a Heterogeneous Cell Array

1 On the Define Input Types page, click Let me enter input or global types
directly.
2 Click the field to the right of the input parameter that you want to define.
3 Select cell (Heterogeneous).

The app displays the selected type, cell. The app displays the size options.
4 Specify that your structure is a scalar, 1 x n vector, m x 1 vector, or m x n matrix.
By default, if you do not select a size option, the app defines inputs as scalars.
5 Optionally, if your input is not scalar, enter sizes m and n. A heterogeneous cell array
is fixed size.

The app lists the cell array elements. It uses indexing notation to specify each
element. For example, {1,2} indicates the element in row 1, column 2.
6 Specify the class, size, and complexity for each cell array element.
7 Optionally, add elements. See “Add an Element to a Heterogeneous Cell Array” on
page 18-22
8 Optionally, specify properties for the structure that represents the cell array in the
generated code. See “Set Structure Properties for a Heterogeneous Cell Array” on
page 18-19.

Set Structure Properties for a Heterogeneous Cell Array

A heterogeneous cell array is represented as a structure in the generated code. You can
specify the properties for the structure that represents the cell array.

1
Click to the right of the cell array definition. Optionally click .
2 In the dialog box, specify properties for the structure in the generated code.

Property Description
C type definition name Name for the structure type in the
generated code.
Type definition is externally defined Default: No — type definition is not
externally defined.

If you select Yes to declare an externally


defined structure, the app does not

18-19
18 Setting Up a MATLAB Coder Project

Property Description
generate the definition of the structure
type. You must provide it in a custom
include file.

Dependency: C type definition


name enables this option.
C type definition header file Name of the header file that contains the
external definition of the structure, for
example, "mystruct.h". Specify the
path to the file using the Additional
include directories parameter on the
project settings dialog box Custom Code
tab.

By default, the generated code contains


#include statements for custom header
files after the standard header files. If a
standard header file refers to the custom
structure type, then the compilation
fails. If you specify the C type definition
header file, the app includes that header
file exactly at the point where it is
required.

Must be a nonempty string.

Dependency: When Type definition


is externally defined is set to Yes,
this option is enabled.

18-20
Define or Edit Input Parameter Type Using the App

Property Description
Data alignment boundary The run-time memory alignment of
structures of this type in bytes.

If you have an Embedded Coder license


and use Code Replacement Libraries
(CRLs), the CRLs provide the ability
to align data objects passed into a
replacement function to a specified
boundary. You can take advantage of
target-specific function implementations
that require aligned data. By default, the
structure is not aligned on any specific
boundary so it is not matched by CRL
functions that require alignment.

Alignment must be either -1 or a power


of 2 that is no more than 128.

Default: 0

Dependency: When Type definition


is externally defined is set to Yes,
this option is enabled.

Change Classification as Homogeneous or Heterogeneous

To change the classification as homogeneous or heterogeneous, right-click the variable.


Select Homogeneous or Heterogeneous.

18-21
18 Setting Up a MATLAB Coder Project

The app clears the definitions of the elements.

Change the Size of the Cell Array

1 In the definition of the cell array, click a dimension. Specify the size.
2 For a homogeneous cell array, specify whether the dimension is variable size and
whether the dimension is bounded or unbounded. Alternatively, right-click the
variable. Select Bounded (fixed-size), Bounded (variable-size), or Unbounded
3 For a heterogeneous cell array, the app adds elements so that the cell array has the
specified size and shape.

Add an Element to a Heterogeneous Cell Array

1 In the definition of the cell array, click a dimension. Specify the size. For example,
enter 1 for the first dimension and 4 for the second dimension.

The app adds elements so that the cell array has the specified size and shape. For
example for a 1x4 heterogeneous cell array, the app lists four elements: {1,1},
{1,2}, {1,3}, and {1,4}.
2 Specify the properties of the new elements.

18-22
Define Constant Input Parameters Using the App

Define Constant Input Parameters Using the App


1 On the Define Input Types page, click Let me enter input or global types
directly.
2 Click the field to the right of the input parameter name.
3 Select Define Constant.
4 In the field to the right of the parameter name, enter the value of the constant or a
MATLAB expression that represents the constant.

The app uses the value of the specified MATLAB expression as a compile-time
constant.

18-23
18 Setting Up a MATLAB Coder Project

Define Inputs Programmatically in the MATLAB File


You can use the MATLAB assert function to define properties of primary function
inputs in your MATLAB entry-point files.

To instruct the MATLAB Coder app to determine input types from the assert statements

in your code, on the app toolbar, click . Select Determine input types from code
preconditions. If you enable this option:

• The app labels all entry-point function inputs as Deferred. It determines the input
types at compile time.
• In this project, you cannot use other input specification methods to specify input
types.

See “Define Input Properties Programmatically in the MATLAB File” on page 21-66.

Note: If you enable fixed-point conversion (requires a Fixed-Point Designer license), the
app disables the Determine input types from code preconditions option.

18-24
Add Global Variables Using the App

Add Global Variables Using the App


To add global variables to the project:

1 On the Define Input Types page, set Does this code use global variables? to
Yes.

By default, the app names the first global variable in a project g, and subsequent
global variables g1, g2, etc.
2 Enter the name of the global variable.
3 After adding a global variable, but before building the project, specify its type and
initial value. Otherwise, you must create a variable with the same name in the
global workspace. See “Specify Global Variable Type and Initial Value Using the
App” on page 18-26.

18-25
18 Setting Up a MATLAB Coder Project

Specify Global Variable Type and Initial Value Using the App
In this section...
“Why Specify a Type Definition for Global Variables?” on page 18-26
“Specify a Global Variable Type” on page 18-26
“Define a Global Variable by Example” on page 18-26
“Define or Edit Global Variable Type” on page 18-27
“Define Global Variable Initial Value” on page 18-28
“Define Global Variable Constant Value” on page 18-29
“Remove Global Variables” on page 18-29

Why Specify a Type Definition for Global Variables?


If you use global variables in your MATLAB algorithm, before building the project,
you must add a global type definition and initial value for each global variable. If you
do not initialize the global data, the app looks for the variable in the MATLAB global
workspace. If the variable does not exist, the app generates an error.

For MEX functions, if you use global data, you must also specify whether to synchronize
this data between MATLAB and the MEX function.

Specify a Global Variable Type


1 Specify the type of each global variable using one of the following methods:

• Define by example
• Define type
2 Define an initial value for each global variable.

If you do not provide a type definition and initial value for a global variable, create
a variable with the same name and suitable class, size, complexity, and value in the
MATLAB workspace.

Define a Global Variable by Example


1 Click the field to the right of the global variable that you want to define.

18-26
Specify Global Variable Type and Initial Value Using the App

2 Select Define by Example.


3 In the field to the right of the global name, enter a MATLAB expression that has the
required class, size, and complexity. MATLAB Coder software uses the class, size,
and complexity of the value of this expression as the type for the global variable.
4 Optionally, change the size of the global variable. Click the dimension that you want
to change and enter the size, for example, 10.

You can specify:

• Fixed size. In this example, select 10.


• Variable size, up to a specified limit, by using the : prefix. In this example, to
specify that your input can vary in size up to 10, select :10.
• Unbounded variable size by selecting :Inf.

Define or Edit Global Variable Type


1 Click the field to the right of the global variable that you want to define.
2 Optionally, for numeric types, select Complex to make the parameter a complex
type. By default, inputs are real.
3 Select the type for the global variable. For example, double.

By default, the global variable is a scalar.


4 Optionally, change the size of the global variable. Click the dimension that you want
to change and enter the size, for example, 10.

18-27
18 Setting Up a MATLAB Coder Project

You can specify:

• Fixed size. In this example, select 10.


• Variable size, up to a specified limit, by using the : prefix. In this example, to
specify that your input can vary in size up to 10, select :10.
• Unbounded variable size by selecting :Inf.

Define Global Variable Initial Value


• “Define Initial Value Before Defining Type” on page 18-28
• “Define Initial Value After Defining Type” on page 18-29

Define Initial Value Before Defining Type

1 Click the field to the right of the global variable.


2 Select Define Initial Value.
3 Enter a MATLAB expression. MATLAB Coder software uses the value of the
specified MATLAB expression as the value of the global variable. Because you
did not define the type of the global variable before you defined its initial value,
MATLAB Coder uses the initial value type as the global variable type.

The project shows that the global variable is initialized.

18-28
Specify Global Variable Type and Initial Value Using the App

If you change the type of a global variable after defining its initial value, you must
redefine the initial value.

Define Initial Value After Defining Type

• Click the type field of a predefined global variable.


• Select Define Initial Value.
• Enter a MATLAB expression. MATLAB Coder software uses the value of the specified
MATLAB expression as the value of the global variable.

The project shows that the global variable is initialized.

Define Global Variable Constant Value


1 Click the field to the right of the global variable.
2 Select Define Constant Value.
3 In the field to the right of the global variable, enter a MATLAB expression.

Remove Global Variables


1 Right-click the global variable.
2 From the menu, select Remove Global.

18-29
18 Setting Up a MATLAB Coder Project

Undo and Redo Changes to Type Definitions in the App


To revert or restore changes to input argument type definitions, above the input
arguments table, click or .

To revert or restore changes to global variable type definitions, above the global variables
table, click or .

Alternatively, use the keyboard shortcuts for Undo and Redo. The keyboard shortcuts
apply to the table that is selected. The shortcuts are defined in your MATLAB
preferences. On a Windows platform, the default keyboard shortcuts for Undo and Redo
are Ctrl+Z and Ctrl+Y.

Each undo operation reverts the last change. Each redo operation restores the last
change.

Related Examples
• “Define Keyboard Shortcuts”

18-30
Changing Output Type

Changing Output Type


In this section...
“Project Settings” on page 18-31
“Configuration Object Parameters” on page 18-32

MEX functions use a different set of configuration parameters than libraries and
executables use. When you switch the output type between MEX Function and Source
Code, Static Library, Dynamic Library, or C/C++ Executable, verify these
settings.

If you enable any of the following parameters when the output type is MEX Function,
and you want to use the same setting for C/C++ code generation as well, you must
enable it again for C/C++ Static Library, C/C++ Dynamic Library, and C/C++
Executable.

Project Settings
Project Settings Dialog Box Tab Parameter Name
Paths Working folder
Build folder
Search paths
Speed Saturate on integer overflow
Memory Enable variable-sizing
Dynamic memory allocation
Stack usage max
Code Appearance Generated file partitioning method
Include comments
MATLAB source code as comments
Reserved names
Debugging Always create a code generation report
Automatically launch a report if one is generated
Custom Code Source file

18-31
18 Setting Up a MATLAB Coder Project

Project Settings Dialog Box Tab Parameter Name


Header file
Initialize function
Terminate function
Additional include directories
Additional source files
Additional libraries
Post-code-generation command
Advanced Constant folding timeout
Language
Inline threshold
Inline threshold max
Inline stack limit
Use memcpy for vector assignment
Memcpy threshold (bytes)
Use memset to initialize floats and doubles to 0.0

Configuration Object Parameters


• ConstantFoldingTimeout
• CustomHeaderCode
• CustomInclude
• CustomInitializer
• CustomLibrary
• CustomSource
• CustomSourceCode
• CustomTerminator
• DynamicMemoryAllocation
• EnableMemcpy
• EnableVariableSizing

18-32
Changing Output Type

• FilePartitionMethod
• GenCodeOnly
• GenerateComments
• GenerateReport
• InitFltsAndDblsToZero
• InlineStackLimit
• InlineThreshold
• InlineThresholdMax
• LaunchReport
• MATLABSourceComments
• MemcpyThreshold
• PostCodeGenCommand
• ReservedNameArray
• SaturateOnIntegerOverflow
• StackUsageMax
• TargetLang

18-33
18 Setting Up a MATLAB Coder Project

Code Generation Readiness Screening in the MATLAB Coder App


By default, the MATLAB Coder app screens your MATLAB code for features and
functions that code generation does not support. After you enter entry-point functions
and click Next, if the app detects issues, it opens the Review Code Generation
Readiness page.

If you click Review Issues, you can use the app editor to fix issues before you generate
code.

If the code generation readiness screening causes slow operations in the app, consider
disabling the screening. To disable code generation readiness screening, on the app

toolbar, click and clear Check code generation readiness.

If you clear Check code generation readiness during or after screening, the app
retains the screening results for the current session. If you fix or introduce code
generation readiness issues in your code, the app does not update the screening results.
To clear screening results after you disable screening, or to update screening results after
you reenable screening, close and reopen the project.

For a fixed-point conversion project, code generation readiness screening identifies


functions that do not have fixed-point support. The app lists these functions on the
Function Replacements tab of the Convert to Fixed Point page where you can
specify function replacement with a custom function or a lookup table. If you disable
screening, do not rely on the app to identify functions that you must replace. Manually

18-34
Code Generation Readiness Screening in the MATLAB Coder App

enter the names of functions on the Function Replacements tab. Fixed-point


conversion requires a Fixed-Point Designer license.

More About
• “Slow Operations in MATLAB Coder App” on page 18-36
• “Automated Fixed-Point Conversion” on page 15-86

18-35
18 Setting Up a MATLAB Coder Project

Slow Operations in MATLAB Coder App


By default, the MATLAB Coder app screens your entry-point functions for code
generation readiness. For some large entry-point functions, or functions with many
calls, screening can take a long time. If the screening takes a long time, certain app or
MATLAB operations can be slower than expected or appear to be unresponsive.

To determine if slow operations are due to the code generation readiness screening,
disable the screening.

More About
• “Code Generation Readiness Screening in the MATLAB Coder App” on page 18-34

18-36
Unable to Open a MATLAB Coder Project

Unable to Open a MATLAB Coder Project


When you open a project from a different release, if necessary, the MATLAB Coder
app updates the project file so that the format is compatible with the release that
you are using. Before the app updates the project file, it creates a backup file
with the name project_name.prj.bak. For example, the backup file name for
myproject.prj is myproject.prj.bak. If the backup file exists, the app inserts an
integer between the prj and bak extensions to make the file name unique. For example,
if myproject.prj.bak exists, the app creates the backup file myproject.prj.2.bak.

If the project file is from a release before R2015a, the app also displays a message about
the project file update and backup. To use the project in a release before R2015a, use the
backup project file instead of the updated project file.

To use a backup project file, remove the extensions that follow the prj extension. For
example, rename myproject.prj.2.bak to myproject.prj. If you use the backup
project file in the release that created it, the project is the same as the original project.
If you use the backup project file in a different release than the one that created it, you
can possibly lose some information. For example, if you open a project file in a release
that does not recognize a setting in the file, that setting is lost. For best results, open the
backup project file in the release in which you created it.

18-37
19

Preparing MATLAB Code for C/C++


Code Generation

• “Workflow for Preparing MATLAB Code for Code Generation” on page 19-2
• “Fixing Errors Detected at Design Time” on page 19-4
• “Using the Code Analyzer” on page 19-5
• “Check Code With the Code Analyzer” on page 19-6
• “Check Code Using the Code Generation Readiness Tool” on page 19-8
• “Code Generation Readiness Tool” on page 19-9
• “Unable to Determine Code Generation Readiness” on page 19-15
• “Generate MEX Functions Using the MATLAB Coder App” on page 19-16
• “Generate MEX Functions at the Command Line” on page 19-21
• “Fix Errors Detected at Code Generation Time” on page 19-23
• “Design Considerations When Writing MATLAB Code for Code Generation” on page
19-24
• “Running MEX Functions” on page 19-26
• “Debugging Strategies” on page 19-27
• “Collect and View Line Execution Counts for Your MATLAB Code” on page 19-28
19 Preparing MATLAB Code for C/C++ Code Generation

Workflow for Preparing MATLAB Code for Code Generation

19-2
Workflow for Preparing MATLAB Code for Code Generation

See Also
• “Set Up a MATLAB Coder Project” on page 18-2
• “Fixing Errors Detected at Design Time” on page 19-4
• “Generate MEX Functions Using the MATLAB Coder App” on page 19-16
• “Fix Errors Detected at Code Generation Time” on page 19-23
• “Workflow for Testing MEX Functions in MATLAB” on page 20-3
• “C/C++ Code Generation” on page 21-4
• “Accelerate MATLAB Algorithms” on page 26-14

19-3
19 Preparing MATLAB Code for C/C++ Code Generation

Fixing Errors Detected at Design Time


Use the code analyzer and the code generation readiness tool to detect issues at design
time. Before generating code, you must fix these issues.

See Also
• “Check Code With the Code Analyzer” on page 19-6
• “Check Code Using the Code Generation Readiness Tool” on page 19-8
• “Design Considerations When Writing MATLAB Code for Code Generation” on page
19-24
• “Debugging Strategies” on page 19-27

19-4
Using the Code Analyzer

Using the Code Analyzer


You use the code analyzer in the MATLAB Editor to check for code violations at design
time, minimizing compilation errors. The code analyzer continuously checks your code as
you enter it. It reports problems and recommends modifications.

To use the code analyzer to identify warnings and errors specific to MATLAB for code
generation, you must add the %#codegen directive (or pragma) to your MATLAB file.
A complete list of code generation analyzer messages is available in the MATLAB Code
Analyzer preferences. For more information, see “Running the Code Analyzer Report”.

Note: The code analyzer might not detect all MATLAB for code generation issues. After
eliminating the errors or warnings that the code analyzer detects, compile your code with
MATLAB Coder to determine if the code has other compliance issues.

19-5
19 Preparing MATLAB Code for C/C++ Code Generation

Check Code With the Code Analyzer


The code analyzer checks your code for problems and recommends modifications. You can
use the code analyzer to check your code interactively in the MATLAB Editor while you
work.

To verify that continuous code checking is enabled:

1 In MATLAB, select the Home tab and then click Preferences.


2 In the Preferences dialog box, select Code Analyzer.
3 In the Code Analyzer Preferences pane, verify that Enable integrated warning
and error messages is selected.

The code analyzer provides an indicator in the top right of the editor window. If the
indicator is green, the analyzer did not detect code generation issues.

If the indicator is red, the analyzer has detected errors in your code. If it is orange, it has
detected warning. When the indicator is red or orange, a red or orange marker appears
to the right of the code where the error occurs. Place your pointer over the marker for
information about the error. Click the underlined text in the error message for a more
detailed explanation and suggested actions to fix the error.

19-6
Check Code With the Code Analyzer

Before generating code from your MATLAB code, you must fix the errors detected by the
code analyzer.

19-7
19 Preparing MATLAB Code for C/C++ Code Generation

Check Code Using the Code Generation Readiness Tool


In this section...
“Run Code Generation Readiness Tool at the Command Line” on page 19-8
“Run Code Generation Readiness Tool from the Current Folder Browser” on page
19-8
“Run the Code Generation Readiness Tool Using the MATLAB Coder App” on page
19-8

Run Code Generation Readiness Tool at the Command Line


1 Navigate to the folder that contains the file that you want to check for code
generation readiness.
2 At the command prompt, enter:
coder.screener('filename')

The Code Generation Readiness tool opens for the file named filename. The tool
provides a code generation readiness score and lists issues that you must fix prior to
code generation.

Run Code Generation Readiness Tool from the Current Folder Browser
1 In the current folder browser, right-click the file that you want to check for code
generation readiness.
2 From the context menu, select Check Code Generation Readiness.

The Code Generation Readiness tool opens for the selected file. It provides a code
generation readiness score and lists issues that you must fix prior to code generation.

Run the Code Generation Readiness Tool Using the MATLAB Coder App
After you add entry-point files to your project, the MATLAB Coder app analyzes the
functions for coding issues and code generation readiness. If the app identifies issues, it
opens the Review Code Generation Readiness page. You can review and fix issues.

See “Code Generation Readiness Tool” on page 19-9.

19-8
Code Generation Readiness Tool

Code Generation Readiness Tool


In this section...
“Information That the Code Generation Readiness Tool Provides” on page 19-9
“Summary Tab” on page 19-9
“Code Structure Tab” on page 19-11

Information That the Code Generation Readiness Tool Provides


The code generation readiness tool screens MATLAB code for features and functions that
code generation does not support. The tool provides a report that lists the source files
that contain unsupported features and functions. The report also indicates the amount
of work required to make the MATLAB code suitable for code generation. It is possible
that the tool does not detect all code generation issues. Under certain circumstances, it is
possible that the tool can report false errors. Therefore, before you generate C code, verify
that your code is suitable for code generation by generating a MEX function.

Summary Tab

19-9
19 Preparing MATLAB Code for C/C++ Code Generation

The Summary tab provides a Code Generation Readiness Score, which ranges from
1 to 5. A score of 1 indicates that the tool detects issues that require extensive changes
to the MATLAB code to make it suitable for code generation. A score of 5 indicates that
the tool does not detect code generation issues; the code is ready to use with minimal or
no changes.

On this tab, the tool also displays information about:

• MATLAB syntax issues. These issues are reported in the MATLAB editor. To learn
more about the issues and how to fix them, use the Code Analyzer.
• Unsupported MATLAB function calls.
• Unsupported MATLAB language features, such as anonymous function handles and
nested functions.
• Unsupported data types.

19-10
Code Generation Readiness Tool

Code Structure Tab

If the code that you are checking calls other MATLAB functions, or you are checking
multiple entry-point functions, the tool displays the Code Structure Tab.

This tab displays information about the relative size of each file and how suitable each
file is for code generation.

19-11
19 Preparing MATLAB Code for C/C++ Code Generation

Code Distribution

The Code Distribution pane displays a pie chart that shows the relative sizes of the
files and how suitable each file is for code generation. During the planning phase of
a project, you can use this information for estimation and scheduling. If the report
indicates that multiple files are not suitable for code generation, consider fixing files that
require minor changes before addressing files with significant issues.

Call Tree

The Call Tree pane displays information about the nesting of function calls. For each
called function, the report provides a Code Generation Readiness score, which ranges
from 1 to 5. A score of 1 indicates that the tool detects issues that require extensive
changes to the MATLAB code to make it suitable for code generation. A score of 5
indicates that the tool does not detect code generation issues. The code is ready to use
with minimal or no changes. The report also lists the number of lines of code in each file.

Show MATLAB Functions

If you select Show MATLAB Functions, the report also lists the MATLAB functions
that your function calls. For each of these MATLAB functions, if code generation
supports the function, the report sets Code Generation Readiness to Yes.

19-12
Code Generation Readiness Tool

19-13
19 Preparing MATLAB Code for C/C++ Code Generation

Related Examples
• “Check Code Using the Code Generation Readiness Tool” on page 19-8

19-14
Unable to Determine Code Generation Readiness

Unable to Determine Code Generation Readiness


Sometimes the code generation readiness tool cannot determine whether the entry-point
functions in your project are suitable for code generation. The most likely reason is that
the tool is unable to find the entry-point files. Verify that your current working folder is
set to the folder that contains your entry-point files. If it is not, either make this folder
your current working folder or add the folder containing these files to the MATLAB path.

19-15
19 Preparing MATLAB Code for C/C++ Code Generation

Generate MEX Functions Using the MATLAB Coder App

In this section...
“Workflow for Generating MEX Functions Using the MATLAB Coder App” on page
19-16
“Generate a MEX Function Using the MATLAB Coder App” on page 19-16
“Configure Project Settings” on page 19-19
“Build a MATLAB Coder Project” on page 19-19
“See Also” on page 19-20

Workflow for Generating MEX Functions Using the MATLAB Coder App
Step Action Details
1 Set up the MATLAB Coder project. “Set Up a MATLAB Coder Project” on page
18-2
2 Specify the build configuration parameters. “Configure Project Settings” on page
Set Build type to MEX. 19-19
3 Build the project. “Build a MATLAB Coder Project” on page
19-19

Generate a MEX Function Using the MATLAB Coder App


This example shows how to generate a MEX function from MATLAB code using the
MATLAB Coder app.

Create the Entry-Point Function

In a local writable folder, create a MATLAB file, mcadd.m, that contains:


function y = mcadd(u,v) %#codegen
y = u + v;

Create the Test File

In the same local writable folder, create a MATLAB file, mcadd_test.m, that calls
mcadd with example inputs. The example inputs are scalars with type int16.

19-16
Generate MEX Functions Using the MATLAB Coder App

function y = mcadd_test
y = mcadd(int16(2), int16(3));

Open the MATLAB Coder App

On the MATLAB Toolstrip Apps tab, under Code Generation, click the MATLAB
Coder app icon.

The app opens the Select Source Files page.

Specify Source Files

1 On the Select Source Files page, type or select the name of the entry-point
function mcadd.

The app creates a project with the default name mcadd.prj.


2 Click Next to go to the Define Input Types step. The app analyzes the function for
coding issues and code generation readiness. If the app identifies issues, it opens the
Review Code Generation Readiness page where you can review and fix issues.
In this example, because the app does not detect issues, it opens the Define Input
Types page.

Define Input Types

Because C uses static typing, at compile time, MATLAB Coder must determine the
properties of all variables in the MATLAB files. You must specify the properties of all
entry-point function inputs. From the properties of the entry-point function inputs,
MATLAB Coder can infer the properties of all variables in the MATLAB files.

Specify the test file mcadd_test.m that MATLAB Coder uses to automatically define
types for u and v:

1 Enter or select the test file mcadd_test.m.


2 Click Autodefine Input Types.

The test file, mcadd_test.m, calls the entry-point function, mcadd, with the
example input types. MATLAB Coder infers that inputs u and v are int16(1x1).
3 Click Next to go to the Check for Run-Time Issues step.

Check for Run-Time Issues

The Check for Run-Time Issues step generates a MEX file from your entry-point
functions, runs the MEX function, and reports issues. This step is optional. However, it

19-17
19 Preparing MATLAB Code for C/C++ Code Generation

is a best practice to perform this step. You can detect and fix run-time errors that are
harder to diagnose in the generated C code.

1 To open the Check for Run-Time Issues dialog box, click the Check for Issues
arrow .

The app populates the test file field with mcadd_test, the test file that you used to
define the input types.
2 Click Check for Issues.

The app generates a MEX function. It runs the test file replacing calls to mcadd
with calls to the MEX function. If the app detects issues during the MEX function
generation or execution, it provides warning and error messages. Click these
messages to navigate to the problematic code and fix the issue. In this example, the
app does not detect issues.
3 Click Next to go to the Generate Code step.

Generate the MEX Function

1
To open the Generate dialog box, click the Generate arrow .
2 In the Generate dialog box, set Build type to MEX and Language to C. Use the
default values for the other project build configuration settings.
3 Click Generate.

The app indicates that code generation succeeded. It displays the source MATLAB
files and the generated output files on the left side of the page. On the Variables
tab, it displays information about the MATLAB source variables. On the Build Log