0% found this document useful (0 votes)
93 views

MATLAB Coder Documentation (PDFDrive)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

MATLAB Coder Documentation (PDFDrive)

Copyright
© © All Rights Reserved
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
tab, it displays the build log, including compiler warnings and errors.

MATLAB Coder builds the project and, by default, generates a MEX function,
mcadd_mex, in the current folder. MATLAB Coder also generates other supporting
files in a subfolder called codegen/mex/mcadd. MATLAB Coder uses the name of
the MATLAB function as the root name for the generated files. It creates a platform-
specific extension for the MEX file. See “Naming Conventions” on page 21-81.
4 To view the code generation report, click View Report.
5 Click Next to open the Finish Workflow page.

19-18
Generate MEX Functions Using the MATLAB Coder App

Review the Finish Workflow Page

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

Configure Project Settings


To open the project settings dialog box:

1
To open the Generate dialog box, click the Generate arrow .
2 Click More Settings.

To change a project setting, click the tab that contains the setting that you want to
change. For example, to change the Saturate on integer overflow setting, click the
Speed tab.

MEX functions use a different set of configuration parameters than libraries and
executables. When you change the output type from MEX Function to Source Code
Static Library, Dynamic Library, or Executable, verify these settings. See
“Changing Output Type” on page 18-31.

See Also

• “Enable Code Generation Reports” on page 22-28


• “Using the MATLAB Coder App” on page 21-124
• “How to Disable Inlining Globally Using the MATLAB Coder App” on page 21-134
• “Generate Traceable Code” on page 22-2
• “Disabling Run-Time Checks Using the MATLAB Coder App” on page 26-17

Build a MATLAB Coder Project


To build a project using the specified settings, on the Generate Code page, click
Generate. As the MATLAB Coder app builds a project, it displays the build progress.
When the build is complete, the app provides details about the build on the Build Log
tab.

If the code generation report is enabled or build errors occur, the app generates a report.
The report provides detailed information about the most recent build, and provides a link
to the report.

19-19
19 Preparing MATLAB Code for C/C++ Code Generation

To view the report, click the View report link. The report provides links to your
MATLAB code and generated C/C++ files and compile-time type information for the
variables in your MATLAB code. If build errors occur, the report lists errors and
warnings.

See Also

• “Code Generation Reports” on page 22-10


• “Generate Code for Multiple Entry-Point Functions” on page 21-86
• “Generate Code for Global Data” on page 21-92

See Also
• “Generate Code for Multiple Entry-Point Functions” on page 21-86
• “Generate Code for Global Data” on page 21-92
• “Configure Build Settings” on page 21-26

19-20
Generate MEX Functions at the Command Line

Generate MEX Functions at the Command Line


Command-line Workflow for Generating MEX Functions
Step Action Details
1 Install prerequisite products. “Installing Prerequisite Products”
2 Set up your file infrastructure. “Paths and File Infrastructure Setup” on
page 21-80
3 Fix errors detected by the code analyzer. “Fixing Errors Detected at Design Time” on
page 19-4
4 Specify build configuration parameters. “Specify Build Configuration Parameters” on
page 21-32
5 Specify properties of primary function inputs. “Primary Function Input Specification” on
page 21-45
6 Generate the MEX function using codegen “Generating MEX Functions at the Command
with suitable command-line options. Line Using codegen” on page 19-22

Generate MEX Functions at the Command Line


In this example, you use the codegen function to generate a MEX function from a
MATLAB file that adds two inputs. You use the codegen -args option to specify that
both inputs are int16.

1 In a local writable folder, create a MATLAB file, mcadd.m, that contains:


function y = mcadd(u,v) %#codegen
y = u + v;
2 Generate a platform-specific MEX function in the current folder. At the command
line, specify that the two input parameters are int16 using the -args option. By
default, if you do not use the -args option, codegen treats inputs as real, scalar
doubles.
codegen mcadd -args {int16(0), int16(0)}

codegen generates a MEX function, mcadd_mex, in the current folder. codegen also
generates other supporting files in a subfolder called codegen/mex/mcadd.codegen
uses the name of the MATLAB function as the root name for the generated files

19-21
19 Preparing MATLAB Code for C/C++ Code Generation

and creates a platform-specific extension for the MEX file, as described in “Naming
Conventions” on page 21-81.

Generating MEX Functions at the Command Line Using codegen


You generate a MEX function at the command line using the codegen function.

The basic command is:


codegen fcn
By default, codegen generates a MEX function in the current folder as described in
“Generate MEX Functions at the Command Line” on page 19-21.

You can modify this default behavior by specifying one or more compiler options with
codegen, separated by spaces on the command line. For more information, see codegen.

See Also
• “Primary Function Input Specification” on page 21-45
• “MEX Function Generation at the Command Line”
• “Generate Code for Multiple Entry-Point Functions” on page 21-86
• “Generate Code for Global Data” on page 21-92

19-22
Fix Errors Detected at Code Generation Time

Fix Errors Detected at Code Generation Time


When the code generation software detects errors or warnings, it automatically generates
an error report. The error report describes the issues and provides links to the MATLAB
code with errors.

To fix the errors, modify your MATLAB code to use only those MATLAB features that are
supported for code generation. For more information, see “Programming Considerations
for Code Generation”. Choose a debugging strategy for detecting and correcting code
generation errors in your MATLAB code. For more information, see “Debugging
Strategies” on page 19-27.

When code generation is complete, the software generates a MEX function that you can
use to test your implementation in MATLAB.

If your MATLAB code calls functions on the MATLAB path, unless the code generation
software determines that these functions should be extrinsic or you declare them to be
extrinsic, it attempts to compile these functions. See “Resolution of Function Calls for
Code Generation” on page 14-2. To get detailed diagnostics, add the %#codegen directive
to each external function that you want codegen to compile.

See Also
• “Code Generation Reports” on page 22-10
• “Why Test MEX Functions in MATLAB?” on page 20-2
• “When to Generate Code from MATLAB Algorithms” on page 2-2
• “Debugging Strategies” on page 19-27
• “Declaring MATLAB Functions as Extrinsic Functions” on page 14-12

19-23
19 Preparing MATLAB Code for C/C++ Code Generation

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 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 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 or /C++ compiler. The default compiler that MathWorks


supplies with MATLAB for Windows 64-bit platforms is not a good compiler for
performance.

19-24
Design Considerations When Writing MATLAB Code for Code Generation

• Consider disabling run-time checks.

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

See Also
• “Programming Considerations for Code Generation”
• “Data Definition”
• “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

19-25
19 Preparing MATLAB Code for C/C++ Code Generation

Running MEX Functions


When you call a MEX function, pass it the same inputs that you use for the original
MATLAB algorithm. Do not pass coder.Constant or any of the coder.Type classes to
a MEX function. You can use these classes with only the codegen function.

To run a MEX function generated by MATLAB Coder, you must have licenses for all the
toolboxes that the MEX function requires. For example, if you generate a MEX function
from a MATLAB algorithm that uses a Computer Vision System Toolbox function or
System object, to run the MEX function, you must have a Computer Vision System
Toolbox license.

When you upgrade MATLAB, before running MEX functions with the new version,
rebuild the MEX functions.

Debugging MEX Functions


To debug your MEX functions, use the disp function to inspect the contents of your MEX
function variables. You cannot use save to debug MEX function variables because code
generation does not support it. Code generation does not support declaration of save as
extrinsic.

19-26
Debugging Strategies

Debugging Strategies
Before you perform code verification, choose a debugging strategy for detecting and
correcting noncompliant code in your MATLAB applications, especially if they consist
of a large number of MATLAB files that call each other's functions. The following table
describes two general strategies, each of which has advantages and disadvantages.

Debugging What to Do Pros Cons


Strategy
Bottom-up 1 Verify that your lowest- • Efficient Requires application tests that
verification level (leaf) functions are • Unlikely to cause work from the bottom up
compliant. errors
2 Work your way up the • Easy to isolate
function hierarchy code generation
incrementally to compile syntax violations
and verify each function,
ending with the top-level
function.
Top-down 1 Declare functions called You retain your top- Introduces extraneous code
verification by the top-level function level tests that you must remove after
to be extrinsic so that code verification, including:
MATLAB Coder does
not compile them. See • Extrinsic declarations
“Declaring MATLAB • Additional assignment
Functions as Extrinsic statements as required
Functions” on page 14-12. to convert opaque values
2 Verify that your top-level returned by extrinsic
function is compliant. functions to nonopaque
values (see “Working with
3 Work your way down mxArrays” on page 14-17).
the function hierarchy
incrementally by
removing extrinsic
declarations one by one to
compile and verify each
function, ending with the
leaf functions.

19-27
19 Preparing MATLAB Code for C/C++ Code Generation

Collect and View Line Execution Counts for Your MATLAB Code
When you perform the Check for Run-Time Issues step in the MATLAB Coder app,
you must provide a test that calls your entry-point functions with representative data.
The Check for Run-Time Issues step generates a MEX function from your MATLAB
functions and runs the test, replacing calls to the MATLAB functions with calls to the
MEX function. When running the MEX function, the app counts executions of the MEX
code that corresponds to a line of MATLAB code. These line execution counts help you
to see how well your test exercises your MATLAB code. You can identify dead code and
sections of code that require further testing.

To see the line execution counts, after the Check for Run-Time Issues step finishes the
test, click View MATLAB line execution counts.

In the app editor, the app displays a color-coded bar to the left of your MATLAB code.

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

This table describes the color coding.

Color Indicates
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.

19-29
19 Preparing MATLAB Code for C/C++ Code Generation

Color Indicates
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 bar, the color highlighting extends over the code.
For each section of code, the app displays the number of times that the section executes.

Collection of line execution counts is on by default. Turn it off only after you have verified
that you have adequate test file coverage. Turning off line execution counts can speed
up the Check for Run-Time Issues step. To turn off collection of line executions

19-30
Collect and View Line Execution Counts for Your MATLAB Code

counts, in the Check for Run-Time Issues dialog box, clear the Collect MATLAB line
execution counts check box.

Related Examples
• “Check for Run-Time Issues by Using the App” on page 20-6

More About
• “Why Test MEX Functions in MATLAB?” on page 20-2

19-31
20

Testing MEX Functions in MATLAB

• “Why Test MEX Functions in MATLAB?” on page 20-2


• “Workflow for Testing MEX Functions in MATLAB” on page 20-3
• “Running MEX Functions” on page 20-5
• “Check for Run-Time Issues by Using the App” on page 20-6
• “Verify MEX Functions in the MATLAB Coder App” on page 20-8
• “Verify MEX Functions at the Command Line” on page 20-9
• “Debug Run-Time Errors” on page 20-10
• “Using MEX Functions That MATLAB Coder Generates” on page 20-13
• “Using Generated C/C++ Code” on page 20-14
20 Testing MEX Functions in MATLAB

Why Test MEX Functions in MATLAB?


Before generating C/C++ code for your MATLAB code, it is a best practice to test the
MEX function to verify that it provides the same functionality as the original MATLAB
code. To do this testing, run the MEX function using the same inputs as you used to run
the original MATLAB code and compare the results. For more information about how
to test a MEX function using the MATLAB Coder app, see “Check for Run-Time Issues
by Using the App” on page 20-6 and “Verify MEX Functions in the MATLAB Coder
App” on page 20-8. For more information about how to test a MEX function at the
command line, see “Verify MEX Functions at the Command Line” on page 20-9.

Running the MEX function in MATLAB before generating code enables you to detect
and fix run-time errors that are much harder to diagnose in the generated code. If you
encounter run-time errors in your MATLAB functions, fix them before generating code.
See “Fix Errors Detected at Code Generation Time” on page 19-23 and “Debug Run-Time
Errors” on page 20-10.

When you run your MEX function in MATLAB, by default, the following run-time checks
execute:

• Memory integrity checks. These checks perform array bounds checking, dimension
checking, and detect violations of memory integrity in code generated for MATLAB
functions. If a violation is detected, MATLAB stops execution and provides a
diagnostic message.
• Responsiveness checks in code generated for MATLAB functions. These checks enable
periodic checks for Ctrl+C breaks in code generated for MATLAB functions, allowing
you to terminate execution with Ctrl+C.

For more information, see “Control Run-Time Checks” on page 26-16.

20-2
Workflow for Testing MEX Functions in MATLAB

Workflow for Testing MEX Functions in MATLAB

See Also
• “Set Up a MATLAB Coder Project” on page 18-2
• “Workflow for Preparing MATLAB Code for Code Generation” on page 19-2

20-3
20 Testing MEX Functions in MATLAB

• “Why Test MEX Functions in MATLAB?” on page 20-2


• “Debug Run-Time Errors” on page 20-10
• “C/C++ Code Generation” on page 21-4
• “Accelerate MATLAB Algorithms” on page 26-14

20-4
Running MEX Functions

Running MEX Functions


When you call a MEX function, pass it the same inputs that you use for the original
MATLAB algorithm. Do not pass coder.Constant or any of the coder.Type classes to
a MEX function. You can use these classes with only the codegen function.

To run a MEX function generated by MATLAB Coder, you must have licenses for all the
toolboxes that the MEX function requires. For example, if you generate a MEX function
from a MATLAB algorithm that uses a Computer Vision System Toolbox function or
System object, to run the MEX function, you must have a Computer Vision System
Toolbox license.

When you upgrade MATLAB, before running MEX functions with the new version,
rebuild the MEX functions.

Debugging MEX Functions


To debug your MEX functions, use the disp function to inspect the contents of your MEX
function variables. You cannot use save to debug MEX function variables because code
generation does not support it. Code generation does not support declaration of save as
extrinsic.

20-5
20 Testing MEX Functions in MATLAB

Check for Run-Time Issues by Using the App


Before you generate standalone C/C++ code for your MATLAB code, it is a best practice
to generate a MEX function from your entry-point functions. Running the MEX function
helps you to detect and fix run-time errors that are much harder to diagnose in the
generated code. It also helps you to verify that the MEX provides the same functionality
as the original MATLAB code.

In the MATLAB Coder app, to generate and run the MEX function for your MATLAB
code, perform the Check for Run-Time Issues step.

1 Write a function or script that calls your entry-point functions. You can use the same
test file (or files) that you use to automatically define input types in the Define
Input Types step.
2 Complete the Select Source Files and Define Input Types steps. On the Define
Input Types page, click Next to go to Check for Run-Time Issues step.
3 Specify the test file. In the previous step, if you automatically generated the input
types, the app populates the dialog box with that test file. Instead of a test file, you
can enter code that calls your entry-point functions. However, it is a best practice to
provide a test file.
4 Click Check for Issues. The app generates a MEX function from your MATLAB
function. It runs the test that you specified, substituting calls to your MATLAB
entry-point functions with calls to the generated MEX function. The app reports
MEX generation or build errors on the Build Errors tab. The app reports MEX run-
time errors on the Test Output tab.
5 If the app reports errors, to edit the MATLAB code, click View errors.
6 After you fix issues, to rerun the test, click Check for Issues.

When the app runs the MEX function, it counts executions of the MEX code that
corresponds to a line of MATLAB code. If the app does not detect issues, you can view
these line execution counts. The line execution counts help you to see how well your
test exercises your MATLAB code. You can identify dead code and sections of code that
require further testing. See “Collect and View Line Execution Counts for Your MATLAB
Code” on page 19-28.

Related Examples
• “C Code Generation Using the MATLAB Coder App”
• “Fix Errors Detected at Code Generation Time” on page 19-23
• “Collect and View Line Execution Counts for Your MATLAB Code” on page 19-28

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

• “Control Run-Time Checks” on page 26-16

More About
• “Why Test MEX Functions in MATLAB?” on page 20-2

20-7
20 Testing MEX Functions in MATLAB

Verify MEX Functions in the MATLAB Coder App


In the MATLAB Coder app, after you generate a MEX function, you can verify that the
generated MEX function has the same functionality as the original MATLAB entry-point
function. Provide a test file that calls the original MATLAB entry-point function. The test
file can be a function or a script. The test file must be in the same folder as the original
entry-point function.

1 On the Generate Code page, click Verify Code.


2 Type or select the test file name.
3 To run the test file without replacing calls to the original MATLAB function with
calls to the MEX function, for Run using, select MATLAB code. Click Run
Generated Code.

4 To run the test file, replacing calls to the original MATLAB function with calls to
the MEX function, for Run using, select Generated code. Click Run Generated
Code.
5 Compare the results of running the original MATLAB function with the results of
running the MEX function.

20-8
Verify MEX Functions at the Command Line

Verify MEX Functions at the Command Line


If you have a test file that calls your original MATLAB function, use coder.runTest
to verify the MEX function at the command line. coder.runTest runs the test file
replacing calls to the original MATLAB function with calls to the generated MEX
function. If errors occur during the run with coder.runTest, call stack information
is available for debugging purposes. For more information, see the coder.runTest
function reference information and “Verifying the MEX Function” in the MATLAB Coder
“C Code Generation at the Command Line” tutorial.

20-9
20 Testing MEX Functions in MATLAB

Debug Run-Time Errors


In this section...
“Viewing Errors in the Run-Time Stack” on page 20-10
“Handling Run-Time Errors” on page 20-12

If you encounter run-time errors in your MATLAB functions, the run-time stack appears
in the MATLAB command window. Use the error message and stack information to
learn more about the source of the error, and then either fix the issue or add error-
handling code. For more information, see “Viewing Errors in the Run-Time Stack” on
page 20-10“Handling Run-Time Errors” on page 20-12.

Viewing Errors in the Run-Time Stack


About the Run-Time Stack

The run-time stack is enabled by default for MEX code generation from MATLAB. To
learn more about the source of the error, use the error message and the following stack
information:

• The name of the function that generated the error


• The line number of the attempted operation
• The sequence of function calls that led up to the execution of the function and the line
at which each of these function calls occurred

20-10
Debug Run-Time Errors

Example Run-Time Stack Trace

This example shows the run-time stack trace for MEX function mlstack_mex:

mlstack_mex(-1)

Index exceeds matrix dimensions. Index


value -1 exceeds valid range [1-4] of
array x.

Error in mlstack>mayfail (line 31)


y = x(u);

Error in mlstack>subfcn1 (line 5)


switch (mayfail(u))

Error in mlstack (line 2)


y = subfcn1(u);

The stack trace provides the following information:

• The type of error.

??? Index exceeds matrix dimensions.


Index value -1 exceeds valid range [1-4] of array x.
• Where the error occurred.

Error in ==>mlstack>mayfail at 31
y = x(u);
• The function call sequence prior to the failure.

Error in ==> mlstack>subfcn1 at 5


switch (mayfail(u))

Error in ==> mlstack at 2


y = subfcn1(u);

When to Use the Run-Time Stack

To help you find the source of run-time errors, the run-time stack is useful during
debugging. However, when the stack is enabled, the generated code contains instructions
for maintaining the run-time stack, which might slow the run time. Consider disabling
the run-time stack for faster run time.

20-11
20 Testing MEX Functions in MATLAB

Disable the Run-Time Stack

You can disable the run-time stack by disabling the memory integrity checks as described
in “How to Disable Run-Time Checks” on page 26-17.

Caution Before disabling the memory integrity checks, you verify that all array bounds
and dimension checking is unnecessary.

Handling Run-Time Errors


The code generation software propagates error IDs. If you throw an error or warning in
your MATLAB code, use the try-catch statement in your test bench code to examine
the error information and attempt to recover, or clean up and abort. For example, for
the function in “Example Run-Time Stack Trace” on page 20-11, create a test script
containing:
try
mlstack_mex(u)
catch
% Add your error handling code here
end
For more information, see “The try/catch Statement”.

20-12
Using MEX Functions That MATLAB Coder Generates

Using MEX Functions That MATLAB Coder Generates


When you specify MEX for the output (build) type, MATLAB Coder generates a binary
MATLAB executable (MEX) version of your MATLAB function. You can call the MEX
function from MATLAB. See “Call MEX-File Functions”.

How you use the MEX function depends on your goal.

Goal See
Accelerate your MATLAB function. “MATLAB Algorithm Acceleration”
Test generated function for functionality “Why Test MEX Functions in MATLAB?”
and run-time issues. on page 20-2
Debug your MEX function. “Debug Run-Time Errors” on page 20-10

20-13
20 Testing MEX Functions in MATLAB

Using Generated C/C++ Code


Goal See
Package generated files into a zip file “Package Code for Other Development
for relocation to another development Environments” on page 25-44
environment.
Call generated code from MATLAB code. “External Code Integration for Code
Generation” on page 28-2
Generate an example C/C++ main function. “Use an Example C Main in an
Use that function to integrate generated Application” on page 25-21
code into a C application.
Integrate generated code into a C/C++ “Use a C Dynamic Library in a Microsoft
application. Visual Studio Project” on page 25-9
Integrate generated code that uses • “Use an Example C Main in an
emxArrays. Application” on page 25-21
• “C Code Interface for Arrays” on page
7-17
Generate a C/C++ Executable. “Generating Standalone C/C++ Executables
from MATLAB Code” on page 21-14

20-14
21

Generating C/C++ Code from


MATLAB Code

• “Code Generation Workflow” on page 21-3


• “C/C++ Code Generation” on page 21-4
• “Generating C/C++ Static Libraries from MATLAB Code” on page 21-5
• “Generating C/C++ Dynamically Linked Libraries from MATLAB Code” on page
21-9
• “Generating Standalone C/C++ Executables from MATLAB Code” on page 21-14
• “Configure Build Settings” on page 21-26
• “Specify Data Types Used in Generated Code” on page 21-38
• “Standard Math Libraries” on page 21-39
• “Change the Standard Math Library” on page 21-40
• “Share Build Configuration Settings” on page 21-41
• “Convert MATLAB Coder Project to MATLAB Script” on page 21-43
• “Primary Function Input Specification” on page 21-45
• “Specify Cell Array Inputs at the Command Line” on page 21-55
• “Control Constant Inputs in MEX Function Signatures” on page 21-62
• “Define Input Properties Programmatically in the MATLAB File” on page 21-66
• “Speed Up Compilation” on page 21-78
• “Disable Creation of the Code Generation Report” on page 21-79
• “Paths and File Infrastructure Setup” on page 21-80
• “Generate Code for Multiple Entry-Point Functions” on page 21-86
• “Generate Code for Global Data” on page 21-92
• “Specify Global Cell Arrays at the Command Line” on page 21-102
• “Generate Code for Enumerated Types” on page 21-104
21 Generating C/C++ Code from MATLAB Code

• “Generate Code for Variable-Size Data” on page 21-105


• “Code Generation for MATLAB Classes” on page 21-123
• “How MATLAB Coder Partitions Generated Code” on page 21-124
• “Requirements for Signed Integer Representation” on page 21-137
• “Customize the Post-Code-Generation Build Process” on page 21-138
• “Troubleshooting” on page 21-176

21-2
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
• “Configure Build Settings” on page 21-26
• “C/C++ Code Generation” on page 21-4

21-3
21 Generating C/C++ Code from MATLAB Code

C/C++ Code Generation


Using MATLAB Coder, you can generate standalone C/C++ static and dynamic libraries
and C/C++ executables. If you specify C++, MATLAB Coder wraps the C code into .cpp
files so that you can use a C++ compiler and interface with external C++ applications. It
does not generate C++ classes. By default, if MATLAB Coder does not detect errors, it
generates a platform-specific MEX function in the current folder.

To learn how to generate... See...


C/C++ static libraries from your MATLAB “Generating C/C++ Static Libraries from
code MATLAB Code” on page 21-5
C/C++ dynamic libraries from your “Generating C/C++ Dynamically Linked
MATLAB code Libraries from MATLAB Code” on page
21-9
C/C++ executables from your MATLAB “Generating Standalone C/C++ Executables
code from MATLAB Code” on page 21-14
MEX functions from your MATLAB code “Generate MEX Functions Using the
MATLAB Coder App” on page 19-16

If errors occur, MATLAB Coder does not generate code, but produces an error report and
provides a link to this report. For more information, see “Code Generation Reports” on
page 22-10.

Specify Custom Files to Build


In addition to your MATLAB file, you can specify the following types of custom files to
include in the build for standalone C/C++ code generation.

File Extension Description


.c Custom C file
.cpp Custom C++ file
.h Custom header file
.o , .obj Custom object file
.a , .lib, .so Library
.tmf Template makefile for custom MATLAB
Coder builds

21-4
Generating C/C++ Static Libraries from MATLAB Code

Generating C/C++ Static Libraries from MATLAB Code


In this section...
“Generate a C Static Library Using the MATLAB Coder App” on page 21-5
“Generate a C Static Library at the Command Line” on page 21-7

Generate a C Static Library Using the MATLAB Coder App


This example shows how to generate a C static library from MATLAB code using the
MATLAB Coder app.

In this example, you create a MATLAB function that adds two numbers. You use the app
to create a MATLAB Coder project and generate a C static library for the MATLAB code.

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.

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.

21-5
21 Generating C/C++ Code from MATLAB Code

The app creates a project with the default name mcadd.prj in the current folder.
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 can use 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
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

21-6
Generating C/C++ Static Libraries from MATLAB Code

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 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.
3 Click Generate.

The 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, mcadd.c. To view a different
file, in the Source Code or Output Files pane, click the file name.

MATLAB Coder generates a standalone C static library mcadd in the codegen\lib


\mcadd folder. It generates the minimal set of #include statements for header files
required by the selected code replacement library.
4 To view the code generation report, click View Report.
5 Click Next to open the Finish Workflow page.

Review the Finish Workflow Page

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

Generate a C Static Library at the Command Line


This example shows how to generate a C static library from MATLAB code at the
command line using the codegen function.

1 In a local writable folder, create a MATLAB file, mcadd.m, that contains:

function y = mcadd(u,v) %#codegen

21-7
21 Generating C/C++ Code from MATLAB Code

y = u + v;
2 Using the config:lib option, generate C library files. Using the -args option,
specify that the first input is a 1-by-4 vector of unsigned 16-bit integers and that
the second input is a double-precision scalar.
codegen -config:lib mcadd -args {zeros(1,4,'uint16'),0}

MATLAB Coder generates a C static library with the default name, mcadd, and
supporting files in the default folder, codegen/lib/mcadd. It generates the
minimal set of #include statements for header files required by the selected code
replacement library.

21-8
Generating C/C++ Dynamically Linked Libraries from MATLAB Code

Generating C/C++ Dynamically Linked Libraries from MATLAB


Code
In this section...
“Dynamic Libraries Generated by MATLAB Coder” on page 21-9
“Generate a C Dynamically Linked Library Using the MATLAB Coder App” on page
21-9
“Generate a C Dynamic Library at the Command Line” on page 21-12

Dynamic Libraries Generated by MATLAB Coder


By default, when MATLAB Coder generates a dynamic library (DLL):

• The DLL is suitable for the platform that you are working on.
• The DLL uses the release version of the C run-time library.
• The DLL linkage conforms to the target language, by default, C. If you set the target
language to C++, the linkage conforms to C++.
• When the target language is C, the generated header files explicitly declare the
exported functions to be extern "C" to simplify integration of the DLL into C++
applications.
• When an executable that uses the DLL runs, the DLL must be on the system path so
that the executable can access it.

If you generate a DLL that uses dynamically allocated variable-size data, MATLAB
Coder provides exported utility functions to interact with this data in the generated code.
For more information, see “Utility Functions for Creating emxArray Data Structures” on
page 7-20.

Generate a C Dynamically Linked Library Using the MATLAB Coder App


This example shows how to generate a C DLL from MATLAB code using the MATLAB
Coder app.

Create the Entry-Point Functions

Write two MATLAB functions, ep1 and ep2. ep1 takes one input, a single scalar. ep2
takes two inputs that are double scalars. In a local writable folder:

21-9
21 Generating C/C++ Code from MATLAB Code

1 Create a MATLAB file, ep1.m, that contains:


function y = ep1(u) %#codegen
y = u;
2 Create a MATLAB file, ep2.m, that contains:
function y = ep2(u, v) %#codegen
y = u + v;

Create the Test File

In the folder that contains ep1.m and ep2.m, create a MATLAB file, ep_test.m, that
calls ep1 and ep2 with example inputs.
function [y, y1] = ep_test
y = ep1(single(2));
y1 = ep2(double(3), double(4));

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 ep1.

The app creates a project with the default name ep1.prj in the current folder.
2 To add ep2 to the list of entry-point functions, click Add Entry-Point Function.
Type or select the name of the entry-point function ep2.
3 Click Next to go to the Define Input Types step. The app analyzes the functions
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

21-10
Generating C/C++ Dynamically Linked Libraries from MATLAB Code

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 a test file that MATLAB Coder can use to automatically define types:

1 Enter or select the test file ep_test.m.


2 Click Autodefine Input Types.

The test file, eps_test.m, calls the entry-point functions ep1 and ep2 with the
example input types. MATLAB Coder infers that for ep1, input u is single(1x1).
For ep2, u and v are 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 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. 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 ep_test, the test file that you used to
define the input types.
2 Click Check for Issues.

The app generates a MEX function named ep1_mex for ep1 and ep2. It runs the
test file ep_test replacing calls to ep1 and ep2 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 C Code

1
To open the Generate dialog box, click the Generate arrow .
2 In the Generate dialog box, set Build type to Dynamic Library and Language
to C. Use the default values for the other project build configuration settings.

21-11
21 Generating C/C++ Code from MATLAB Code

3 Click Generate.

The 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, ep1.c. To view a different file,
in the Source Code or Output Files pane, click the file name.

On Microsoft® Windows systems, MATLAB Coder generates a C dynamic library,


ep1.dll, and supporting files, in the default folder, codegen\dll\ep1. It
generates the minimal set of #include statements for header files required by the
selected code replacement library. On Linux® and Macintosh systems, it generates
a shared object (.so) file. The DLL linkage conforms to the target language, in this
example, C. If you set the target language to C++, the linkage conforms to C++.
MATLAB Coder generates a standalone C static library mcadd in the codegen\lib
\mcadd folder.
4 To view the code generation report, click View Report.
5 Click Next to open the Finish Workflow page.

Review the Finish Workflow Page

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

Generate a C Dynamic Library at the Command Line


This example shows how to generate a C dynamic library from MATLAB code at the
command line using the codegen function.

1 Write two MATLAB functions, ep1 takes one input, a single scalar, and ep2 takes
two inputs, both double scalars. In a local writable folder, create a MATLAB file,
ep1.m, that contains:

function y = ep1(u) %#codegen


y = u;
In the same local writable folder, create a MATLAB file, ep2.m, that contains:

function y = ep2(u, v) %#codegen


y = u + v;

21-12
Generating C/C++ Dynamically Linked Libraries from MATLAB Code

2 Generate the C dynamic library.


codegen -config:dll ep1 -args single(0) ep2 -args {0,0}

On Microsoft Windows systems, codegen generates a C dynamic library, ep1.dll,


and supporting files, in the default folder, codegen/dll/ep1. It generates the
minimal set of #include statements for header files required by the selected code
replacement library. On Linux and Macintosh systems, it generates a shared object
(.so) file. The DLL linkage conforms to the target language, in this example, C. If you
set the target language to C++, the linkage conforms to C++.

Note: The default target language is C. To change the target language to C++, see
“Specify a Language for Code Generation” on page 21-28.

21-13
21 Generating C/C++ Code from MATLAB Code

Generating Standalone C/C++ Executables from MATLAB Code


In this section...
“Generate a C Executable Using the MATLAB Coder App” on page 21-14
“Generate a C Executable at the Command Line” on page 21-23
“Specifying main Functions for C/C++ Executables” on page 21-24
“Specify main Functions” on page 21-25

Generate a C Executable Using the MATLAB Coder App


This example shows how to generate a C executable from MATLAB code using the
MATLAB Coder app. In this example, you generate an executable for a MATLAB
function that generates a random scalar value. Using the app, you:

1 Generate a C main function that calls the generated library function.


2 Copy and modify the generated main.c and main.h.
3 Modify the project settings so that the app can find the modified main.c and
main.h.
4 Generate the executable.

Create the Entry-Point Function

In a local writable folder, create a MATLAB function, coderand, that generates a


random scalar value from the standard uniform distribution on the open interval (0,1):
function r = coderand() %#codegen
r = rand();

Create the Test File

In the same local writable folder, create a MATLAB file, coderand_test.m, that calls
coderand.
function y = coderand_test()
y = coderand();

Open the MATLAB Coder app

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

21-14
Generating Standalone C/C++ Executables from MATLAB Code

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 coderand.

The app creates a project with the default name coderand.prj in the current
folder.
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.

In this example, the function coderand does not have inputs.

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. 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 .

Select or enter the test file coderand_test.


2 Click Check for Issues.

The app generates a MEX function for coderand. It runs the test file replacing calls
to coderand with calls to the MEX function. If the app detects issues during the
MEX function generation or execution, it provides warning and error messages.

21-15
21 Generating C/C++ Code from MATLAB Code

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 a C main Function

When you generate an executable, you must provide a C/C++ function. By default,
when you generate C/C++ source code, static libraries, dynamically linked libraries, or
executables, MATLAB Coder generates a main function. This generated main function is
a template that you modify for your application. See “Incorporate Generated Code Using
an Example Main Function” on page 25-18. After you copy and modify the generated
main function, you can use it for generation of the C/C++ executable. Alternatively, you
can write your own main function.

Before you generate the executable for coderand, generate a main function that calls
coderand.

1
To open the Generate dialog box, click the Generate arrow .
2 In the Generate dialog box, set Build type to Source Code and Language to C.
Use the default values for the other project build configuration settings.
3 Click More Settings.
4 On the All Settings tab, under Advanced, verify that Generate example main is
set to Generate, but do not compile, an example main function. Click
Close.
5 Click Generate.

MATLAB Coder generates a main.c file and a main.h file. The app indicates that
code generation succeeded.
6 Click Next to open the Finish Workflow page.

On the Finish Workflow page, under Generated Output, you see that main.c is
in the subfolder coderand\codegen\lib\coderand\examples.

Copy the Generated Example Main Files

Because subsequent code generation can overwrite the generated example files, before
you modify these files, copy them to a writable folder outside of the codegen folder. For
this example, copy main.c and main.h from the subfolder coderand\codegen\lib
\coderand\examples to a writable folder, for example, c:\myfiles.

21-16
Generating Standalone C/C++ Executables from MATLAB Code

Modify the Generated Example Main Files

1 In the folder that contains a copy of the example main files, open main.c.

Generated main.c

/*************************************************************************/
/* This automatically generated example C main file shows how to call */
/* entry-point functions that MATLAB Coder generated. You must customize */
/* this file for your application. Do not modify this file directly. */
/* Instead, make a copy of this file, modify it, and integrate it into */
/* your development environment. */
/* */
/* This file initializes entry-point function arguments to a default */
/* size and value before calling the entry-point functions. It does */
/* not store or use any values returned from the entry-point functions. */
/* If necessary, it does pre-allocate memory for returned values. */
/* You can use this file as a starting point for a main function that */
/* you can deploy in your application. */
/* */
/* After you copy the file, and before you deploy it, you must make the */
/* following changes: */
/* * For variable-size function arguments, change the example sizes to */
/* the sizes that your application requires. */
/* * Change the example values of function arguments to the values that */
/* your application requires. */
/* * If the entry-point functions return values, store these values or */
/* otherwise use them as required by your application. */
/* */
/*************************************************************************/
/* Include Files */
#include "rt_nonfinite.h"
#include "coderand.h"
#include "main.h"
#include "coderand_terminate.h"
#include "coderand_initialize.h"

/* Function Declarations */
static void main_coderand(void);

/* Function Definitions */

/*
* Arguments : void

21-17
21 Generating C/C++ Code from MATLAB Code

* Return Type : void


*/
static void main_coderand(void)
{
double r;

/* Call the entry-point 'coderand'. */


r = coderand();
}

/*
* Arguments : int argc
* const char * const argv[]
* Return Type : int
*/
int main(int argc, const char * const argv[])
{
(void)argc;
(void)argv;

/* Initialize the application.


You do not need to do this more than one time. */
coderand_initialize();

/* Invoke the entry-point functions.


You can call entry-point functions multiple times. */
main_coderand();

/* Terminate the application.


You do not need to do this more than one time. */
coderand_terminate();
return 0;
}

/*
* File trailer for main.c
*
* [EOF]
*/
2 Modify main.c so that it prints the results of a coderand call:

• In main_coderand, delete the line

double r;

21-18
Generating Standalone C/C++ Executables from MATLAB Code

• In main_coderand, replace

r = coderand()
with

printf("coderand=%g\n", coderand());
• For this example, main does not have arguments. In main, delete the lines:

(void)argc;
(void)argv;

Change the definition of main to

int main()

Modified main.c

/* Include Files */
#include "rt_nonfinite.h"
#include "coderand.h"
#include "main.h"
#include "coderand_terminate.h"
#include "coderand_initialize.h"

/* Function Declarations */
static void main_coderand(void);

/* Function Definitions */

/*
* Arguments : void
* Return Type : void
*/
static void main_coderand(void)
{
/* Call the entry-point 'coderand'. */
printf("coderand=%g\n", coderand());
}

/*
* Arguments : int argc
* const char * const argv[]
* Return Type : int
*/

21-19
21 Generating C/C++ Code from MATLAB Code

int main()
{

/* Initialize the application.


You do not need to do this more than one time. */
coderand_initialize();

/* Invoke the entry-point functions.


You can call entry-point functions multiple times. */
main_coderand();

/* Terminate the application.


You do not need to do this more than one time. */
coderand_terminate();
return 0;
}

/*
* File trailer for main.c
*
* [EOF]
*/
3 Open main.h

Generated main.h

*************************************************************************/
/* This automatically generated example C main file shows how to call */
/* entry-point functions that MATLAB Coder generated. You must customize */
/* this file for your application. Do not modify this file directly. */
/* Instead, make a copy of this file, modify it, and integrate it into */
/* your development environment. */
/* */
/* This file initializes entry-point function arguments to a default */
/* size and value before calling the entry-point functions. It does */
/* not store or use any values returned from the entry-point functions. */
/* If necessary, it does pre-allocate memory for returned values. */
/* You can use this file as a starting point for a main function that */
/* you can deploy in your application. */
/* */
/* After you copy the file, and before you deploy it, you must make the */
/* following changes: */
/* * For variable-size function arguments, change the example sizes to */
/* the sizes that your application requires. */

21-20
Generating Standalone C/C++ Executables from MATLAB Code

/* * Change the example values of function arguments to the values that */


/* your application requires. */
/* * If the entry-point functions return values, store these values or */
/* otherwise use them as required by your application. */
/* */
/*************************************************************************/
#ifndef __MAIN_H__
#define __MAIN_H__

/* Include Files */

#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "rtwtypes.h"
#include "coderand_types.h"

/* Function Declarations */
extern int main(int argc, const char * const argv[]);

#endif

/*
* File trailer for main.h
*
* [EOF]
*/
4 Modify main.h:

• Add stdio to the include files:

#include <stdio.h>
• Change the declaration of main to

extern int main()

Modified main.h

#ifndef __MAIN_H__
#define __MAIN_H__

/* Include Files */

21-21
21 Generating C/C++ Code from MATLAB Code

#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "rtwtypes.h"
#include "coderand_types.h"

/* Function Declarations */
extern int main();

#endif

/*
* File trailer for main.h
*
* [EOF]
*/

Generate the Executable

1
To open the Generate Code page, expand the workflow steps and click
Generate
2
To open the Generate dialog box, click the Generate arrow .
3 Set Build type to Executable (.exe).
4 Click More Settings.
5 On the Custom Code tab, in Additional source files, enter main.c
6 On the Custom Code tab, in Additional include directories, enter the location of
the modified main.c and main.h files. For example, c:\myfiles. Click Close.
7 To generate the executable, click Generate.

The app indicates that code generation succeeded.


8 Click Next to go to the Finish Workflow step.
9 Under Generated Output, you can see the location of the generated executable
coderand.exe.

Run the Executable

To run the executable in MATLAB on a Windows platform:

21-22
Generating Standalone C/C++ Executables from MATLAB Code

system('coderand')

Generate a C Executable at the Command Line


In this example, you create a MATLAB function that generates a random scalar value
and a main C function that calls this MATLAB function. You then specify types for the
function input parameters, specify the main function, and generate a C executable for the
MATLAB code.

1 Write a MATLAB function, coderand, that generates a random scalar value from
the standard uniform distribution on the open interval (0,1):

function r = coderand() %#codegen


r = rand();
2 Write a main C function, c:\myfiles\main.c, that calls coderand. For example:

/*
** main.c
*/
#include <stdio.h>
#include <stdlib.h>
#include "coderand.h"
#include "coderand_initialize.h"
#include "coderand_terminate.h"

int main()
{
coderand_initialize();

printf("coderand=%g\n", coderand());

coderand_terminate();

return 0;
}

Note: In this example, because the default file partitioning method is to generate
one file for each MATLAB file, you include “coderand_initialize.h” and
“coderand_terminate.h”. If your file partitioning method is set to generate
one file for all functions, do not include “coderand_initialize.h” and
“coderand_terminate.h”.

21-23
21 Generating C/C++ Code from MATLAB Code

3 Configure your code generation parameters to include the main C function and then
generate the C executable:

cfg = coder.config('exe');
cfg.CustomSource = 'main.c';
cfg.CustomInclude = 'c:\myfiles';
codegen -config cfg coderand

codegen generates a C executable, coderand.exe, in the current folder. It


generates supporting files in the default folder, codegen/exe/coderand. codegen
generates the minimal set of #include statements for header files required by the
selected code replacement library.

Specifying main Functions for C/C++ Executables


When you generate an executable, you must provide a main function. For a C executable,
provide a C file, main.c. For a C++ executable, provide a C++ file, main.cpp. Verify that
the folder containing the main function has only one main file. Otherwise, main.c takes
precedence over main.cpp, which causes an error when generating C++ code. You can
specify the main file from the project settings dialog box, the command line, or the Code
Generation dialog box.

By default, when you generate C/C++ source code, static libraries, dynamically linked
libraries, or executables, MATLAB Coder generates a main function. This generated
main function is a template that you modify for your application. See “Incorporate
Generated Code Using an Example Main Function” on page 25-18. After you copy
and modify the generated main function, you can use it for generation of the C/C++
executable. Alternatively, you can write your own main function.

When you convert a MATLAB function to a C/C++ library function or a C/C++


executable, MATLAB Coder generates an initialize function and a terminate function.

• If your file partitioning method is set to generate one file for each MATLAB file, you
must include the initialize and terminate header functions in main.c. Otherwise, do
not include them in main.c.
• You must call these functions along with the C/C++ function. For more information,
see “Calling Initialize and Terminate Functions” on page 25-7.

21-24
Generating Standalone C/C++ Executables from MATLAB Code

Specify main Functions


Specifying main Functions Using the MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Click More Settings.
3 On the Custom Code tab, set:

a Additional source files to the name of the C/C++ source file that contains the
main function. For example, main.c. For more information, see “Specifying
main Functions for C/C++ Executables” on page 21-24.
b Additional include directories to the location of main.c. For example, c:
\myfiles.

Specifying main Functions at the Command Line

Set the CustomSource and CustomInclude properties of the code generation


configuration object (see “Working with Configuration Objects” on page 21-33).
The CustomInclude property indicates the location of C/C++ files specified by
CustomSource.

1 Create a configuration object for an executable:


cfg = coder.config('exe');
2 Set the CustomSource property to the name of the C/C++ source file that contains
the main function. (For more information, see “Specifying main Functions for C/C++
Executables” on page 21-24.) For example:
cfg.CustomSource = 'main.c';
3 Set the CustomInclude property to the location of main.c. For example:

cfg.CustomInclude = 'c:\myfiles';
4 Generate the C/C++ executable using the command-line options. For example, if
myFunction takes one input parameter of type double:

codegen -config cfg myMFunction -args {0}

MATLAB Coder compiles and links the main function with the C/C++ code that it
generates from myMFunction.m.

21-25
21 Generating C/C++ Code from MATLAB Code

Configure Build Settings


In this section...
“Specify Build Type” on page 21-26
“Specify a Language for Code Generation” on page 21-28
“Specify Output File Name” on page 21-30
“Specify Output File Locations” on page 21-30
“Parameter Specification Methods” on page 21-32
“Specify Build Configuration Parameters” on page 21-32

Specify Build Type


Build Types

MATLAB Coder can generate code for the following output types:

• MEX function
• Standalone C/C++ code
• Standalone C/C++ code and compile it to a static library
• Standalone C/C++ code and compile it to a dynamically linked library
• Standalone C/C++ code and compile it to an executable

Note: When you generate an executable, you must provide a C/C++ file that contains
the main function, as described in “Specifying main Functions for C/C++ Executables”
on page 21-24.

Location of Generated Files

By default, MATLAB Coder generates files in output folders based on your output type.
For more information, see “Generated Files and Locations” on page 21-130.

Note: Each time MATLAB Coder generates the same type of output for the same code or
project, it removes the files from the previous build. If you want to preserve files from a
build, copy them to a different location before starting another build.

21-26
Configure Build Settings

Specify the Build Type Using the MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Set Build type to one of the following.

• Source Code
• MEX
• Static Library
• Dynamic Library
• Executable

If you select Source Code, MATLAB Coder does not invoke the make command or
generate compiled object code. When you want to iterate rapidly between modifying
MATLAB code and generating C/C++ code and you want to inspect the generated code,
this option saves you time. This option is equivalent to Static Library with the
Generate code only box selected. See “Generate Code Only” on page 21-78.

Code generation uses a different set of configuration parameters for MEX functions
than it uses for the other build types. . When you switch the output type between MEX
Function and Source, Static Library, Dynamic Library, or Executable, verify
these settings. For more information, see “Changing Output Type” on page 18-31.

Specifying the Build Type at the Command Line

Call codegen with the -config option. For example, suppose that you have a primary
function foo that takes no input parameters. The following table shows how to specify
different output types when compiling foo. If a primary function has input parameters,
you must specify these inputs. For more information, see “Primary Function Input
Specification” on page 21-45.

Note: C is the default language for code generation with MATLAB Coder. To generate C+
+ code, see “Specify a Language for Code Generation” on page 21-28.

To Generate: Use This Command:


MEX function using the default codegen foo
code generation options

21-27
21 Generating C/C++ Code from MATLAB Code

To Generate: Use This Command:


MEX function specifying code cfg = coder.config('mex');
generation options % Set configuration parameters, for example,
% enable a code generation report
cfg.GenerateReport=true;
% Call codegen, passing the configuration
% object
codegen -config cfg foo
Standalone C/C++ code and codegen -config:lib foo
compile it to a library using the
default code generation options
Standalone C/C++ code and cfg = coder.config('lib');
compile it to a library specifying % Set configuration parameters, for example,
code generation options % enable a code generation report
cfg.GenerateReport=true;
% Call codegen, passing the configuration
% object
codegen -config cfg foo
Standalone C/C++ code and codegen -config:exe main.c foo
compile it to an executable using
the default code generation
options and specifying the Note: You must specify a main function for generating a C/
main.c file at the command line C++ executable. See “Specifying main Functions for C/C++
Executables” on page 21-24
Standalone C/C++ code and cfg = coder.config('exe');
compile it to an executable % Set configuration parameters, for example,
specifying code generation % specify main file
cfg.CustomSource = 'main.c';
options
cfg.CustomInclude = 'c:\myfiles';
codegen -config cfg foo

Note: You must specify a main function for generating a C/


C++ executable. See “Specifying main Functions for C/C++
Executables” on page 21-24

Specify a Language for Code Generation


• “Specify the Language Using the MATLAB Coder App” on page 21-29

21-28
Configure Build Settings

• “Specifying the Language Using the Command-Line Interface” on page 21-29

MATLAB Coder can generate C or C++ libraries and executables. C is the default
language. You can specify a language explicitly from the project settings dialog box or at
the command line.

Specify the Language Using the MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Set Language to C or C++.

Note: If you specify C++, MATLAB Coder wraps the C code into .cpp files. You can
use a C++ compiler and interface with external C++ applications. MATLAB Coder
does not generate C++ classes.

Specifying the Language Using the Command-Line Interface

1 Select a suitable compiler for your target language.


2 Create a configuration object for code generation. For example, for a library:

cfg = coder.config('lib');
3 Set the TargetLang property to 'C' or 'C++'. For example:

cfg.TargetLang = 'C++';

Note: If you specify C++, MATLAB Coder wraps the C code into .cpp files. You can
then use a C++ compiler and interface with external C++ applications. MATLAB
Coder does not generate C++ classes.

See Also

• “Working with Configuration Objects” on page 21-33


• “Setting Up the C or C++ Compiler”

21-29
21 Generating C/C++ Code from MATLAB Code

Specify Output File Name


Specify Output File Name Using the MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 In the Output file name field, enter the file name.

Note: Do not put spaces in the file name.

By default, if the name of the first entry-point MATLAB file is fcn1, the output file name
is:

• fcn1 for C/C++ libraries and executables.


• fcn1_mex for MEX functions.

By default, MATLAB Coder generates files in the folder project_folder/codegen/


target/fcn1:

• project_folder is your current project folder


• target is:

• mex for MEX functions


• lib for static C/C++ libraries
• dll for dynamic C/C++ libraries
• exe for C/C++ executables

Command-Line Alternative

Use the codegen function -o option.

Specify Output File Locations


Specify Output File Location Using the MATLAB Coder App

The output file location must not contain:

21-30
Configure Build Settings

• Spaces (Spaces can lead to code generation failures in certain operating system
configurations).
• Tabs
• \, $, #, *, ?
• Non-7-bit ASCII characters, such as Japanese characters.

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Set Build type to Source Code, Static Library, Dynamic Library, or
Executable (depending on your requirements).
3 Click More Settings.
4 Click the Paths tab.

The default setting for the Build folder field is A subfolder of the project
folder. By default, MATLAB Coder generates files in the folder project_folder/
codegen/target/fcn1:

• fcn1 is the name of the alphabetically first entry-point file.


• target is:

• mex for MEX functions


• lib for static C/C++ libraries
• dll for dynamically linked C/C++ libraries
• exe for C/C++ executables
5 To change the output location, you can either:

• Set Build Folder to A subfolder of the current MATLAB working


folder

MATLAB Coder generates files in the MATLAB_working_folder/codegen/


target/fcn1 folder
• Set Build Folder to Specified folder. In the Build folder name field,
provide the path to the folder.

Command-Line Alternative

Use the codegen function -d option.

21-31
21 Generating C/C++ Code from MATLAB Code

Parameter Specification Methods


If you are using Use Details
The MATLAB Coder app The project settings dialog box. “Specify Build Configuration
Parameters MATLAB Coder
App” on page 21-32
codegen at the command Configuration objects “Specify Build Configuration
line and want to specify a few Parameters at the Command
parameters Line Using Configuration
codegen in build scripts Objects” on page 21-33

codegen at the command Configuration object dialog “Specifying Build Configuration


line and want to specify many boxes Parameters at the Command
parameters Line Using Dialog Boxes” on
page 21-37

Specify Build Configuration Parameters


• “Specify Build Configuration Parameters MATLAB Coder App” on page 21-32
• “Specify Build Configuration Parameters at the Command Line Using Configuration
Objects” on page 21-33
• “Specifying Build Configuration Parameters at the Command Line Using Dialog
Boxes” on page 21-37

You can specify build configuration parameters from the MATLAB Coder project settings
dialog box, the command line, or configuration object dialog boxes.

Specify Build Configuration Parameters MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Set Build type to Source Code, Static Library, Dynamic Library, or
Executable (depending on your requirements).
3 Click More Settings.

The project settings dialog box provides the set of configuration parameters
applicable to the output type that you select. Code generation uses a different set of
configuration parameters for MEX functions than it uses for the other build types.

21-32
Configure Build Settings

When you switch the output type between MEX Function and Source Code,
Static Library, Dynamic Library, or Executable, verify these settings. See
“Changing Output Type” on page 18-31.
4 Modify the parameters as required. For more information about parameters on a tab,
click Help.

Changes to the parameter settings take place immediately.

Specify Build Configuration Parameters at the Command Line Using Configuration Objects
Types of Configuration Objects

The codegen function uses configuration objects to customize your environment for code
generation. The following table lists the available configuration objects.

Configuration Object Description


coder.CodeConfig If no Embedded Coder license is available or you disable
use of the Embedded Coder license, specifies parameters
for C/C++ library or executable generation.

For more information, see the class reference information


for coder.CodeConfig.
coder.EmbeddedCodeConfig If an Embedded Coder license is available, specifies
parameters for C/C++ library or executable generation.

For more information, see the class reference information


for coder.EmbeddedCodeConfig.
coder.HardwareImplementation Specifies parameters of the target hardware
implementation. If not specified, codegen generates code
that is compatible with the MATLAB host computer.

For more information, see the class reference information


for coder.HardwareImplementation.
coder.MexCodeConfig Specifies parameters for MEX code generation.

For more information, see the class reference information


for coder.MexCodeConfig.

Working with Configuration Objects

To use configuration objects to customize your environment for code generation:

21-33
21 Generating C/C++ Code from MATLAB Code

1 In the MATLAB workspace, define configuration object variables, as described in


“Creating Configuration Objects” on page 21-35.

For example, to generate a configuration object for C static library generation:


cfg = coder.config('lib');
% Returns a coder.CodeConfig object if no
% Embedded Coder license available.
% Otherwise, returns a coder.EmbeddedCodeConfig object.
2 Modify the parameters of the configuration object as required, using one of these
methods:

• Interactive commands, as described in “Specify Build Configuration Parameters


at the Command Line Using Configuration Objects” on page 21-33
• Dialog boxes, as described in “Specifying Build Configuration Parameters at the
Command Line Using Dialog Boxes” on page 21-37
3 Call the codegen function with the -config option. Specify the configuration object
as its argument.

The -config option instructs codegen to generate code for the target, based on
the configuration property values. In the following example, codegen generates a
C static library from a MATLAB function, foo, based on the parameters of a code
generation configuration object, cfg, defined in the first step:

codegen -config cfg foo

The -config option specifies the type of output that you want to build — in this
case, a C static library. For more information, see codegen.

21-34
Configure Build Settings

Creating Configuration Objects

You can define a configuration object in the MATLAB workspace.

To Create... Use a Command Such As...


MEX configuration object cfg = coder.config('mex');
coder.MexCodeConfig
Code generation configuration % To generate a static library
object for generating a standalone cfg = coder.config('lib');
C/C++ library or executable % To generate a dynamic library
cfg = coder.config('dll')
coder.CodeConfig
% To generate an executable
cfg = coder.config('exe');

Note: If an Embedded Coder license is available, creates a


coder.EmbeddedCodeConfig object.

If you use concurrent licenses, to disable the check out of an


Embedded Coder license, use one of the following commands:
cfg = coder.config('lib', 'ecoder', false)

cfg = coder.config('dll', 'ecoder', false)

cfg = coder.config('exe', 'ecoder', false)


Code generation configuration % To generate a static library
object for generating a standalone cfg = coder.config('lib');
C/C++ library or executable for an % To generate a dynamic library
cfg = coder.config('dll')
embedded target
% To generate an executable
coder.EmbeddedCodeConfig cfg = coder.config('exe');

Note: Requires an Embedded Coder license; otherwise creates


a coder.CodeConfig object.
Hardware implementation hwcfg = coder.HardwareImplementation
configuration object
coder.HardwareImplementation

21-35
21 Generating C/C++ Code from MATLAB Code

Each configuration object comes with a set of parameters, initialized to default values.
You can change these settings, as described in “Modifying Configuration Objects at the
Command Line Using Dot Notation” on page 21-36.
Modifying Configuration Objects at the Command Line Using Dot Notation

You can use dot notation to modify the value of one configuration object parameter at a
time. Use this syntax:

configuration_object.property = value

Dot notation uses assignment statements to modify configuration object properties:

• To specify a main function during C/C++ code generation:

cfg = coder.config('exe');
cfg.CustomInclude = 'c:\myfiles';
cfg.CustomSource = 'main.c';
codegen -config cfg foo
• To automatically generate and launch code generation reports after generating a C/C+
+ static library:

cfg = coder.config('lib');
cfg.GenerateReport= true;
cfg.LaunchReport = true;
codegen -config cfg foo

Saving Configuration Objects

Configuration objects do not automatically persist between MATLAB sessions. Use one of
the following methods to preserve your settings:

Save a configuration object to a MAT-file and then load the MAT-file at your next session

For example, assume that you create and customize a MEX configuration object mexcfg
in the MATLAB workspace. To save the configuration object, at the MATLAB prompt,
enter:

save mexcfg.mat mexcfg


The save command saves mexcfg to the file mexcfg.mat in the current folder.

To restore mexcfg in a new MATLAB session, at the MATLAB prompt, enter:

load mexcfg.mat

21-36
Configure Build Settings

The load command loads the objects defined in mexcfg.mat to the MATLAB workspace.

Write a script that creates the configuration object and sets its properties.

You can rerun the script whenever you need to use the configuration object again.

Specifying Build Configuration Parameters at the Command Line Using Dialog Boxes

1 Create a configuration object as described in “Creating Configuration Objects” on


page 21-35.

For example, to create a coder.MexCodeConfig configuration object for MEX code


generation:
mexcfg = coder.config('mex');
2 Open the property dialog box using one of these methods:

• In the MATLAB workspace, double-click the configuration object variable.


• At the MATLAB prompt, issue the open command, passing it the configuration
object variable, as in this example:
open mexcfg
3 In the dialog box, modify configuration parameters as required, then click Apply.
4 Call the codegen function with the -config option. Specify the configuration object
as its argument:
codegen -config mexcfg foo

The -config option specifies the type of output that you want to build. For more
information, see codegen.

21-37
21 Generating C/C++ Code from MATLAB Code

Specify Data Types Used in Generated Code


In this section...
“Specify Data Type Using the MATLAB Coder App” on page 21-38
“Specify Data Type at the Command Line” on page 21-38

MATLAB Coder can use built-in C data types or predefined types from rtwtypes.h in
generated code. By default, when the generated code declares variables, it uses built-in C
types.

You can explicitly specify the data types used in generated code in the project settings
dialog box or at the command line.

Specify Data Type Using the MATLAB Coder App


1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Set Build type to Source Code, Static Library, Dynamic Library, or
Executable (depending on your requirements).
3 Click More Settings.
4 To use built-in C types, on the Code Appearance tab, set Data Type
Replacement to Use built-in C data types in the generated code.
To use predefined types from rtwtypes.h, set Data Type Replacement to Use
MathWorks typedefs in the generated code.

Specify Data Type at the Command Line


1 Create a configuration object for code generation. Use coder.config with
arguments 'lib','dll', or 'exe' (depending on your requirements). For example:

cfg = coder.config('lib');
2 To use built-in C types, set the DataTypeReplacement property to 'CBuiltIn'.

cfg.DataTypeReplacement = 'CBuiltIn';

To use predefined types from rtwtypes.h, set the DataTypeReplacement property


to 'CoderTypedefs'.

21-38
Standard Math Libraries

Standard Math Libraries


By default, the MATLAB Coder software generates code that calls the ISO/IEC
9899:1990 C math library for math operations. Depending on your programming
language choice, you have the option of changing the standard math library that the code
generation software uses. Available libraries include:

Library Name Language Support Standard


C89/C90 (ANSI) C, C++ ISO/IEC 9899:1990 (default)
C99 (ISO) C, C++ ISO/IEC 9899:1999
C++03 (ISO) C++ ISO/IEC 14882:2003

The C++03 (ISO) math library is available for use only if you select C++ for the language
support.

21-39
21 Generating C/C++ Code from MATLAB Code

Change the Standard Math Library


By default, the MATLAB Coder software uses the ISO/IEC 9899:1990 C math library
when generating C or C++ code. If your compiler supports newer language standards,
you can specify a different supported library. To change the library:

• In the project build settings, on the Custom Code tab, set the Standard math
library parameter.
• In a code configuration object, set the TargetLangStandard parameter.

See Also
• “Standard Math Libraries” on page 21-39
• “Specify Build Configuration Parameters MATLAB Coder App” on page 21-32
• “Specify Build Configuration Parameters at the Command Line Using Configuration
Objects” on page 21-33

21-40
Share Build Configuration Settings

Share Build Configuration Settings


To share build configuration settings between multiple projects or between the project
and command-line workflow, you can export settings to and import settings from a code
generation configuration object.

Export Settings
To export the current project settings to a code generation configuration object stored in
the base workspace:

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Set Build type to Source Code, Static Library, Dynamic Library), or
Executable (depending on your requirements).
3 Click More Settings.
4 Click Import/Export Settings.
5 In the Variable name field, specify a name for the configuration object.
6 Click Export to Variable.

MATLAB Coder saves the project settings information in a configuration object with
the specified name in the base workspace.

Project Output Type Configuration Object


MEX Function coder.MexCodeConfig
C/C++ Static Library Without an Embedded Coder license:
C/C++ Dynamic Library coder.CodeConfig
With an Embedded Coder license:
C/C++ Executable coder.EmbeddedCodeConfig

You can then either import these settings into another project or use the
configuration object with the codegen function -config option to generate code at
the command line.

21-41
21 Generating C/C++ Code from MATLAB Code

Import Settings
To import the settings saved in a code generation configuration object stored in the base
workspace:

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Set Build type to Source Code, Static Library, Dynamic Library, or
Executable (depending on your requirements).
3 Click More Settings.
4 Click Import/Export Settings.
5 In the Variable name field, specify the name of the configuration object.
6 Click Import from Variable.

See Also
• “Configure Build Settings” on page 21-26
• coder.config
• “Convert MATLAB Coder Project to MATLAB Script” on page 21-43

21-42
Convert MATLAB Coder Project to MATLAB Script

Convert MATLAB Coder Project to MATLAB Script


After you define input types, you can convert a MATLAB Coder project to the equivalent
script of MATLAB commands. The script reproduces the project in a configuration object
and runs the codegen command. You can:

• Move from a project workflow to a command-line workflow.


• Save the project as a text file that you can share.

You can convert a project using the MATLAB Coder app or the command-line interface.

Convert a Project Using the MATLAB Coder App


1
On the app toolbar, click , and then select Convert to script.
2 Specify the script name and click Save.

Convert a Project Using the Command-Line Interface


To convert a project to a script using the command-line interface, use the -tocode option
of the coder command. The project file must be on the search path.

For example, to convert the project, myproject.prj to the script named myscript.m
use this command:

coder -tocode myproject -script myscript.m

The coder command overwrites a file that has the same name as the script. If you omit
the -script option, the coder command writes the script to the Command Window.

For more information about the -tocode option, see coder.

Run the Script


1 Make sure that the entry-point functions that are arguments to codegen in the
script are on the search path.
2 Run the script. For example:

myscript

21-43
21 Generating C/C++ Code from MATLAB Code

The following variables appear in the base workspace.

Variable For
cfg Configuration object
ARGS Types of input arguments, if the project has
entry-point function inputs
ARG Types of cell array elements, if the project
has cell array inputs. A script can reuse
ARG for different cell array elements
GLOBALS Types and initial values of global variables,
if the project has global variables

cfg, ARGS, ARG, and GLOBALS appear in the workspace only after you run the script.
The type of configuration object depends on the project output type.

Project Output Type Configuration Object


MEX Function coder.MexCodeConfig
C/C++ Static Library Without an Embedded Coder license:
C/C++ Dynamic Library coder.CodeConfig
With an Embedded Coder license:
C/C++ Executable coder.EmbeddedCodeConfig

You can import the settings from the configuration object cfg into a project. See “Share
Build Configuration Settings” on page 21-41.

For a project that includes fixed-point conversion, project to script conversion generates a
pair of scripts for fixed-point conversion and fixed-point code generation. For an example,
see “Convert Fixed-Point Conversion Project to MATLAB Scripts” on page 15-107.

21-44
Primary Function Input Specification

Primary Function Input Specification


In this section...
“Why You Must Specify Input Properties” on page 21-45
“Properties to Specify” on page 21-45
“Rules for Specifying Properties of Primary Inputs” on page 21-48
“Methods for Defining Properties of Primary Inputs” on page 21-49
“Define Input Properties by Example at the Command Line” on page 21-50
“Specify Constant Inputs at the Command Line” on page 21-52
“Specify Variable-Size Inputs at the Command Line” on page 21-53

Why You Must Specify Input Properties


Because C and C++ are statically typed languages, MATLAB Coder must determine
the properties of all variables in the MATLAB files at compile time. To infer variable
properties in MATLAB files, MATLAB Coder must be able to 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,
MATLAB Coder can compile your MATLAB file without modification. You do not need to
specify properties of inputs to local functions or external functions called by the primary
function.

If you use the tilde (~) character to specify unused function inputs:

• In MATLAB Coder projects, if you want a different type to appear in the generated
code, specify the type. Otherwise, the inputs default to real, scalar doubles.
• When generating code with codegen, you must specify the type of these inputs using
the -args option.

Properties to Specify
If your primary function has inputs, you must specify the following properties for each
input.

For Specify properties


Class Size Complexity numerictype fimath

21-45
21 Generating C/C++ Code from MATLAB Code

For Specify properties


Fixed-point
inputs
Each field in Specify properties for each field according to its class
a structure
input When a primary input is a structure, the code generation software treats each
field as a separate input. Therefore, you must specify properties for allfields of a
primary structure input in the order that they appear in the structure definition:

• For each field of input structures, specify class, size, and complexity.
• For each field that is fixed-point class, also specify numerictype, and fimath.
Other inputs

Default Property Values

MATLAB Coder assigns the following default values for properties of primary function
inputs.

Property Default
class double
size scalar
complexity real
numerictype No default
fimath MATLAB default fimath object
Specifying Default Values for Structure Fields

In most cases, when you do not explicitly specify values for properties, MATLAB Coder
uses defaults except for structure fields. The only way to name a field in a structure is
to set at least one of its properties. Therefore, you might need to specify default values
for properties of structure fields. For examples, see “Specifying Class and Size of Scalar
Structure” on page 21-76 and “Specifying Class and Size of Structure Array” on page
21-76.
Specifying Default fimath Values for MEX Functions

MEX functions generated with MATLAB Coder use the default fimath value in effect
at compile time. If you do not specify a default fimath value, MATLAB Coder uses the
MATLAB default fimath. The MATLAB factory default has the following properties:

21-46
Primary Function Input Specification

RoundingMethod: Nearest
OverflowAction: Saturate
ProductMode: FullPrecision
SumMode: FullPrecision
CastBeforeSum: true
For more information, see “fimath for Sharing Arithmetic Rules”.

When running MEX functions that depend on the default fimath value, do not change
this value during your MATLAB session. Otherwise, you receive a run-time warning,
alerting you to a mismatch between the compile-time and run-time fimath values.

For example, suppose that you define the following MATLAB function test:
function y = test %#codegen
y = fi(0);

The function test constructs a fi object without explicitly specifying a fimath object.
Therefore, test relies on the default fimath object in effect at compile time. At the
MATLAB prompt, generate the MEX function text_mex to use the factory setting of the
MATLAB default fimath:
codegen test
% codegen generates a MEX function, test_mex,
% in the current folder

Next, run test_mex to display the MATLAB default fimath value:


test_mex

ans =

DataTypeMode: Fixed-point: binary point scaling


Signedness: Signed
WordLength: 16
FractionLength: 15

Now create a local MATLAB fimath value. so you no longer use the default setting:
F = fimath('RoundingMethod','Floor');

Finally, clear the MEX function from memory and rerun it:
clear test_mex
test_mex

21-47
21 Generating C/C++ Code from MATLAB Code

The mismatch is detected and causes an error:

??? This function was generated with a different default


fimath than the current default.

Error in ==> test_mex

Supported Classes

The following table presents the class names supported by MATLAB Coder.

Class Name Description


logical Logical array of true and false values
char Character array
int8 8-bit signed integer array
uint8 8-bit unsigned integer array
int16 16-bit signed integer array
uint16 16-bit unsigned integer array
int32 32-bit signed integer array
uint32 32-bit unsigned integer array
int64 64-bit signed integer array
uint64 64–bit unsigned integer array
single Single-precision floating-point or fixed-point
number array
double Double-precision floating-point or fixed-point
number array
struct Structure array
embedded.fi Fixed-point number array

Rules for Specifying Properties of Primary Inputs


When specifying the properties of primary inputs, follow these rules.

• You must specify the class of all primary inputs. If you do not specify the size or
complexity of primary inputs, they default to real scalars.

21-48
Primary Function Input Specification

• For each primary function input whose class is fixed point (fi), you must specify the
input numerictype and fimath properties.
• For each primary function input whose class is struct, you must specify the
properties of each of its fields in the order that they appear in the structure definition.

Methods for Defining Properties of Primary Inputs

Method Advantages Disadvantages


“Specify Properties of • If you are working in a MATLAB • Not efficient for specifying
Entry-Point Function Coder project, easy to use memory-intensive inputs such as
Inputs Using the App” • Does not alter original MATLAB large structures and arrays
on page 18-3 code
• MATLAB Coder saves the
definitions in the project file
“Define Input • Easy to use • Must be specified at the
Properties by Example • Does not alter original MATLAB command line every time you
at the Command Line” code invoke codegen (unless you use
on page 21-50 a script)
• Designed for prototyping a
function that has a few primary • Not efficient for specifying
inputs memory-intensive inputs such as
Note: If you define
large structures and arrays
input properties
programmatically
in the MATLAB file,
you cannot use this
method
“Define Input • Integrated with MATLAB code; • Uses complex syntax
Properties no need to redefine properties • MATLAB Coder project
Programmatically in each time you invoke MATLAB files do not currently
the MATLAB File” on Coder recognize properties defined
page 21-66 • Provides documentation of programmatically. If you are
property specifications in the using a project, you must reenter
MATLAB code the input types in the project.
• Efficient for specifying memory-
intensive inputs such as large
structures

21-49
21 Generating C/C++ Code from MATLAB Code

Define Input Properties by Example at the Command Line


• “Command-Line Option -args” on page 21-50
• “Rules for Using the -args Option” on page 21-50
• “Specifying Properties of Primary Inputs by Example at the Command Line” on page
21-51
• “Specifying Properties of Primary Fixed-Point Inputs by Example at the Command
Line” on page 21-51

Command-Line Option -args

The codegen function provides a command-line option -args for specifying the
properties of primary (entry-point) function inputs as a cell array of example values. The
cell array can be a variable or literal array of constant values. Using this option, you
specify the properties of inputs at the same time as you generate code for the MATLAB
function with codegen .

If you have a test function or script that calls the entry-point MATLAB function with the
required types, you can use coder.getArgTypes to determine the types of the function
inputs. coder.getArgTypes returns a cell array of coder.Type objects that you can
pass to codegen using the -args option. See “Specifying General Properties of Primary
Inputs” on page 21-72 for codegen.

For information about specifying cell array inputs, see “Specify Cell Array Inputs at the
Command Line” on page 21-55.

Rules for Using the -args Option

When using the -args command-line option to define properties by example, follow these
rules:

• The cell array of sample values must contain the same number of elements as
primary function inputs.
• The order of elements in the cell array must correspond to the order in which inputs
appear in the primary function signature — for example, the first element in the cell
array defines the properties of the first primary function input.

Note: If you specify an empty cell array with the -args option, codegen interprets this
to mean that the function takes no inputs; a compile-time error occurs if the function
does have inputs.

21-50
Primary Function Input Specification

Specifying Properties of Primary Inputs by Example at the Command Line

Consider a MATLAB function that adds its two inputs:


function y = mcf(u,v)
%#codegen
y = u + v;

The following examples show how to specify different properties of the primary inputs u
and v by example at the command line:

• Use a literal cell array of constants to specify that both inputs are real scalar doubles:
codegen mcf -args {0,0}
• Use a literal cell array of constants to specify that input u is an unsigned 16-bit, 1-
by-4 vector and input v is a scalar double:
codegen mcf -args {zeros(1,4,'uint16'),0}
• Assign sample values to a cell array variable to specify that both inputs are real,
unsigned 8-bit integer vectors:
a = uint8([1;2;3;4])
b = uint8([5;6;7;8])
ex = {a,b}
codegen mcf -args ex

Specifying Properties of Primary Fixed-Point Inputs by Example at the Command Line

To generate a MEX function or C/C++ code for fixed-point MATLAB code, you must
install Fixed-Point Designer software.

Consider a MATLAB function that calculates the square root of a fixed-point number:
%#codegen
function y = sqrtfi(x)
y = sqrt(x);

To specify the properties of the primary fixed-point input x by example, follow these
steps:

1 Define the numerictype properties for x, for example:


T = numerictype('WordLength',32,...
'FractionLength',23,...

21-51
21 Generating C/C++ Code from MATLAB Code

'Signed',true);
2 Define the fimath properties for x, for example:

F = fimath('SumMode','SpecifyPrecision',...
'SumWordLength',32,...
'SumFractionLength',23,...
'ProductMode','SpecifyPrecision',...
'ProductWordLength',32,...
'ProductFractionLength',23);
3 Create a fixed-point variable with the numerictype and fimath properties that you
defined, for example:

myeg = { fi(4.0,T,F) };
4 Compile the function sqrtfi using the codegen command, passing the variable
myeg as the argument to the -args option, for example:

codegen sqrtfi -args myeg;

Specify Constant Inputs at the Command Line


If you know that your primary inputs do not change at run time, you can reduce overhead
in the generated code by specifying that the primary inputs are constant values.
Constant inputs are commonly used for flags that control how an algorithm executes and
values that specify the sizes or types of data.

To specify that inputs are constants, use the -args command-line option with a
coder.Constant object. To specify that an input is a constant with the size, class,
complexity, and value of constant_input, use the following syntax:

-args {coder.Constant(constant_input)}

Calling Functions with Constant Inputs

The code generation software compiles constant function inputs into the generated
code. In the generated C or C++ code, function signatures do not contain the constant
inputs. By default, MEX function signatures contain the constant inputs. When you call
a MEX function, you must provide the compile-time constant values. The constant input
values must match the compile-time values. You can control whether a MEX function
signature includes constant inputs and whether the constant input values must match
the compile-time values. See “Control Constant Inputs in MEX Function Signatures” on
page 21-62.

21-52
Primary Function Input Specification

Specifying a Structure as a Constant Input

Suppose that you define a structure tmp in the MATLAB workspace to specify the
dimensions of a matrix:
tmp = struct('rows', 2, 'cols', 3);

The following MATLAB function rowcol accepts a structure input p to define matrix y:
function y = rowcol(u,p) %#codegen
y = zeros(p.rows,p.cols) + u;

The following example shows how to specify that primary input u is a double scalar
variable and primary input p is a constant structure:
codegen rowcol -args {0,coder.Constant(tmp)}

Specify Variable-Size Inputs at the Command Line


Variable-size data is data whose size might change at run time. MATLAB supports
bounded and unbounded variable-size data for code generation. 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. You can define inputs to have one or
more variable-size dimensions — and specify their upper bounds — using the -args
option and coder.typeof function:
-args {coder.typeof(example_value, size_vector, variable_dims}
Specifies a variable-size input with:

• Same class and complexity as example_value


• Same size and upper bounds as size_vector
• Variable dimensions specified by variable_dims

When you enable dynamic memory allocation, you can specify Inf in the size vector for
dimensions with unknown upper bounds at compile time.

When variable_dims is a scalar, it is applied to all the dimensions, with the following
exceptions:

• If the dimension is 1 or 0, which are fixed.


• If the dimension is unbounded, which is always variable size.

21-53
21 Generating C/C++ Code from MATLAB Code

For more information, see coder.typeof and “Generate Code for Variable-Size Data” on
page 21-105.

Specifying a Variable-Size Vector Input

1 Write a function that computes the average of every n elements of a vector A and
stores them in a vector B:

function B = nway(A,n) %#codegen


% Compute average of every N elements of A and put them in B.

coder.extrinsic('error');
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
B = zeros(1,0);
error('n <= 0 or does not divide number of elements evenly');
end
2 Specify the first input A as a vector of double values. Its first dimension stays fixed in
size and its second dimension can grow to an upper bound of 100. Specify the second
input n as a double scalar.

codegen -report nway -args {coder.typeof(0,[1 100],1),1}


3 As an alternative, assign the coder.typeof expression to a MATLAB variable, then
pass the variable as an argument to -args:

vareg = coder.typeof(0,[1 100],1)


codegen -report nway -args {vareg, 0}

21-54
Specify Cell Array Inputs at the Command Line

Specify Cell Array Inputs at the Command Line


To specify cell array inputs at the command line, use the same methods that you use for
other types of inputs. You can:

• Provide an example cell array input to the -args option of the codegen command.
• Provide a coder.CellType object to the -args option of the codegen command. To
create a coder.CellType object, use coder.typeof.
• Use coder.Constant to specify a constant cell array input.

For code generation, cell arrays are classified as homogeneous or heterogeneous. See
“Homogeneous vs. Heterogeneous Cell Arrays” on page 9-2. When you provide an
example cell array to codegen or coder.typeof, the function determines whether
the cell array type is homogeneous or heterogeneous. If the cell array elements have
the same class and size, coder.typeof returns a homogeneous cell array type. If the
elements have different classes, coder.typeof returns a heterogeneous cell array type.
For some cell arrays, the classification as homogeneous or heterogeneous is ambiguous.
For example, the type for {1 [2 3]} can be a 1x2 heterogeneous type. The first element is
double and the second element is 1x2 double. The type can also be a 1x3 homogeneous
type in which the elements have class double and size 1x:2. For these ambiguous cases,
coder.typeof uses heuristics to classify the type as homogeneous or heterogeneous.
If you want a different classification, use the coder.CellType makeHomogeneous or
makeHeterogeneous methods. The makeHomogeneous method makes a homogeneous
copy of a type. The makeHeterogeneous method makes a heterogeneous copy of a type.

The makeHomogeneous and makeHeterogeneous methods permanently assign the


classification as homogeneous and heterogeneous, respectively. You cannot later use one
of these methods to create a copy that has a different classification.

If you have a test file, you can use coder.getArgTypes to determine input types.
In the output cell array of types, for cell array inputs, coder.getArgTypes returns
a coder.CellType object. If you want a different classification (homogeneous or
heterogeneous), use the makeHomogeneous or makeHeterogeneous methods.

Specify Cell Array Inputs by Example


To specify a cell array input by example, provide an example cell array in the -args
option of the codegen command.

21-55
21 Generating C/C++ Code from MATLAB Code

For example:

• To specify a 1x3 cell array whose elements have class double:

codegen myfunction -args {{1 2 3}} -report

The input argument is a 1x3 homogeneous cell array whose elements are 1x1 double.
• To specify a 1x2 cell array whose first element has class char and whose second
element has class double:

codegen myfunction -args {{'a', 1}} -report

The input argument is a 1x2 heterogeneous cell array whose first element is 1x1 char
and whose second element is 1x1 double.

Specify the Type of the Cell Array Input


To specify the type of a cell array input, use coder.typeof to create a
coder.CellType object. Pass the coder.CellType object to the -args option of the
codegen command.

For example:

• To specify a 1x3 cell array whose elements have class double:

t = coder.typeof({1 2 3});
codegen myfunction -args {t} -report

The input argument is a 1x3 homogeneous cell array whose elements are 1x1 double.
• To specify a 1x2 cell array whose first element has class char and whose second
element has class double:

t = coder.typeof({'a', 1});
codegen myfunction -args {t}

The input argument is a 1x2 heterogeneous cell array whose first element is a 1x1
char and whose second element is a 1x1 double.

You can also use the advanced function coder.newtype to create a coder.CellType
object.

21-56
Specify Cell Array Inputs at the Command Line

Make a Homogeneous Copy of a Type


If coder.typeof returns a heterogeneous cell array type, but you want a homogeneous
type, use the makeHomogeneous method to make a homogeneous copy of the type.

The following code creates a heterogeneous type.

t = coder.typeof({1 [2 3]})

t =

coder.CellType
1x2 heterogeneous cell
f0: 1x1 double
f1: 1x2 double

To make a homogeneous copy of the type, use:

t = makeHomogeneous(t)

t =

coder.CellType
1x2 homogeneous cell
base: 1x:2 double

Alternatively, use this notation:

t = makeHomogeneous(coder.typeof({1 [2 3]}))

t =

coder.CellType
1x2 homogeneous cell
base: 1x:2 double

The classification as homogeneous is permanent. You cannot later use the


makeHeterogeneous method to make a heterogeneous copy of the type.

If the elements of a type have different classes, such as char and double, you cannot use
makeHomogeneous to make a homogeneous copy of the type.

If you use coder.cstructname to specify a name for the structure type that represents
a type in the generated code, you cannot create a homogeneous copy of the type.

21-57
21 Generating C/C++ Code from MATLAB Code

Make a Heterogeneous Copy of a Type


If coder.typeof returns a homogeneous cell array type, but you want a heterogeneous
type, use the makeHeterogeneous method to make a heterogeneous copy of the type.

The following code creates a homogeneous type.

t = coder.typeof({1 2 3})

t =

coder.CellType
1x3 homogeneous cell
base: 1x1 double

To make the type heterogeneous, use:

t = makeHeterogeneous(t)

t =

coder.CellType
1x3 heterogeneous cell
f0: 1x1 double
f1: 1x1 double
f2: 1x1 double

Alternatively, use this notation:

t = makeHeterogeneous(coder.typeof({1 2 3}))

t =

coder.CellType
1x3 heterogeneous cell
f0: 1x1 double
f1: 1x1 double
f2: 1x1 double

The classification as heterogeneous is permanent. You cannot later use the


makeHomogeneous method to make a homogeneous copy of the type.

If a type is variable size, you cannot use makeHeterogeneous to make a heterogeneous


copy of it.

21-58
Specify Cell Array Inputs at the Command Line

Specify Variable-Size Cell Array Inputs


You can specify variable-size cell array inputs in the following ways:

• In the coder.typeof call.

For example, to specify a variable-size cell array whose first dimension is fixed and
whose second dimension has an upper bound of 5:

t = coder.typeof({1}, [1 5], [0 1])

t =

coder.CellType
1x:5 homogeneous cell
base: 1x1 double

For elements with the same classes, but different sizes, you can the use
coder.typeof size and variable dimensions arguments to create a variable-size
homogeneous cell array type. For example, the following code does not use the size
and variable dimensions arguments. This code creates a type for a heterogeneous cell
array.

t = coder.typeof({1 [2 3]})

t =

coder.CellType
1x2 heterogeneous cell
f0: 1x1 double
f1: 1x2 double

The following code, that uses the size and dimensions arguments, creates a type for a
variable-size homogeneous type cell array:

t = coder.typeof({1 [2 3]}, [1 5], [0 1])

t =

coder.CellType
1x:5 homogeneous cell
base: 1x:2 double
• Use coder.resize.

21-59
21 Generating C/C++ Code from MATLAB Code

For example, to specify a variable-size cell array whose first dimension is fixed and
whose second dimension has an upper bound of 5:

t = coder.typeof({1});
t = coder.resize(t, [1 5], [0,1])

t =

coder.CellType
1x5 homogeneous cell
base: 1x1 double

You cannot use coder.resize with a heterogeneous cell array type.

Specify Type Name for Heterogeneous Cell Array Inputs


A heterogeneous cell array is represented in the generated code as a structure. To specify
the name of the structure type in the generated code, use coder.cstructname.

For example, to specify the name myname for the cell array type in the generated code:

t = coder.typeof({'a', 1})
t = coder.cstructname(t, 'myname')

t =

coder.CellType
1x2 heterogeneous cell myname
f0: 1x1 char
f1: 1x1 double

If you use coder.cstructname with a homogeneous cell array type,


coder.cstructname returns a heterogeneous copy of the type. However, it is a best
practice to use the makeHeterogeneous method of the coder.CellType object
to make a heterogeneous copy of a homogeneous cell array type. Then, you can use
coder.cstructname with the heterogeneous copy of the type.

Specify Constant Cell Array Inputs


To specify that a cell array input is constant, use the coder.Constant function with the
-args option of the codegen command. For example:

21-60
Specify Cell Array Inputs at the Command Line

codegen myfunction -args {coder.Constant({'red', 1 'green', 2, 'blue', 3})} -report

The input is a 1x6 heterogeneous cell array. The sizes and classes of the elements are:

• 1x3 char
• 1x1 double
• 1x5 char
• 1x1 double
• 1x4 char
• 1x1 double

See Also
coder.CellType | coder.getArgTypes | coder.newtype | coder.resize |
coder.typeof

Related Examples
• “Define Input Properties by Example at the Command Line” on page 21-50
• “Specify Constant Inputs at the Command Line” on page 21-52

More About
• “Homogeneous vs. Heterogeneous Cell Arrays” on page 9-2

21-61
21 Generating C/C++ Code from MATLAB Code

Control Constant Inputs in MEX Function Signatures


In this section...
“Control MEX Function Signature Using the MATLAB Coder App” on page 21-62
“Control MEX Function Signature at the Command-Line Interface” on page 21-62
“Options for Controlling Constant Inputs in MEX Function Signatures” on page
21-63
“Call MEX Function with a Constant Input” on page 21-64
“See Also” on page 21-65

You can control whether a generated MEX function signature includes constant inputs.
If you want to use the same test file to run the original MATLAB function and the MEX
function, then the MEX function signature must contain the constant inputs. You can
also control whether the run-time values of the constant inputs must match the compile-
time values. Checking that the values match can slow down execution speed.

Control MEX Function Signature Using the MATLAB Coder App


1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Set Build type to MEX.
3 Click More Settings.
4 On the All Settings tab, set Constant Inputs to one of the menu options. See
“Options for Controlling Constant Inputs in MEX Function Signatures” on page
21-63.

Control MEX Function Signature at the Command-Line Interface


1 Create a code configuration object for MEX code generation.
mexcfg = coder.config('mex');
2 Set the ConstantInputs parameter to 'CheckValues', 'IgnoreValues', or
'Remove' For example:
mexcfg.ConstantInputs = 'IgnoreValues';

For a description of the options, see “Options for Controlling Constant Inputs in
MEX Function Signatures” on page 21-63

21-62
Control Constant Inputs in MEX Function Signatures

Options for Controlling Constant Inputs in MEX Function Signatures


The following table lists the options for the:

• Constant Inputs setting in a project with Output Type set to MEX.


• ConstantInputs property in a configuration object for MEX code generation.

Constant Inputs (Project) ConstantInputs (Configuration Description


Object)
Check values at run time 'CheckValues' • The MEX function signature
(default) includes the constant
inputs. When you call the
function, you must provide
the constant inputs.
• The run-time values of the
constant inputs must match
the compile-time values.
When you call the function,
you must provide the value
that was used at compile-
time.
• Allows you to use the same
test file to run the original
MATLAB algorithm and the
MEX function.
• Slows down execution of the
MEX function.
• This setting is the default.
Ignore input value 'IgnoreValues' • The MEX function signature
includes the constant
inputs. When you call the
function, you must provide
the constant inputs.
• The run-time values of the
constant inputs can differ
from the compile-time values.

21-63
21 Generating C/C++ Code from MATLAB Code

Constant Inputs (Project) ConstantInputs (Configuration Description


Object)
• Allows you to use the same
test file to run the original
MATLAB algorithm and the
MEX function.
Remove from MEX 'Remove' The MEX function signature
signature does not include the constant
inputs. When you call the
function, you do not provide the
constant inputs.

Call MEX Function with a Constant Input


This example shows how to call MEX functions that have constant inputs. It shows how
to use the ConstantInputs parameter to control whether the MEX function signature
includes constant inputs and whether the constant input values must match the compile-
time values.

Write a function identity that copies its input to its output.


function y = identity(u) %#codegen
y = u;

Create a code configuration object for MEX code generation.


cfg = coder.config('mex');

Generate a MEX function identity_mex with the constant input 42.


codegen identity -config cfg -args {coder.Constant(42)}

Call identity_mex. You must provide the input 42.


identity_mex(42)

ans =

42

Configure ConstantInputs so that the MEX function does not check that the input
value matches the compile-time value.

21-64
Control Constant Inputs in MEX Function Signatures

cfg.ConstantInputs = 'IgnoreValues';

Generate identity_mex with the new configuration.

codegen identity -config cfg -args {coder.Constant(42)}

Call identity_mex with a constant input value other than 42 .

identity_mex(50)

ans =

42

The MEX function ignored the input value 50.

Configure ConstantInputs so that the MEX function does not include the constant
input.
cfg.ConstantInputs = 'Remove';

Generate identity_mex with the new configuration.

codegen identity -config cfg -args {coder.Constant(42)}

Call identity_mex. Do not provide the input value .

identity_mex()

ans =

42

See Also
• “Specify Constant Inputs at the Command Line” on page 21-52

• “Define Constant Input Parameters Using the App” on page 18-23

21-65
21 Generating C/C++ Code from MATLAB Code

Define Input Properties Programmatically in the MATLAB File


With MATLAB Coder, you use the MATLAB assert function to define properties of
primary function inputs directly in your MATLAB file.

How to Use assert with MATLAB Coder


Use the assert function to invoke standard MATLAB functions for specifying the class,
size, and complexity of primary function inputs.

When specifying input properties using the assert function, use one of the following
methods. Use the exact syntax that is provided; do not modify it.

• “Specify Any Class” on page 21-66


• “Specify fi Class” on page 21-67
• “Specify Structure Class” on page 21-67
• “Specify Cell Array Class” on page 21-68
• “Specify Fixed Size” on page 21-68
• “Specify Scalar Size” on page 21-68
• “Specify Upper Bounds for Variable-Size Inputs” on page 21-69
• “Specify Inputs with Fixed- and Variable-Size Dimensions” on page 21-69
• “Specify Size of Individual Dimensions” on page 21-69
• “Specify Real Input” on page 21-70
• “Specify Complex Input” on page 21-70
• “Specify numerictype of Fixed-Point Input” on page 21-70
• “Specify fimath of Fixed-Point Input” on page 21-71
• “Specify Multiple Properties of Input” on page 21-71

Specify Any Class


assert ( isa ( param, 'class_name') )

Sets the input parameter param to the MATLAB class class_name. For example, to set
the class of input U to a 32-bit signed integer, call:
...
assert(isa(U,'int32'));

21-66
Define Input Properties Programmatically in the MATLAB File

...

Specify fi Class
assert ( isfi ( param ) )
assert ( isa ( param, 'embedded.fi' ) )

Sets the input parameter param to the MATLAB class fi (fixed-point numeric object).
For example, to set the class of input U to fi, call:
...
assert(isfi(U));
...

or
...
assert(isa(U,'embedded.fi'));
...

You must specify both the fi class and the numerictype. See “Specify numerictype
of Fixed-Point Input” on page 21-70. You can also set the fimath properties, see
“Specify fimath of Fixed-Point Input” on page 21-71. If you do not set the fimath
properties, codegen uses the MATLAB default fimath value.

Specify Structure Class


assert ( isstruct ( param ) )
assert ( isa ( param, 'struct' ) )

Sets the input parameter param to the MATLAB class struct (structure). For example,
to set the class of input U to a struct, call:
...
assert(isstruct(U));
...

or
...
assert(isa(U, 'struct'));
...

If you set the class of an input parameter to struct, you must specify the properties of
all fields in the order that they appear in the structure definition.

21-67
21 Generating C/C++ Code from MATLAB Code

Specify Cell Array Class


assert(iscell( param))
assert(isa(param, 'cell'))

Sets the input parameter param to the MATLAB class cell (cell array). For example, to
set the class of input C to a cell, call:
...
assert(iscell(C));
...

or
...
assert(isa(C, 'cell'));
...

To specify the properties of cell array elements, see “Specifying Properties of Cell Arrays”
on page 21-74.

Specify Fixed Size


assert ( all ( size (param) == [dims ] ) )

Sets the input parameter param to the size that dimensions dims specifies. For example,
to set the size of input U to a 3-by-2 matrix, call:
...
assert(all(size(U)== [3 2]));
...

Specify Scalar Size


assert ( isscalar (param ) )
assert ( all ( size (param) == [ 1 ] ) )

Sets the size of input parameter param to scalar. To set the size of input U to scalar, call:
...
assert(isscalar(U));
...
or
...
assert(all(size(U)== [1]));
...

21-68
Define Input Properties Programmatically in the MATLAB File

Specify Upper Bounds for Variable-Size Inputs


assert ( all(size(param)<=[N0 N1 ...]));
assert ( all(size(param)<[N0 N1 ...]));

Sets the upper-bound size of each dimension of input parameter param. To set the upper-
bound size of input U to be less than or equal to a 3-by-2 matrix, call:
assert(all(size(U)<=[3 2]));

Note: You can also specify upper bounds for variable-size inputs using coder.varsize.

Specify Inputs with Fixed- and Variable-Size Dimensions


assert ( all(size(param)>=[M0 M1 ...]));
assert ( all(size(param)<=[N0 N1 ...]));

When you use assert(all(size(param)>=[M0 M1 ...])) to specify the lower-bound


size of each dimension of an input parameter:

• You must also specify an upper-bound size for each dimension of the input parameter.
• For each dimension, k, the lower-bound Mk must be less than or equal to the upper-
bound Nk.
• To specify a fixed-size dimension, set the lower and upper bound of a dimension to the
same value.
• Bounds must be nonnegative.

To fix the size of the first dimension of input U to 3 and set the second dimension as
variable size with upper bound of 2, call:
assert(all(size(U)>=[3 0]));
assert(all(size(U)<=[3 2]));

Specify Size of Individual Dimensions


assert (size(param, k)==Nk);
assert (size(param, k)<=Nk);
assert (size(param, k)<Nk);

You can specify individual dimensions and all dimensions simultaneously. You can also
specify individual dimensions instead of specifying all dimensions simultaneously. The
following rules apply:

21-69
21 Generating C/C++ Code from MATLAB Code

• You must specify the size of each dimension at least once.


• The last dimension specification takes precedence over earlier specifications.

Sets the upper-bound size of dimension k of input parameter param. To set the upper-
bound size of the first dimension of input U to 3, call:
assert(size(U,1)<=3)

To fix the size of the second dimension of input U to 2, call:


assert(size(U,2)==2)

Specify Real Input


assert ( isreal (param ) )

Specifies that the input parameter param is real. To specify that input U is real, call:
...
assert(isreal(U));
...

Specify Complex Input


assert ( ~isreal (param ) )

Specifies that the input parameter param is complex. To specify that input U is complex,
call:
...
assert(~isreal(U));
...

Specify numerictype of Fixed-Point Input


assert ( isequal ( numerictype ( fiparam ), T ) )

Sets the numerictype properties of fi input parameter fiparam to the numerictype


object T. For example, to specify the numerictype property of fixed-point input U as a
signed numerictype object T with 32-bit word length and 30-bit fraction length, use the
following code:
%#codegen
...
% Define the numerictype object.

21-70
Define Input Properties Programmatically in the MATLAB File

T = numerictype(1, 32, 30);

% Set the numerictype property of input U to T.


assert(isequal(numerictype(U),T));
...

Specifying the numerictype for a variable does not automatically specify that the
variable is fixed point. You must specify both the fi class and the numerictype.

Specify fimath of Fixed-Point Input

assert ( isequal ( fimath ( fiparam ), F ) )

Sets the fimath properties of fi input parameter fiparam to the fimath object F. For
example, to specify the fimath property of fixed-point input U so that it saturates on
integer overflow, use the following code:

%#codegen
...
% Define the fimath object.
F = fimath('OverflowMode','saturate');

% Set the fimath property of input U to F.


assert(isequal(fimath(U),F));
...
If you do not specify the fimath properties using assert, codegen uses the MATLAB
default fimath value.

Specify Multiple Properties of Input

assert ( function1 ( params ) &&


function2 ( params ) &&
function3 ( params ) && ... )

Specifies the class, size, and complexity of one or more inputs using a single assert
function call. For example, the following code specifies that input U is a double, complex,
3-by-3 matrix, and input V is a 16-bit unsigned integer:

%#codegen
...
assert(isa(U,'double') &&
~isreal(U) &&
all(size(U) == [3 3]) &&
isa(V,'uint16'));

21-71
21 Generating C/C++ Code from MATLAB Code

...

Rules for Using assert Function


When using the assert function to specify the properties of primary function inputs,
follow these rules:

• Call assert functions at the beginning of the primary function, before control-flow
operations such as if statements or subroutine calls.
• Do not call assert functions inside conditional constructs, such as if, for, while,
and switch statements.
• For a fixed-point input, you must specify both the fi class and the numerictype. See
“Specify numerictype of Fixed-Point Input” on page 21-70. You can also set the
fimath properties. See “Specify fimath of Fixed-Point Input” on page 21-71. If you
do not set the fimath properties, codegen uses the MATLAB default fimath value.
• If you set the class of an input parameter to struct, you must specify the class, size,
and complexity of all fields in the order that they appear in the structure definition.
• When you use assert(all(size(param)>=[M0 M1 ...])) to specify the lower-
bound size of each dimension of an input parameter:

• You must also specify an upper-bound size for each dimension of the input
parameter.
• For each dimension, k, the lower-bound Mk must be less than or equal to the
upper-bound Nk.
• To specify a fixed-size dimension, set the lower and upper bound of a dimension to
the same value.
• Bounds must be nonnegative.
• If you specify individual dimensions, the following rules apply:

• You must specify the size of each dimension at least once.


• The last dimension specification takes precedence over earlier specifications.

Specifying General Properties of Primary Inputs


In the following code excerpt, a primary MATLAB function mcspecgram takes two
inputs: pennywhistle and win. The code specifies the following properties for these
inputs.

21-72
Define Input Properties Programmatically in the MATLAB File

Input Property Value


pennywhistle class int16
size 220500-by-1 vector
complexity real (by default)
win class double
size 1024-by-1 vector
complexity real (by default)

%#codegen
function y = mcspecgram(pennywhistle,win)
nx = 220500;
nfft = 1024;
assert(isa(pennywhistle,'int16'));
assert(all(size(pennywhistle) == [nx 1]));
assert(isa(win, 'double'));
assert(all(size(win) == [nfft 1]));
...

Alternatively, you can combine property specifications for one or more inputs inside
assert commands:

%#codegen
function y = mcspecgram(pennywhistle,win)
nx = 220500;
nfft = 1024;
assert(isa(pennywhistle,'int16') && all(size(pennywhistle) == [nx 1]));
assert(isa(win, 'double') && all(size(win) == [nfft 1]));
...

Specifying Properties of Primary Fixed-Point Inputs


To specify fixed-point inputs, you must install Fixed-Point Designer software.

In the following example, the primary MATLAB function mcsqrtfi takes one fixed-point
input x. The code specifies the following properties for this input.

Property Value
class fi

21-73
21 Generating C/C++ Code from MATLAB Code

Property Value
numerictype numerictype object T, as specified in the primary
function
fimath fimath object F, as specified in the primary function
size scalar
complexity real (by default)
function y = mcsqrtfi(x) %#codegen
T = numerictype('WordLength',32,'FractionLength',23,...
'Signed',true);
F = fimath('SumMode','SpecifyPrecision',...
'SumWordLength',32,'SumFractionLength',23,...
'ProductMode','SpecifyPrecision',...
'ProductWordLength',32,'ProductFractionLength',23);
assert(isfi(x));
assert(isequal(numerictype(x),T));
assert(isequal(fimath(x),F));

y = sqrt(x);

You must specify both the fi class and the numerictype.

Specifying Properties of Cell Arrays


To specify the MATLAB class cell (cell array), use one of the following syntaxes:
assert(iscell(param))
assert(isa( param, 'cell'))

For example, to set the class of input C to cell, use:


...
assert(iscell(C));
...

or
...
assert(isa(C, 'cell'));
...

You can also specify the size of the cell array and the properties of the cell array
elements. The number of elements that you specify determines whether the cell array is

21-74
Define Input Properties Programmatically in the MATLAB File

homogeneous or heterogeneous. See “Homogeneous vs. Heterogeneous Cell Arrays” on


page 9-2.

If you specify the properties of the first element only, the cell array is homogeneous.
For example, the following code specifies that C is a 1x3 homogeneous cell array whose
elements are 1x1 double.
...
assert(isa(C, 'cell'));
assert(all(size(C) == [1 3]));
assert(isa(C{1}, 'double'));
...

If you specify the properties of the first element only, but also assign a structure
type name to the cell array, the cell array is heterogeneous. Each element has the
properties of the first element. For example, the following code specifies that C is a 1x3
heterogeneous cell array. Each element is a 1x1 double.
...
assert(isa(C, 'cell'));
assert(all(size(C) == [1 3]));
assert(isa(C{1}, 'double'));
coder.cstructname(C, 'myname');
...

If you specify the properties of each element, the cell array is heterogeneous. For
example, the following code specifies a 1x2 heterogeneous cell array whose first element
is 1x1 char and whose second element is 1x3 double.
...
assert(isa(C, 'cell'));
assert(all(size(C) == [1 2]));
assert(isa(C{1}, 'char'));
assert(all(size(C{2}) == [1 3]));
assert(isa(C{2}, 'double'));
...

If you specify more than one element, you cannot specify that the cell array is variable
size, even if all elements have the same properties. For example, the following code
specifies a variable-size cell array. Because the code specifies the properties of the first
and second elements, code generation fails.
...
assert(isa(C, 'cell'));

21-75
21 Generating C/C++ Code from MATLAB Code

assert(all(size(C) <= [1 2]));


assert(isa(C{1}, 'double'));
assert(isa(C{2}, 'double'));
...

In the previous example, if you specify the first element only, you can specify that the cell
array is variable-size. For example:
...
assert(isa(C, 'cell'));
assert(all(size(C) <= [1 2]));
assert(isa(C{1}, 'double'));
...

Specifying Class and Size of Scalar Structure


Suppose that you defineS as the following scalar MATLAB structure:
S = struct('r',double(1),'i',int8(4));
The following code specifies the properties of the function input S and its fields:
function y = fcn(S) %#codegen

% Specify the class of the input as struct.


assert(isstruct(S));

% Specify the class and size of the fields r and i


% in the order in which you defined them.
assert(isa(S.r,'double'));
assert(isa(S.i,'int8');
...

In most cases, when you do not explicitly specify values for properties, MATLAB Coder
uses defaults—except for structure fields. The only way to name a field in a structure
is to set at least one of its properties. At a minimum, you must specify the class of a
structure field.

Specifying Class and Size of Structure Array


For structure arrays, you must choose a representative element of the array for
specifying the properties of each field. For example, assume that you have defined S as
the following 1-by-2 array of MATLAB structures:

21-76
Define Input Properties Programmatically in the MATLAB File

S = struct('r',{double(1), double(2)},'i',{int8(4), int8(5)});

The following code specifies the class and size of each field of structure input S by using
the first element of the array:
%#codegen
function y = fcn(S)

% Specify the class of the input S as struct.


assert(isstruct(S));

% Specify the size of the fields r and i


% based on the first element of the array.
assert(all(size(S) == [1 2]));
assert(isa(S(1).r,'double'));
assert(isa(S(1).i,'int8'));
The only way to name a field in a structure is to set at least one of its properties. At a
minimum, you must specify the class of all fields.

21-77
21 Generating C/C++ Code from MATLAB Code

Speed Up Compilation

Generate Code Only


If you select this option, MATLAB Coder does not invoke the make command or generate
compiled object code. When you want to iterate rapidly between modifying MATLAB code
and generating C/C++ code and you want to inspect the generated code, this option saves
you time.

Using the MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Set Build Type to Static Library, Dynamic Library, or Executable.
3 Select the Generate code only check box.

Alternatively, set Build type to Source Code. This build type is equivalent to Static
Library with the Generate code only box selected.

At the Command Line

Use the codegen -c option to only generate code without invoking the make command.
For example, to generate code only for a function, foo, that takes one single, scalar
input:
codegen -c foo -args {single(0)}
For more information and a complete list of compilation options, see codegen.

21-78
Disable Creation of the Code Generation Report

Disable Creation of the Code Generation Report


If you disable creation of the code generation report, you can speed up code generation,
unless an error occurs. If an error occurs, the code generation software creates a report
even if you disabled creation of the report.

To disable creation of the code generation report:

• In the MATLAB Coder app, in the project build settings, on the Debugging tab, clear
the Always create a code generation report check box.
• At the command line, when you generate code, do not use the -report option. If you
specify a code configuration object, make sure that the GenerateReport property is
set to false.

By default, creation of the code generation report is disabled.

Related Examples
• “Enable Code Generation Reports” on page 22-28

More About
• “Configure Build Settings” on page 21-26
• “Code Generation Reports” on page 22-10

21-79
21 Generating C/C++ Code from MATLAB Code

Paths and File Infrastructure Setup


In this section...
“Compile Path Search Order” on page 21-80
“Specify Folders to Search for Custom Code” on page 21-80
“Naming Conventions” on page 21-81

Compile Path Search Order


MATLAB Coder resolves MATLAB functions by searching first on the code generation
path and then on the MATLAB path. The code generation path contains the current
folder and the code generation libraries. By default, unless MATLAB Coder determines
that a function should be extrinsic or you explicitly declare the function to be extrinsic,
MATLAB Coder tries to compile and generate code for functions it finds on the path.
MATLAB Coder does not compile extrinsic functions, but rather dispatches them to
MATLAB for execution. See “Resolution of Function Calls for Code Generation” on page
14-2.

Specify Folders to Search for Custom Code


If you want to integrate custom code — such as source, header, and library files — with
the generated code, you can specify additional folder to search. The following table
describes how to specify these search paths. The path should not contain:

• Spaces (Spaces can lead to code generation failures in certain operating system
configurations)
• Tabs
• \, $, #, *, ?
• Non-7-bit ASCII characters, such as Japanese characters

To specify additional Do this


folders
Using the MATLAB 1 To open the Generate dialog box, on the Generate Code
Coder app
page, click the Generate arrow .
2 Click More Settings.

21-80
Paths and File Infrastructure Setup

To specify additional Do this


folders
3 On the Paths tab, in the Search paths field, either
browse to add a folder to the search path or enter the full
path. The search path must not contain spaces.
At the command line Use the codegen function -I option.

Naming Conventions
MATLAB Coder enforces naming conventions for MATLAB functions and generated files.

• “Reserved Prefixes” on page 21-81


• “Reserved Keywords” on page 21-81
• “Conventions for Naming Generated Files” on page 21-84

Reserved Prefixes

MATLAB Coder reserves the prefix eml for global C/C++ functions and variables in
generated code. For example, MATLAB for code generation run-time library function
names begin with the prefix emlrt, such as emlrtCallMATLAB. To avoid naming
conflicts, do not name C/C++ functions or primary MATLAB functions with the prefix
eml.

Reserved Keywords

• “C Reserved Keywords” on page 21-82


• “C++ Reserved Keywords” on page 21-82
• “Reserved Keywords for Code Generation” on page 21-82
• “MATLAB Coder Code Replacement Library Keywords” on page 21-83

MATLAB Coder software reserves certain words for its own use as keywords of the
generated code language. MATLAB Coder keywords are reserved for use internal to
MATLAB Coder software and should not be used in MATLAB code as identifiers or
function names. C reserved keywords should also not be used in MATLAB code as
identifiers or function names. If your MATLAB code contains reserved keywords, the
code generation build does not complete and an error message is displayed. To address
this error, modify your code to use identifiers or names that are not reserved.

21-81
21 Generating C/C++ Code from MATLAB Code

If you are generating C++ code using the MATLAB Coder software, in addition, your
MATLAB code must not contain the “C++ Reserved Keywords” on page 21-82.
C Reserved Keywords

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

C++ Reserved Keywords

catch friend protected try


class inline public typeid
const_cast mutable reinterpret_cast typename
delete namespace static_cast using
dynamic_cast new template virtual
explicit operator this wchar_t
export private throw

Reserved Keywords for Code Generation

abs fortran localZCE rtNaN


asm HAVESTDIO localZCSV SeedFileBuffer
bool id_t matrix SeedFileBufferLen
boolean_T int_T MODEL single
byte_T int8_T MT TID01EQ
char_T int16_T NCSTATES time_T

21-82
Paths and File Infrastructure Setup

cint8_T int32_T NULL true


cint16_T int64_T NUMST TRUE
cint32_T INTEGER_CODE pointer_T uint_T
creal_T LINK_DATA_BUFFER_SIZE PROFILING_ENABLED uint8_T
creal32_T LINK_DATA_STREAM PROFILING_NUM_SAMPLES uint16_T
creal64_T localB real_T uint32_T
cuint8_T localC real32_T uint64_T
cuint16_T localDWork real64_T UNUSED_PARAMETER
cuint32_T localP RT USE_RTMODEL
ERT localX RT_MALLOC VCAST_FLUSH_DATA
false localXdis rtInf vector
FALSE localXdot rtMinusInf

MATLAB Coder Code Replacement Library Keywords

The list of code replacement library (CRL) reserved keywords for your development
environment varies depending on which CRLs currently are registered. Beyond the
default ANSI, ISO, and GNU® CRLs provided with MATLAB Coder software, additional
CRLs might be registered and available for use if you have installed other products that
provide CRLs (for example, a target product), or if you have used Embedded Coder APIs
to create and register custom CRLs.

To generate a list of reserved keywords for the CRLs currently registered in your
environment, use the following MATLAB function:
crl_ids = RTW.TargetRegistry.getInstance.getTflReservedIdentifiers()

This function returns an array of CRL keyword strings. Specifying the return argument
is optional.

Note: To list the CRLs currently registered in your environment, use the MATLAB
command crviewer.

To generate a list of reserved keywords for the CRL that you are using to generate code,
call the function passing the name of the CRL as displayed in the Code replacement

21-83
21 Generating C/C++ Code from MATLAB Code

library menu on the Code Generation > Interface pane of the Configuration
Parameters dialog box. For example,
crl_ids = RTW.TargetRegistry.getInstance.getTflReservedIdentifiers('GNU99 (GNU)')

Here is a partial example of the function output:


>> crl_ids = RTW.TargetRegistry.getInstance.getTflReservedIdentifiers('GNU99 (GNU)')

crl_ids =

'exp10'
'exp10f'
'acosf'
'acoshf'
'asinf'
'asinhf'
'atanf'
'atanhf'
...
'rt_lu_cplx'
'rt_lu_cplx_sgl'
'rt_lu_real'
'rt_lu_real_sgl'
'rt_mod_boolean'
'rt_rem_boolean'
'strcpy'
'utAssert'

Note: Some of the returned keyword strings appear with the suffix $N, for example,
'rt_atan2$N'. $N expands into the suffix _snf only if nonfinite numbers are
supported. For example, 'rt_atan2$N' represents 'rt_atan2_snf' if nonfinite
numbers are supported and 'rt_atan2' if nonfinite numbers are not supported. As a
precaution, you should treat both forms of the keyword as reserved.

Conventions for Naming Generated Files

The following table describes how MATLAB Coder names generated files. MATLAB
Coder follows MATLAB conventions by providing platform-specific extensions for MEX
files.

Platform MEX File MATLAB Coder MATLAB Coder MATLAB Coder


Extension Extension for Extension for Executable
Static Library Shared Library Extension
Linux (64-bit) .mexa64 .a .so None

21-84
Paths and File Infrastructure Setup

Platform MEX File MATLAB Coder MATLAB Coder MATLAB Coder


Extension Extension for Extension for Executable
Static Library Shared Library Extension
Apple Mac (64- .mexmaci64 .a .so None
bit)
Windows (64- .mexw64 .lib .dll .exe
bit) Also, generates
an import
library with a
.lib extension
that is required
for linking
against the
.dll.

21-85
21 Generating C/C++ Code from MATLAB Code

Generate Code for Multiple Entry-Point Functions


In this section...
“Advantages of Generating Code for Multiple Entry-Point Functions” on page 21-86
“Generate Code for More Than One Entry-Point Function Using the MATLAB Coder
App” on page 21-86
“Generating Code for More Than One Entry-Point Function at the Command Line” on
page 21-89
“How to Call an Entry-Point Function in a MEX Function” on page 21-90
“How to Call an Entry-Point Function in a C/C++ Library Function from C/C++ Code”
on page 21-91

Advantages of Generating Code for Multiple Entry-Point Functions


Generating a single C/C++ library for more than one entry-point MATLAB function
allows you to:

• Create C/C++ libraries containing multiple, compiled MATLAB files to integrate with
larger C/C++ applications.
• Share code efficiently between library functions.
• Communicate between library functions using shared memory.

Generating a MEX function for more than one entry-point function allows you to validate
entry-point interactions in MATLAB before creating a C/C++ library.

Generate Code for More Than One Entry-Point Function Using the
MATLAB Coder App
This example shows how to generate code for multiple entry-point functions using the
MATLAB Coder app.

Create the Entry-Point Functions

1 In a local writable folder, create a MATLAB file, ep1.m, that contains:

function y = ep1(u) %#codegen


y = u;

21-86
Generate Code for Multiple Entry-Point Functions

2 In the same local writable folder, create a MATLAB file, ep2.m, that contains:
function y = ep2(u, v) %#codegen
y = u + v;

Create the Test File

In the folder that contains ep1.m and ep12.m, create a MATLAB file, ep_test.m, that
calls ep1 and ep2 with example inputs.
function [y, y1] = ep_test
y = ep1(single(2));
y1 = ep2(double(3), double(4));

Open the MATLAB Coder App

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

Specify Source Files

1 On the Select Source Files page, type or select the name of the entry-point
function ep1.

The app creates a project with the default name ep1.prj in the current folder.
2 To add ep2 to the list of entry-point functions, click Add Entry-Point Function.
Type or select the name of the entry-point function ep2.
3 Click Next to go to the Define Input Types step. The app analyzes the functions
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 a test file that MATLAB Coder can use to automatically define types:

1 Enter or select the test file ep_test.m.

21-87
21 Generating C/C++ Code from MATLAB Code

2 Click Autodefine Input Types.

The test file, ep_test.m, calls the entry-point functions ep1 and ep2 with the
example input types. MATLAB Coder infers that for ep1, input u is single(1x1).
For ep2, u and v are 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 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. 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 ep_test, the test file that you used to
define the input types.
2 Click Check for Issues.

The app generates a MEX function named ep1_mex for ep1 and ep2. It runs the
test file ep_test replacing calls to ep1 and ep2 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 MEX Function

1
To open the Generate dialog box, click the Generate arrow .
2 Set Build type to MEX.
3 Verify that the Output file name is ep1_mex. By default, the app uses the name of
the alphabetically first entry-point function.
4 Click Generate.

MATLAB Coder builds the project. It generates a MEX function, ep1_mex, in the
current folder. MATLAB Coder also generates other supporting files in a subfolder
called codegen/mex/ep1_mex. MATLAB Coder uses the name of the MATLAB

21-88
Generate Code for Multiple Entry-Point Functions

function as the root name for the generated files. It creates a platform-specific
extension for the MEX file, as described in “Naming Conventions” on page 21-81.

You can now test your MEX function in MATLAB. See “How to Call an Entry-Point
Function in a MEX Function” on page 21-90.

If you generate a static library for ep1 and ep2, MATLAB Coder builds the project
and generates a C library, ep1, and supporting files in the default folder, codegen/
lib/ep1.

Generating Code for More Than One Entry-Point Function at the


Command Line
To generate code for more than one entry-point function, use the following syntax, where
global_options applies to functions, fun_1 through fun_n, and options_n applies
only to the preceding function fun_n.
codegen -global_options fun_1 -options_1 ... fun_n -options_n

By default, codegen:

• Generates a MEX function in the current folder. codegen names the MEX function,
fun_mex. fun is the name of the alphabetically first entry-point function.

Stores generated files in the subfolder codegen/mex/fun_1. fun_1 is the name of


the first entry-point function.

You can specify the output file name and subfolder name using the -o option.
codegen -o out_fun fun_1 -options_1 ... fun_n -options_n
In this case, codegen:

• Generates a MEX function named out_fun_mex in the current folder.


• Stores generated files in the subfolder codegen/mex/out_fun.

For more information on setting build options at the command line, see codegen.

Generating a MEX Function with Two Entry-Point Functions at the Command Line

Generate a MEX function with two entry-point functions, ep1 and ep2. Function ep1
takes one input, a single scalar, and ep2 takes two inputs, a double scalar and a double
vector. Using the -o option, name the generated MEX function sharedmex.

21-89
21 Generating C/C++ Code from MATLAB Code

codegen -o sharedmex ep1 -args single(0) ep2 -args { 0, zeros(1,1024) }


codegen generates a MEX function named sharedmex.mex in the current folder and
stores generated files in the subfolder codegen/mex/sharedmex.

Generating a C/C++ Static Library with Two Entry-Point Functions at the Command Line

Generate standalone C/C++ code and compile it to a library for two entry-point functions,
ep1 and ep2. Function ep1 takes one input, a single scalar, and ep2 takes two inputs, a
double scalar and a double vector. Use the -config:lib option to specify that the target
is a library. Using the -o option, name the generated library sharedlib.

codegen -config:lib -o sharedlib ep1 -args single(0) ep2 ...


-args { 0, zeros(1,1024) }
codegen generates C/C++ library code in the codegen/lib/sharedlib folder.

For information on viewing entry-point functions in the code generation report, see “Code
Generation Reports” on page 22-10.

How to Call an Entry-Point Function in a MEX Function


To call an entry-point function in a MEX function that has more than one entry point,
use this syntax:

MEX_Function('entry_point_function_name',
... entry_point_function_param1,
... , entry_point_function_paramn)

Calling an Entry-Point Function in a MEX Function

Consider a MEX function, sharedmex, that has entry-point functions ep1 and ep2.
Entry-point function ep1 takes one single scalar input and ep2 takes two inputs, a
double scalar and a double vector.

To call ep1 with an input parameter u, enter:

sharedmex('ep1', u)

To call ep2 with input parameters u and v, enter:

sharedmex('ep2', u, v)

21-90
Generate Code for Multiple Entry-Point Functions

How to Call an Entry-Point Function in a C/C++ Library Function from C/


C++ Code
To call an entry-point function in a C/C++ library function from C/C++ code, write a main
function in C/C++ that:

• Includes the generated header files, which contain the function prototypes for the
entry-point functions.
• Calls the initialize function before calling the entry-point functions for the first time.
• Calls the terminate function after calling the entry-point functions for the last time.
• Configures your target to integrate this custom C/C++ main function with your
generated code, as described in “Specify External File Locations” on page 25-12.
• Generates the C/C++ executable using codegen.

See the example, “Call a C Static Library Function from C Code” on page 25-2.

21-91
21 Generating C/C++ Code from MATLAB Code

Generate Code for Global Data


In this section...
“Workflow” on page 21-92
“Declare Global Variables” on page 21-92
“Define Global Data” on page 21-93
“Synchronizing Global Data with MATLAB” on page 21-94
“Define Constant Global Data” on page 21-98
“Limitations of Using Global Data” on page 21-101

Workflow
To generate C/C++ code from MATLAB code that uses global data:

1 Declare the variables as global in your code.


2 Before using the global data, define and initialize it.

For more information, see “Define Global Data” on page 21-93.


3 Generate code using the MATLAB Coder app or using codegen.

If you use global data, you must also specify whether you want to synchronize this
data between MATLAB and the generated MEX function. For more information, see
“Synchronizing Global Data with MATLAB” on page 21-94.

Declare Global Variables


When using global data, you must first declare the global variables in your MATLAB
code. Consider the use_globals function that uses two global variables AR and B:
function y = use_globals(u)
%#codegen
% Turn off inlining to make
% generated code easier to read
coder.inline('never');
% Declare AR and B as global variables
global AR;
global B;
AR(1) = u + B(1);

21-92
Generate Code for Global Data

y = AR * 2;

Define Global Data


You can define global data in the MATLAB global workspace, in a MATLAB Coder
project, or at the command line. If you do not initialize global data in the project or at the
command line, MATLAB Coder looks for the variable in the MATLAB global workspace.
If the variable does not exist, MATLAB Coder generates an error.

Defining Global Data in the MATLAB Global Workspace

To generate a MEX function for the use_globals function described in “Declare Global
Variables” on page 21-92 using codegen:

1 In the MATLAB workspace, define and initialize the global data. At the MATLAB
prompt, enter:
global AR B;
AR = ones(4);
B=[1 2 3];
2 Generate a MEX file.
codegen use_globals -args {0}
% Use the -args option to specify that the input u
% is a real, scalar, double
% By default, codegen generates a MEX function,
% use_globals_mex, in the current folder

Defining Global Data Using the MATLAB Coder App

1 On the Define Input Types page, for Does this code use global variables?,
select Yes.
2 Under Global variables, enter a name for the global variable.

By default, MATLAB Coder names the first global variable in a project g, and
subsequent global variables g1, g2, etc.
3 Click the field to the right of the global variables name. Specify the type and initial
value of the global variable. See “Specify Global Variable Type and Initial Value
Using the App” on page 18-26.

If you do not specify the type, you must create a variable with the same name in the
global workspace.

21-93
21 Generating C/C++ Code from MATLAB Code

Defining Global Data at the Command Line

To define global data at the command line, use the codegen -globals option. For
example, to compile the use_globals function described in “Declare Global Variables”
on page 21-92, specify two global inputs AR and B at the command line. Use the
-args option to specify that the input u is a real, scalar double. By default, codegen
generates a MEX function, use_globals_mex, in the current folder.

codegen -globals {'AR',ones(4),'B',[1 2 3]} use_globals -args {0}

Alternatively, specify the type and initial value with the -globals flag using the format
-globals {'g', {type, initial_value}}. For cell arrays, you must use this
format. See “Specify Global Cell Arrays at the Command Line” on page 21-102.
Defining Variable-Size Global Data

To provide initial values for variable-size global data, specify the type and initial
value with the -globals flag using the format -globals {'g', {type,
initial_value}}. For example, to specify a global variable g1 that has an initial value
[1 1] and upper bound [2 2], enter:

codegen foo -globals {'g1', {coder.typeof(0, [2 2],1),[1 1]}}


For a detailed explanation of the syntax, see coder.typeof.

Synchronizing Global Data with MATLAB


Why Synchronize Global Data?

The generated MEX function and MATLAB each have their own copies of global data.
To make these copies consistent, you must synchronize their global data whenever the
two interact. If you do not synchronize the data, their global variables might differ. The
level of interaction determines when to synchronize global data. For more information,
see “When to Synchronize Global Data” on page 21-95.

When global data is constant, you cannot synchronize the global data with MATLAB. By
default, the MEX function tests for consistency between the compile-time constant global
values and the MATLAB values at function entry and after extrinsic function calls. If the
MATLAB values differ from the compile-time constant global values, the MEX function
ends with an error. For information about controlling when the MEX function tests for
consistency between the compile-time constant global values and the MATLAB values,
see “Consistency Between MATLAB and Constant Global Data” on page 21-100.

21-94
Generate Code for Global Data

When to Synchronize Global Data

By default, synchronization between the MEX function's global data and MATLAB occurs
at MEX function entry and exit and for extrinsic calls. Use this synchronization method
for maximum consistency between the MEX function and MATLAB.

To improve performance, you can:

• Select to synchronize only at MEX function entry and exit points.


• Disable synchronization when the global data does not interact.
• Choose whether to synchronize before and after each extrinsic call.

The following table summarizes which global data synchronization options to use. To
learn how to set these options, see “How to Synchronize Global Data” on page 21-96.

21-95
21 Generating C/C++ Code from MATLAB Code

Global Data Synchronization Options


If you want to Set the global data Synchronize before and after
synchronization mode extrinsic calls?
to:
Have maximum consistency At MEX-function Yes. Default behavior.
when all extrinsic calls modify entry, exit and
global data. extrinsic calls
(default)
Have maximum consistency At MEX-function Yes. Use the
when most extrinsic calls modify entry, exit and coder.extrinsic -
global data, but a few do not. extrinsic calls sync:off option to turn
(default) off synchronization for the
extrinsic calls that do not
change global data.
Have maximum consistency At MEX-function Yes. Use the
when most extrinsic calls do not entry and exit coder.extrinsic -sync:on
modify global data, but a few do. option to synchronize only the
calls that modify global data.
Maximize performance when At MEX-function No.
synchronizing global data, and entry and exit
none of your extrinsic calls
modify global data.
Communicate between Disabled No.
generated MEX functions
only. No interaction between
MATLAB and MEX function
global data.

How to Synchronize Global Data

To control global data synchronization, set the global data synchronization mode and
select whether to synchronize extrinsic functions. For guidelines on which options to use,
see “When to Synchronize Global Data” on page 21-95.

You can control the global data synchronization mode from the project settings
dialog box, the command line, or a MEX configuration dialog box. You control the
synchronization of data with extrinsic functions using the coder.extrinsic -sync:on
and -sync:off options.

21-96
Generate Code for Global Data

Controlling the Global Data Synchronization Mode Using the MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Set Build type to MEX.
3 Click More Settings.
4 On the Memory tab, set Global data synchronization mode to At MEX-
function entry and exit or Disabled, as applicable.

Controlling the Global Data Synchronization Mode from the Command Line

1 In the MATLAB workspace, define the code generation configuration object. At the
MATLAB command line, enter:
mexcfg = coder.config('mex');
2 At the MATLAB command line, set the GlobalDataSyncMethod property to
SyncAtEntryAndExits or NoSync, as applicable. For example:
mexcfg.GlobalDataSyncMethod = 'SyncAtEntryAndExits';
3 When compiling your code, use the mexcfg configuration object. For example, to
generate a MEX function for function foo that has no inputs:
codegen -config mexcfg foo

Controlling Synchronization for Extrinsic Function Calls

To control whether synchronization between MATLAB and MEX function global data
occurs before and after you call an extrinsic function, use the coder.extrinsic-
sync:on and -sync:off options.

By default, global data is:

• Synchronized before and after each extrinsic call, if the global data synchronization
mode is At MEX-function entry, exit and extrinsic calls. If you are sure
that certain extrinsic calls do not change global data, turn off synchronization for
these calls using the -sync:off option. For example, if functions foo1 and foo2 do
not change global data, turn off synchronization for these functions:
coder.extrinsic('-sync:off', 'foo1', 'foo2');
• Not synchronized, if the global data synchronization mode is At MEX-function
entry and exit. If the code has a few extrinsic calls that change global data,

21-97
21 Generating C/C++ Code from MATLAB Code

turn on synchronization for these calls using the -sync:on option. For example,
if functions foo1 and foo2 change global data, turn on synchronization for these
functions:

coder.extrinsic('-sync:on', 'foo1', 'foo2');


• Not synchronized, if the global data synchronization mode is Disabled. When
synchronization is disabled, you cannot use the -sync:on option to control the
synchronization for specific extrinsic calls.

Define Constant Global Data


If you know that the value of a global variable does not change at run time, you can
reduce overhead in the generated code by specifying that the global variable has a
constant value. You cannot write to the constant global variable.

Define Constant Global Data Using the MATLAB Coder App

1 On the Define Input Types page, for Does this code use global variables?,
select Yes.
2 Under Global Variables, enter a name for the global variable.
3 Click the field to the right of the global variable name.
4 Select Define Constant Value.

21-98
Generate Code for Global Data

5 In the field to the right of the global variable, enter a MATLAB expression.

Define Constant Global Data at the Command-Line Interface

To specify that a global variable is constant using the codegen command, use the -
globals option with the coder.Constant class.

1 Define a configuration object for the code generation output type that you want. For
example, define a configuration object for MEX code generation:

cfg = coder.config('mex');
2 Use coder.Constant to specify that a global variable has a constant value. For
example, the following code specifies that the global variable g has initial value 4
and that global variable gc has the constant value 42.

global_values = {'g', 4, 'gc', coder.Constant(42)};

21-99
21 Generating C/C++ Code from MATLAB Code

3 Generate the code using the -globals option. For example, generate code for
myfunction specifying that the global variables are defined in the cell array
global_values.
codegen -config cfg -globals global_values myfunction

Consistency Between MATLAB and Constant Global Data

By default, the generated MEX function verifies that the values of constant global data
in the MATLAB workspace are consistent with the compile-time values in the generated
MEX. It tests for consistency at function entry and after calls to extrinsic functions.
If the MEX function detects an inconsistency, it ends with an error. To control when
the MEX function tests for consistency, use the global synchronization mode and the
coder.extrinsic synchronization options.

The following table shows how the global data synchronization mode and the
coder.extrinsic synchronization option setting determine when a MEX function
verifies consistency between the compile-time constant global data values and MATLAB.

Global Data GlobalDataSyncMethod (MEX Verify coder.extrinsic Verify


Synchronization Configuration Object) Consistency synchronization Consistency
Mode (Project) of Constant option of Constant
Global Values Global Values
at MEX After Extrinsic
Function Entry Function Call
At MEX- 'SyncAlways' yes 'sync:on' yes
function (default)
entry, exit 'sync:off' no
and extrinsic
calls (default)
At MEX- 'SyncAtEntryAndExits' yes 'sync:on' yes
function 'sync:off' no
entry and (default)
exit
Disabled 'NoSync' no N/A N/A

Constant Global Data in a Code Generation Report

The code generation report provides the following information about a constant global
variable:

21-100
Generate Code for Global Data

• Type of Global on the Variables tab.


• Highlighted variable name in the Function pane.

See “MATLAB Code Variables in a Report” on page 22-18.

Limitations of Using Global Data


You cannot use global data with the coder.cstructname function.

21-101
21 Generating C/C++ Code from MATLAB Code

Specify Global Cell Arrays at the Command Line


To specify global cell array inputs, use the -globals option of the codegen command
with this syntax:

codegen myfunction -globals {global_var, {type_object, initial_value}}

For example:

• To specify that the global variable g is a 1x3 cell array whose elements have class
double and whose initial value is {1 2 3}, use:

codegen myfunction -globals {'g', {coder.typeof({1 1 1}), {1 2 3}}}

Alternatively, use:

t = coder.typeof({1 1 1});
codegen myfunction -globals {'g', {t, {1 2 3}}}

The global variable g is a 1x3 homogeneous cell array whose elements are 1x1 double.

To make g heterogeneous, use:

t = makeHeterogeneous(coder.typeof({1 1 1}));
codegen myfunction -globals {'g', {t, {1 2 3}}}
• To specify that g is a cell array whose first element has type char, whose second
element has type double, and whose initial value is {'a', 1}, use:

codegen myfunction -globals {'g', {coder.typeof({'a', 1}), {'a', 1}}}

The global variable g is a 1x2 heterogeneous cell array whose first element is 1x1 char
and whose second element is 1x1 double.
• To specify that g is a cell array whose first element has type double, whose second
element is a 1x2 double array, and whose initial value is {1 [2 3]}, use:

codegen myfunction -globals {'g', {coder.typeof({1 [2 3]}), {1 [2 3]}}}

Alternatively, use:

t = coder.typeof({1 [2 3]});
codegen myfunction -globals {'g', {t, {1 [2 3]}}}

21-102
Specify Global Cell Arrays at the Command Line

The global variable g is a 1x2 heterogeneous cell array whose first element is 1x1
double and whose second element is 1x2 double.

Global variables that are cell arrays cannot have variable size.

See Also
codegen | coder.typeof

Related Examples
• “Generate Code for Global Data” on page 21-92

21-103
21 Generating C/C++ Code from MATLAB Code

Generate Code for Enumerated Types


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

21-104
Generate Code for Variable-Size Data

Generate Code for Variable-Size Data


In this section...
“Disable Support for Variable-Size Data” on page 21-105
“Control Dynamic Memory Allocation” on page 21-106
“Generating Code for MATLAB Functions with Variable-Size Data” on page 21-108
“Generate Code for a MATLAB Function That Expands a Vector in a Loop” on page
21-109
“Using Dynamic Memory Allocation for an "Atoms" Simulation” on page 21-115

Variable-size data is data whose size might change at run time. You can use MATLAB
Coder to generate C/C++ code from MATLAB code that uses variable-size data. MATLAB
supports bounded and unbounded variable-size data for code generation. 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. By default, for MEX and C/C++
code generation, support for variable-size data is enabled and dynamic memory allocation
is enabled for variable-size arrays whose size is greater than or equal to a configurable
threshold.

Disable Support for Variable-Size Data


By default, for MEX and C/C++ code generation, support for variable-size data is
enabled. You modify variable sizing settings from the project settings dialog box, the
command line, or using dialog boxes.

Using the MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Click More Settings.
3 On the Memory tab, select or clear Enable variable-sizing.

At the Command Line

1 Create a configuration object for code generation. For example, for a library:

21-105
21 Generating C/C++ Code from MATLAB Code

cfg = coder.config('lib');
2 Set the EnableVariableSizing option:

cfg.EnableVariableSizing = false;
3 Using the -config option, pass the configuration object to codegen :

codegen -config cfg foo

Control Dynamic Memory Allocation


By default, dynamic memory allocation is enabled for variable-size arrays whose size is
greater than or equal to a configurable threshold. If you disable support for variable-size
data (see “Disable Support for Variable-Size Data” on page 21-105), you also disable
dynamic memory allocation. You can modify dynamic memory allocation settings from
the project settings dialog box or the command line.

Using the MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Click More Settings.
3 On the Memory tab, set Dynamic memory allocation to one of the following
options:

Setting Action
Never Dynamic memory allocation is disabled.
Variable-size data is allocated statically
on the stack.
For all variable-sized arrays Dynamic memory allocation is enabled
for variable-size arrays. Variable-size
data is allocated dynamically on the
heap.
For arrays with max size at or Dynamic memory allocation is enabled
above threshold for variable-size arrays whose size is
greater than or equal to the Dynamic
memory allocation threshold.
Variable-size arrays whose size is less

21-106
Generate Code for Variable-Size Data

Setting Action
than this threshold are allocated on the
stack.
4 Optionally, if you set Dynamic memory allocation to For arrays with
maximum size at or above threshold, configure Dynamic memory
allocation threshold to fine-tune memory allocation.

At the Command Line

1 Create a configuration object for code generation. For example, for a MEX function:
mexcfg = coder.config('mex');
2 Set the DynamicMemoryAllocation option:

Setting Action
mexcfg.DynamicMemoryAllocation='Off'; Dynamic memory allocation
is disabled. Variable-size data
is allocated statically on the
stack.
mexcfg.DynamicMemoryAllocation='AllVariableSizeArrays'; Dynamic memory allocation
is enabled for variable-size
arrays. Variable-size data is
allocated dynamically on the
heap.
mexcfg.DynamicMemoryAllocation='Threshold'; Dynamic memory allocation
is enabled for variable-
size arrays whose size (in
bytes) is greater than or
equal to the value specified
using the Dynamic memory
allocation threshold
parameter. Variable-size
arrays whose size is less than
this threshold are allocated on
the stack.
3 Optionally, if you set Dynamic memory allocation to ‘Threshold’, configure
Dynamic memory allocation threshold to fine tune memory allocation.
4 Using the -config option, pass the configuration object to codegen:

21-107
21 Generating C/C++ Code from MATLAB Code

codegen -config mexcfg foo

Generating Code for MATLAB Functions with Variable-Size Data


Here is a basic workflow that first generates MEX code for verifying the generated
code and then generates standalone code after you are satisfied with the result of the
prototype.

To work through these steps with a simple example, see “Generate Code for a MATLAB
Function That Expands a Vector in a Loop” on page 21-109

1 In the MATLAB Editor, add the compilation directive %#codegen at the top of your
function.

This directive:

• Indicates that you intend to generate code for the MATLAB algorithm
• Turns on checking in the MATLAB Code Analyzer to detect potential errors
during code generation
2 Address issues detected by the Code Analyzer.

In some cases, the MATLAB Code Analyzer warns you when your code assigns
data a fixed size but later grows the data, such as by assignment or concatenation
in a loop. If that data is supposed to vary in size at run time, you can ignore these
warnings.
3 Generate a MEX function using codegen to verify the generated code. Use the
following command-line options:

• -args {coder.typeof...} if you have variable-size inputs


• -report to generate a code generation report

For example:

codegen -report foo -args {coder.typeof(0,[2 4],1)}


This command uses coder.typeof to specify one variable-size input for function
foo. The first argument, 0, indicates the input data type (double) and complexity
(real). The second argument, [2 4], indicates the size, a matrix with two
dimensions. The third argument, 1, indicates that the input is variable sized. The
upper bound is 2 for the first dimension and 4 for the second dimension.

21-108
Generate Code for Variable-Size Data

Note: During compilation, codegen detects variables and structure fields that
change size after you define them, and reports these occurrences as errors. In
addition, codegen performs a run-time check to generate errors when data exceeds
upper bounds.
4 Fix size mismatch errors:

Cause How To Fix For More Information


You try to change the Declare the data to be See “Diagnosing and Fixing
size of data after its size variable sized. Size Mismatch Errors” on
has been locked. page 7-22.
5 Fix upper bounds errors

Cause How To Fix For More Information


MATLAB cannot Specify an upper bound. See “Specifying Upper
determine or compute Bounds for Variable-Size
the upper bound Data” on page 7-6 and
“Diagnosing and Fixing Size
Mismatch Errors” on page
7-22.
MATLAB attempts to If the data is unbounded, See “Control Dynamic
compute an upper bound enable dynamic memory Memory Allocation” on page
for unbounded variable- allocation. 21-106.
size data.
6 Generate C/C++ code using the codegen function.

Generate Code for a MATLAB Function That Expands a Vector in a Loop


• “About the MATLAB Function myuniquetol” on page 21-110
• “Step 1: Add Compilation Directive for Code Generation” on page 21-110
• “Step 2: Address Issues Detected by the Code Analyzer” on page 21-110
• “Step 3: Generate MEX Code” on page 21-111
• “Step 4: Generate C Code” on page 21-112
• “Step 5: Specify an Upper Bound for the Output Vector” on page 21-113
• “Step 6: Change the Dynamic Memory Allocation Threshold” on page 21-114

21-109
21 Generating C/C++ Code from MATLAB Code

About the MATLAB Function myuniquetol

This example uses the function myuniquetol. This function returns in vector B a version
of input vector A, where the elements are unique to within tolerance tol of each other. In
vector B, abs(B(i) - B(j)) > tol for all i and j. Initially, assume input vector A can store
up to 100 elements.

function B = myuniquetol(A, tol)


A = sort(A);
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

Step 1: Add Compilation Directive for Code Generation

Add the %#codegen compilation directive at the top of the function:

function B = myuniquetol(A, tol) %#codegen


A = sort(A);
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

Step 2: Address Issues Detected by the Code Analyzer

The Code Analyzer detects that variable B might change size in the for-loop. It issues
this warning:

The variable 'B' appears to change size on every loop iteration.


Consider preallocating for speed.

In this function, you expect vector B to expand in size because it adds values from vector
A. Therefore, you can ignore this warning.

21-110
Generate Code for Variable-Size Data

Step 3: Generate MEX Code

It is a best practice to generate MEX code before you generate C/C++ code. Generating
MEX code can identify code generation issues that are harder to detect at run time.

1 Generate a MEX function for myuniquetol:

codegen -report myuniquetol -args {coder.typeof(0,[1 100],1),coder.typeof(0)}

What do these command-line options mean?

The -args option specifies the class, complexity, and size of each input to function
myuniquetol:

• The first argument, coder.typeof, defines a variable-size input. The expression


coder.typeof(0,[1 100],1) defines input A as a real double vector with a
fixed upper bound. Its first dimension is fixed at 1 and its second dimension can
vary in size up to 100 elements.

For more information, see “Specify Variable-Size Inputs at the Command Line”
on page 21-53.
• The second argument, coder.typeof(0), defines input tol as a real double
scalar.

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


regardless of whether errors or warnings occur.

For more information, see the codegen reference page.

Code generation is successful. codegen does not detect issues. In the current folder,
codegen generates a MEX function for myuniquetol and provides a link to the code
generation report.
2 Click the View report link.
3 In the code generation report, select the Variables tab.

21-111
21 Generating C/C++ Code from MATLAB Code

The size of A is 1x:100 because you specified that A is variable size with an upper
bound of 100. The size of variable B is 1x:?, indicating that it is variable size with
no upper bounds.

Step 4: Generate C Code

Generate C code for variable-size inputs. By default, codegen allocates memory


statically for data whose size is less than the dynamic memory allocation threshold of 64
kilobytes. If the size of the data is greater than or equal to the threshold or is unbounded,
codegen allocates memory dynamically on the heap.

1 Create a configuration option for C library generation:


cfg=coder.config('lib');
2 Issue this command:

21-112
Generate Code for Variable-Size Data

codegen -config cfg -report myuniquetol -args {coder.typeof(0,[1 100],1),coder.typeof(0)}

codegen generates a static library in the default location, codegen\lib


\myuniquetol and provides a link to the code generation report.
3 Click the View report link.
4 In the code generation report, click the C code tab.
5 On the C code tab, click the link to myuniquetol.h.

The function declaration is:

extern void myuniquetol(const double A_data[], const int A_size[2],...


double tol,emxArray_real_T *B);

codegen computes the size of A and, because its maximum size is less than the
default dynamic memory allocation threshold of 64k bytes, allocates this memory
statically. The generated code contains:

• double A_data[]: the definition of A.


• int A_size[2]: the actual size of the input.

The code generation software determines that B is variable size with unknown upper
bounds. It represents B as emxArray_real_T. MATLAB provides utility functions
for creating and interacting with emxArrays in your generated code. For more
information, see “C Code Interface for Arrays” on page 7-17.

Step 5: Specify an Upper Bound for the Output Vector

You specified that the input A is variable size with an upper bound of 100. Therefore, you
know that the output B cannot be larger than 100 elements.

• Use coder.varsize to indicate that B is variable size with an upper bound of 100.

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

21-113
21 Generating C/C++ Code from MATLAB Code

B = [B A(i)];
k = i;
end
end
• Generate code.

codegen -config cfg -report myuniquetol -args {coder.typeof(0,[1 100],1),coder.typeof(0)}

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]);

The code generation software statically allocates the memory for B. It stores the size
of B in int B_size[2].

Step 6: Change the Dynamic Memory Allocation Threshold

In this step, you reduce the dynamic memory allocation threshold and generate code for
an input that exceeds this threshold. This step specifies that the second dimension of A
has an upper bound of 10000.

1 Change the upper bound of B to match the upper bound of A.


function B = myuniquetol(A, tol) %#codegen
A = sort(A);
coder.varsize('B', [1 10000], [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
2 Set the dynamic memory allocation threshold to 4 kilobytes and generate code where
the size of input A exceeds this threshold.

cfg.DynamicMemoryAllocationThreshold=4096;
codegen -config cfg -report myuniquetol -args {coder.typeof(0,[1 10000],1),coder.typeof(0)}
3 View the generated code in the report. Because the maximum size of A and
B now exceed the dynamic memory allocation threshold, codegen allocates

21-114
Generate Code for Variable-Size Data

A and B dynamically on the heap. In the generated code, A and B have type
emxArray_real_T.

extern void myuniquetol(const emxArray_real_T *A, ...


double tol, emxArray_real_T *B);

Using Dynamic Memory Allocation for an "Atoms" Simulation


This example shows how to generate code for a MATLAB algorithm that runs a
simulation of bouncing "atoms" and returns the result after a number of iterations. There
are no upper bounds on the number of atoms that the algorithm accepts, so this example
takes advantage of dynamic memory allocation.

Prerequisites

There are no prerequisites for this example.

Create a New Folder and Copy Relevant Files

The following code will create a folder in your current working folder (pwd). The new
folder will contain only the files that are relevant for this example. If you do not want
to affect the current folder (or if you cannot generate files in this folder), change your
working folder.

Run Command: Create a New Folder and Copy Relevant Files

coderdemo_setup('coderdemo_atoms');

About the 'run_atoms' Function

The run_atoms.m function runs a simulation of bouncing atoms (also applying gravity
and energy loss).

help run_atoms

atoms = run_atoms(atoms,n)
atoms = run_atoms(atoms,n,iter)
Where 'atoms' the initial and final state of atoms (can be empty)
'n' is the number of atoms to simulate.
'iter' is the number of iterations for the simulation
(if omitted it is defaulted to 3000 iterations.)

21-115
21 Generating C/C++ Code from MATLAB Code

Set Up Code Generation Options

Create a code generation configuration object


cfg = coder.config;
% Enable dynamic memory allocation for variable size matrices.
cfg.DynamicMemoryAllocation = 'AllVariableSizeArrays';

Set Up Example Inputs

Create a template structure 'Atom' to provide the compiler with the necessary
information about input parameter types. An atom is a structure with four fields
(x,y,vx,vy) specifying position and velocity in Cartesian coordinates.
atom = struct('x', 0, 'y', 0, 'vx', 0, 'vy', 0);

Generate a MEX Function for Testing

Use the command 'codegen' with the following arguments:

'-args {coder.typeof(atom, [1 Inf]),0,0}' indicates that the first argument is a row vector
of atoms where the number of columns is potentially infinite. The second and third
arguments are scalar double values.

'-config cfg' enables dynamic memory allocation, defined by workspace variable cfg
codegen run_atoms -args {coder.typeof(atom, [1 Inf]),0,0} -config cfg -o run_atoms_mex

Run the MEX Function

The MEX function simulates 10000 atoms in approximately 1000 iteration steps given
an empty list of atoms. The return value is the state of all the atoms after simulation is
complete.
atoms = repmat(atom,1,0);
atoms = run_atoms_mex(atoms,10000,1000)

Iteration: 50
Iteration: 100
Iteration: 150
Iteration: 200
Iteration: 250
Iteration: 300
Iteration: 350
Iteration: 400

21-116
Generate Code for Variable-Size Data

Iteration: 450
Iteration: 500
Iteration: 550
Iteration: 600
Iteration: 650
Iteration: 700
Iteration: 750
Iteration: 800
Iteration: 850
Iteration: 900
Iteration: 950
Iteration: 1000
Completed iterations: 1000

atoms =

1x10000 struct array with fields:

x
y
vx
vy

Run the MEX Function Again

Continue the simulation with another 500 iteration steps

atoms = run_atoms_mex(atoms,10000,500)

Iteration: 50
Iteration: 100
Iteration: 150
Iteration: 200
Iteration: 250
Iteration: 300
Iteration: 350
Iteration: 400
Iteration: 450
Iteration: 500
Completed iterations: 500

atoms =

1x10000 struct array with fields:

21-117
21 Generating C/C++ Code from MATLAB Code

x
y
vx
vy

Generate a Standalone C Code Library

To generate a C library, create a standard configuration object for libraries:


cfg = coder.config('lib');

Enable dynamic memory allocation


cfg.DynamicMemoryAllocation = 'AllVariableSizeArrays';

In MATLAB the default data type is double. However, integers are usually used in
C code, so pass int32 integer example values to represent the number of atoms and
iterations.
codegen run_atoms -args {coder.typeof(atom, [1 Inf]),int32(0),int32(0)} -config cfg

Inspect Generated Code

When creating a library the code is generated in the folder codegen/lib/run_atoms/ The
code in this folder is self contained. To interface with the compiled C code you need only
the generated header files and the library file.
dir codegen/lib/run_atoms

. rt_nonfinite.h run_atoms_emxutil.obj
.. rt_nonfinite.obj run_atoms_initialize.c
buildInfo.mat rtw_proj.tmw run_atoms_initialize.h
codeInfo.mat rtwtypes.h run_atoms_initialize.obj
examples run_atoms.c run_atoms_ref.rsp
interface run_atoms.h run_atoms_rtw.bat
rtGetInf.c run_atoms.lib run_atoms_rtw.mk
rtGetInf.h run_atoms.obj run_atoms_terminate.c
rtGetInf.obj run_atoms_emxAPI.c run_atoms_terminate.h
rtGetNaN.c run_atoms_emxAPI.h run_atoms_terminate.obj
rtGetNaN.h run_atoms_emxAPI.obj run_atoms_types.h
rtGetNaN.obj run_atoms_emxutil.c
rt_nonfinite.c run_atoms_emxutil.h

21-118
Generate Code for Variable-Size Data

Write a C Main Function

Typically, the main function is platform-dependent code that performs rendering


or some other processing. In this example, a pure ANSI-C function produces a file
'run_atoms_state.m' which (when run) contains the final state of the atom simulation.
type run_atoms_main.c

/* Include standard C libraries */


#include <stdio.h>

/* The interface to the main function we compiled. */


#include "codegen/lib/run_atoms/run_atoms.h"

/* The interface to EMX data structures. */


#include "codegen/lib/run_atoms/run_atoms_emxAPI.h"

int main(int argc, char **argv)


{
int i;
emxArray_Atom *atoms;

/* Main arguments unused */


(void) argc;
(void) argv;

/* Initially create an empty row vector of atoms (1 row, 0 columns) */


atoms = emxCreate_Atom(1, 0);

/* Call the function to simulate 10000 atoms in 1000 iteration steps */


run_atoms(atoms, 10000, 1000);

/* Call the function again to do another 500 iteration steps */


run_atoms(atoms, 10000, 500);

/* Print the result to standard output */


for (i = 0; i < atoms->size[1]; i++) {
printf("%f %f %f %f\n",
atoms->data[i].x, atoms->data[i].y, atoms->data[i].vx, atoms->data[i].vy);
}

/* Free memory */
emxDestroyArray_Atom(atoms);
return(0);

21-119
21 Generating C/C++ Code from MATLAB Code

Create a Configuration Object for Executables


cfg = coder.config('exe');
cfg.DynamicMemoryAllocation = 'AllVariableSizeArrays';

Generate a Standalone Executable

You must pass the function (run_atoms.m) as well as custom C code (run_atoms_main.c)
The 'codegen' command automatically generates C code from the MATLAB code,
then calls the C compiler to bundle this generated code with the custom C code
(run_atoms_main.c).
codegen run_atoms run_atoms_main.c -args {coder.typeof(atom, [1 Inf]),int32(0),int32(0)

Run the Executable

After simulation is complete, this produces the file 'atoms_state.mat'. The MAT file is
a 10000x4 matrix, where each row is the position and velocity of an atom (x, y, vx, vy)
representing the current state of the whole system.
[~,atoms_data] = system(['.' filesep 'run_atoms']);
fh = fopen('atoms_state.mat', 'w');
fprintf(fh, '%s', atoms_data);
fclose(fh);

Fetch the State

Running the executable produced 'atoms_state.mat'. Now, recreate the structure array
from the saved matrix
load atoms_state.mat -ascii
clear atoms
for i = 1:size(atoms_state,1)
atoms(1,i).x = atoms_state(i,1);
atoms(1,i).y = atoms_state(i,2);
atoms(1,i).vx = atoms_state(i,3);
atoms(1,i).vy = atoms_state(i,4);
end

Render the State

Call 'run_atoms_mex' with zero iterations to render only


run_atoms_mex(atoms, 10000, 0);

21-120
Generate Code for Variable-Size Data

Clean Up

Remove files and return to original folder

Run Command: Cleanup


if ispc
delete run_atoms.exe

21-121
21 Generating C/C++ Code from MATLAB Code

else
delete run_atoms
end
delete atoms_state.mat
cleanup

21-122
Code Generation for MATLAB Classes

Code Generation for MATLAB Classes


You can generate code for MATLAB value and handle classes and user-defined System
objects that inherit from a handle class. For more information, see “MATLAB Classes”.

21-123
21 Generating C/C++ Code from MATLAB Code

How MATLAB Coder Partitions Generated Code


In this section...
“Partitioning Generated Files” on page 21-124
“How to Select the File Partitioning Method” on page 21-124
“Partitioning Generated Files with One C/C++ File Per MATLAB File” on page 21-125
“Generated Files and Locations” on page 21-130
“File Partitioning and Inlining” on page 21-132

Partitioning Generated Files


By default, during code generation, MATLAB Coder partitions the code to match your
MATLAB file structure. This one-to-one mapping lets you easily correlate your files
generated in C/C++ with the compiled MATLAB code. MATLAB Coder cannot produce
the same one-to-one correspondence for MATLAB functions that are inlined in generated
code (see “File Partitioning and Inlining” on page 21-132).

Alternatively, you can select to generate all C/C++ functions into a single file. For more
information, see “How to Select the File Partitioning Method” on page 21-124. This
option facilitates integrating your code with existing embedded software.

How to Select the File Partitioning Method


Using the MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Click More Settings.
3 On the Code Appearance tab, set the Generated file partitioning method to
Generate one file for each MATLAB file or Generate all functions
into a single file.

At the Command Line

Use the codegen configuration object FilePartitionMethod option. For example,


to compile the function foo that has no inputs and generate one C/C++ file for each
MATLAB function:

21-124
How MATLAB Coder Partitions Generated Code

1 Create a MEX configuration object and set the FilePartitionMethod option:

mexcfg = coder.config('mex');
mexcfg.FilePartitionMethod = 'MapMFileToCFile';
2 Using the -config option, pass the configuration object to codegen:

codegen -config mexcfg -O disable:inline foo


% Disable inlining to generate one C/C++ file for each MATLAB function

Partitioning Generated Files with One C/C++ File Per MATLAB File
By default, for MATLAB functions that are not inlined, MATLAB Coder generates one C/
C++ file for each MATLAB file. In this case, MATLAB Coder partitions generated C/C++
code so that it corresponds to your MATLAB files.

How MATLAB Coder Partitions Entry-Point MATLAB Functions

For each entry-point (top-level) MATLAB function, MATLAB Coder generates one C/C++
source, header, and object file with the same name as the MATLAB file.

For example, suppose you define a simple function foo that calls the function identity.
The source file foo.m contains the following code:

function y = foo(u,v) %#codegen


s = single(u);
d = double(v);
y = double(identity(s)) + identity(d);

Here is the code for identity.m :

function y = identity(u) %#codegen


y = u;

In the MATLAB Coder app, to generate a C static library for foo.m:

1 Define the inputs u and v. For more information, see “Specify Properties of Entry-
Point Function Inputs Using the App” on page 18-3.
2 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
3 Set the Build type to Static Library

21-125
21 Generating C/C++ Code from MATLAB Code

4 Click More Settings.


5 On the All Settings tab, under Function Inlining, set the Inline threshold
parameter to 0
6 Click Close
7 To generate the library, click Generate.

To generate a C static library for foo.m, at the command line, enter:

codegen -config:lib -O disable:inline foo -args {0, 0}


% Use the -args option to specify that u and v are both
% real, scalar doubles

MATLAB Coder generates source, header, and object files for foo and identity in your
output folder.

21-126
How MATLAB Coder Partitions Generated Code

How MATLAB Coder Partitions Local Functions

For each local function, MATLAB Coder generates code in the same C/C++ file as the
calling function. For example, suppose you define a function foo that calls a local
function identity:

function y = foo(u,v) %#codegen


s = single(u);
d = double(v);
y = double(identity(s)) + identity(d);

function y = identity(u)
y = u;

To generate a C++ library, before generating code, select a C++ compiler and set C++ as
your target language. For example, at the command line:

1 Select C++ as your target language:

cfg = coder.config('lib')
cfg.TargetLang='C++'
2 Generate the C++ library:

codegen -config cfg foo -args {0, 0}


% Use the -args option to specify that u and v are both
% real, scalar doubles

In the primary function foo, MATLAB Coder inlines the code for the identity local
function.

21-127
21 Generating C/C++ Code from MATLAB Code

Note: If you specify C++, MATLAB Coder wraps the C code into .cpp files so that
you can use a C++ compiler and interface with external C++ applications. It does not
generate C++ classes.

Here is an excerpt of the generated code in foo.cpp:

...
/* Function Definitions */
double foo(double u, double v)
{
return (double)(float)u + v;
}
...

How MATLAB Coder Partitions Overloaded Functions

An overloaded function is a function that has multiple implementations to accommodate


different classes of input. For each implementation (that is not inlined), MATLAB Coder
generates a separate C/C++ file with a unique numeric suffix.

21-128
How MATLAB Coder Partitions Generated Code

For example, suppose you define a simple function multiply_defined:

%#codegen
function y = multiply_defined(u)

y = u+1;

You then add two more implementations of multiply_defined, one to handle inputs
of type single (in an @single subfolder) and another for inputs of type double (in an
@double subfolder).

To call each implementation, define the function call_multiply_defined:

%#codegen
function [y1,y2,y3] = call_multiply_defined

y1 = multiply_defined(int32(2));
y2 = multiply_defined(2);
y3 = multiply_defined(single(2));

Next, generate C code for the overloaded function multiply_defined. For example, at
the MATLAB command line, enter:

codegen -O disable:inline -config:lib call_multiply_defined

MATLAB Coder generates C source, header, and object files for each implementation of
multiply_defined, as highlighted. Use numeric suffixes to create unique file names.

21-129
21 Generating C/C++ Code from MATLAB Code

Generated Files and Locations


The types and locations of generated files depend on the target that you specify. For
all targets, if errors or warnings occur during build or if you explicitly request a report,
MATLAB Coder generates reports.

Each time MATLAB Coder generates the same type of output for the same code or
project, it removes the files from the previous build. If you want to preserve files from a
build, copy them to a different location before starting another build.

21-130
How MATLAB Coder Partitions Generated Code

Generated Files for MEX Targets

By default, MATLAB Coder generates the following files for MEX function (mex) targets.

Type of Files Location


Platform-specific MEX files Current folder
MEX, and C/C++ source, header, and codegen/mex/function_name
object files
HTML reports codegen/mex/function_name/html

Generated Files for C/C++ Static Library Targets

By default, MATLAB Coder generates the following files for C/C++ static library targets.

Type of Files Location


C/C++ source, library, header, and codegen/lib/function_name
object files
HTML reports codegen/lib/function_name/html

Generated Files for C/C++ Dynamic Library Targets

By default, MATLAB Coder generates the following files for C/C++ dynamic library
targets.

Type of Files Location


C/C++ source, library, header, and codegen/dll/function_name
object files
HTML reports codegen/dll/function_name/html

Generated Files for C/C++ Executable Targets

By default, MATLAB Coder generates the following files for C/C++ executable targets.

Type of Files Location


C/C++ source, header, and object codegen/exe/function_name
files

21-131
21 Generating C/C++ Code from MATLAB Code

Type of Files Location


HTML reports codegen/exe/function_name/html

Changing Names and Locations of Generated Files


Using the MATLAB Coder App

To change Action
The output file name 1 To open the Generate dialog box, on the Generate Code
page, click the Generate arrow .
2 In the Output file name field, enter the file name.
The output file location 1 To open the Generate dialog box, on the Generate Code
page, click the Generate arrow .
2 Click More Settings.
3 On the Paths tab, set Build folder to Specified
folder.
4 For the Build folder name field, either browse to the
output file location or enter the full path. The output file
location must not contain:

• Spaces (Spaces can lead to code generation failures in


certain operating system configurations).
• Tabs
• \, $, #, *, ?
• Non-7-bit ASCII characters, such as Japanese
characters.

At the Command Line

You can change the name and location of generated files by using the codegen options -
o and -d.

File Partitioning and Inlining


How MATLAB Coder partitions generated C/C++ code depends on whether you choose
to generate one C/C++ file for each MATLAB file and whether you inline your MATLAB
functions.

21-132
How MATLAB Coder Partitions Generated Code

If you MATLAB Coder


Generate all C/C++ Generates a single C/C++ file without inlining functions.
functions into a single file
and disable inlining
Generate all C/C++ Generates a single C/C++ file. Inlines functions whose
functions into a single file sizes fall within the inlining threshold.
and enable inlining
Generate one C/C++ file Partitions generated C/C++ code to match MATLAB file
for each MATLAB file and structure. See “Partitioning Generated Files with One C/C
disable inlining ++ File Per MATLAB File” on page 21-125.
Generate one C/C++ file Places inlined functions in the same C/C++ file as the
for each MATLAB file and function into which they are inlined.
enable inlining
Even when you enable inlining, MATLAB Coder inlines
only those functions whose sizes fall within the inlining
threshold. For MATLAB functions that are not inlined,
MATLAB Coder partitions the generated C/C++ code, as
described.

21-133
21 Generating C/C++ Code from MATLAB Code

Tradeoffs Between File Partitioning and Inlining

Weighing file partitioning against inlining represents a trade-off between readability,


efficiency, and ease of integrating your MATLAB code with existing embedded software.

If You Generate Generated C/C++ Advantages Disadvantages


Code
All C/C++ functions Does not match Easier to integrate Difficult to map C/
into a single file MATLAB file with existing C++ code to original
structure embedded software MATLAB file
One C/C++-file for Does not exactly Program executes Difficult to map C/
each MATLAB file match MATLAB file faster C++ code to original
and enable inlining structure MATLAB file
One C/C++-file for Matches MATLAB Easy to map C/C+ Program runs less
each MATLAB file file structure + code to original efficiently
and disable inlining MATLAB file

How Disabling Inlining Affects File Partitioning

Inlining is enabled by default. Therefore, to generate one C/C++ file for each top-level
MATLAB function, you must:

• Select to generate one C/C++ file for each top-level MATLAB function. For more
information, see “How to Select the File Partitioning Method” on page 21-124.
• Explicitly disable inlining, either globally or for individual MATLAB functions.

How to Disable Inlining Globally Using the MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Click More Settings.
3 On the All Settings tab, under Function Inlining set the Inline threshold to 0.

How to Disable Inlining Globally at the Command Line

To disable inlining of functions, use the -O disable:inline option with codegen. For
example, to disable inlining and generate a MEX function for a function foo that has no
inputs:
codegen -O disable:inline foo

21-134
How MATLAB Coder Partitions Generated Code

For more information, see the description of codegen.


How to Disable Inlining for Individual Functions

To disable inlining for an individual MATLAB function, add the directive


coder.inline('never'); on a separate line in the source MATLAB file, after the
function signature.
function y = foo(u,v) %#codegen
coder.inline('never');
s = single(u);
d = double(v);
y = double(identity(s)) + identity(d);

codegen does not inline entry-point functions.

The coder.inline directive applies only to the function in which it appears. In this
example, inlining is disabled for function foo, but not for identity, a top-level function
defined in a separate MATLAB file and called by foo. To disable inlining for identity,
add this directive after its function signature in the source file identity.m. For more
information, see coder.inline.

For a more efficient way to disable inlining for both functions, see “How to Disable
Inlining Globally at the Command Line” on page 21-134.

Correlating C/C++ Code with Inlined Functions

To correlate the C/C++ code that you generate with the original inlined functions, add
comments in the MATLAB code to identify the function. These comments will appear
in the C/C++ code and help you map the generated code back to the original MATLAB
functions.

Modifying the Inlining Threshold

To change inlining behavior, adjust the inlining threshold parameter.


Modifying the Inlining Threshold Using the MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Click More Settings.
3 On the All Settings tab, under Function Inlining, set the value of the Inline
threshold parameter.

21-135
21 Generating C/C++ Code from MATLAB Code

Modifying the Inlining Threshold at the Command Line

Set the value of the InlineThreshold parameter of the configuration object. See
coder.MexCodeConfig, coder.CodeConfig, coder.EmbeddedCodeConfig.

21-136
Requirements for Signed Integer Representation

Requirements for Signed Integer Representation


You must compile the code that is generated by the MATLAB Coder software on a target
that uses a two’s complement representation for signed integer values. The generated
code does not verify that the target uses a two’s complement representation for signed
integer values.

21-137
21 Generating C/C++ Code from MATLAB Code

Customize the Post-Code-Generation Build Process


For certain applications, you might want to control aspects of the build process that
occur after code generation but before compilation. For example, you might want to
specify compiler or linker options. You can customize build processing that occurs after
code generation using MATLAB Coder for MEX functions, C/C++ libraries and C/C++
executables.

You can customize your build using:

• The coder.updateBuildInfo function in your MATLAB code


• A post-code-generation command

In this section...
“Customize Build Using coder.updateBuildInfo” on page 21-138
“Customize Build Using Post-Code-Generation Command” on page 21-138
“Build Information Object” on page 21-139
“Build Information Methods” on page 21-139
“Write Post-Code-Generation Command” on page 21-173
“Use Post-Code-Generation Command to Customize Build” on page 21-174
“Write and Use Post-Code-Generation Command at the Command Line” on page
21-175

Customize Build Using coder.updateBuildInfo


To customize the post-code-generation build from your MATLAB code:

1 In your MATLAB code, call coder.updateBuildInfo to update the build


information object. You specify a build information object method and the input
arguments for the method. See coder.updateBuildInfo and “Build Information
Methods” on page 21-139.
2 Generate code from your MATLAB code using the codegen command or from the
project interface.

Customize Build Using Post-Code-Generation Command


To customize your build using the post-code-generation command:

21-138
Customize the Post-Code-Generation Build Process

1 “Write Post-Code-Generation Command” on page 21-173. Typically, you use this


command to get the project name and build information or to add data to the build
information object.
2 “Use Post-Code-Generation Command to Customize Build” on page 21-174.

Build Information Object


At the start of a build, the MATLAB Coder build process logs the following project, build
option, and dependency information to a build information object, RTW.BuildInfo:

• Compiler options
• Preprocessor identifier definitions
• Linker options
• Source files and paths
• Include files and paths
• Precompiled external libraries

Use the “Build Information Methods” on page 21-139 to access this information in
the build information object. “Write Post-Code-Generation Command” on page 21-173
explains how to use the functions to control a post-code-generation build.

When code generation is complete, MATLAB Coder creates a buildInfo.mat file in the
build folder.

Build Information Methods


Use these methods to access or write data to the build information object. The syntax is:
buildInfo.method_name(input_arg1, ..., input_argn)

addCompileFlags

• Purpose: Add compiler options to build information.


• Syntax: addCompileFlags(buildinfo, options, groups)

groups is optional.
• Arguments:

buildinfo

21-139
21 Generating C/C++ Code from MATLAB Code

Build information stored in RTW.BuildInfo.


options
A character array or cell array of character arrays that specifies the compiler
options to be added to the build information. The function adds each option to
the end of a compiler option vector. If you specify multiple options within a single
character array, for example '-Zi -Wall', the function adds the string to the
vector as a single element. For example, if you add '-Zi -Wall' and then '-
O3', the vector consists of two elements, as shown below.

'-Zi -Wall' '-O3'


groups (optional)
A character array or cell array of character arrays that groups specified compiler
options. You can use groups to

• Document the use of specific compiler options


• Retrieve or apply collections of compiler options

You can apply

• A single group name to one or more compiler options


• Multiple group names to collections of compiler options (available for
nonmakefile build environments only)

To... Specify groups as a...


Apply one group name to Character array.
compiler options
Apply different group Cell array of character arrays such that the number
names to compiler options of group names matches the number of elements you
specify for options.
• Description:

The addCompileFlags function adds specified compiler options to the project's build
information. MATLAB Coder stores the compiler options in a vector. The function
adds options to the end of the vector based on the order in which you specify them.

In addition to the required buildinfo and options arguments, you can use an
optional groups argument to group your options.

21-140
Customize the Post-Code-Generation Build Process

addDefines

• Purpose: Add preprocessor macro definitions to build information.


• Syntax: addDefines(buildinfo, macrodefs, groups)

groups is optional.
• Arguments:

buildinfo
Build information stored in RTW.BuildInfo.
macrodefs
A character array or cell array of character arrays that specifies the preprocessor
macro definitions to be added to the object. The function adds each definition
to the end of a compiler option vector. If you specify multiple definitions within
a single character array, for example '-DRT -DDEBUG', the function adds the
string to the vector as a single element. For example, if you add '-DPROTO -
DDEBUG' and then '-DPRODUCTION', the vector consists of two elements, as
shown below.

'-DPROTO -DDEBUG' '-DPRODUCTION'


groups (optional)
A character array or cell array of character arrays that groups specified
definitions. You can use groups to

• Document the use of specific macro definitions


• Retrieve or apply groups of macro definitions

You can apply

• A single group name to one or more macro definitions


• Multiple group names to collections of macro definitions (available for
nonmakefile build environments only)

To... Specify groups as a...


Apply one group name to Character array.
macro definitions

21-141
21 Generating C/C++ Code from MATLAB Code

To... Specify groups as a...


Apply different group Cell array of character arrays such that the number
names to macro definitions of group names matches the number elements you
specify for macrodefs.
• Description:

The addDefines function adds specified preprocessor macro definitions to the


project's build information. The MATLAB Coder software stores the definitions in a
vector. The function adds definitions to the end of the vector based on the order in
which you specify them.

In addition to the required buildinfo and macrodefs arguments, you can use an
optional groups argument to group your options.

addIncludeFiles

• Purpose: Add include files to build information.


• Syntax: addIncludeFiles(buildinfo, filenames, paths, groups)

paths and groups are optional.


• Arguments:

buildinfo
Build information stored in RTW.BuildInfo.
filenames
A character array or cell array of character arrays that specifies names of include
files to be added to the build information.

The filename strings can include wildcard characters, provided that the dot
delimiter (.) is present. Examples are '*.*', '*.h', and '*.h*'.

The function adds the filenames to the end of a vector in the order that you specify
them.

The function removes duplicate include file entries that

• You specify as input


• Already exist in the include file vector
• Have a path that matches the path of a matching filename

21-142
Customize the Post-Code-Generation Build Process

A duplicate entry consists of an exact match of a path string and corresponding


filename.
paths (optional)
A character array or cell array of character arrays that specifies paths to the
include files. The function adds the paths to the end of a vector in the order that
you specify them. If you specify a single path as a character array, the function
uses that path for all files.
groups (optional)
A character array or cell array of character arrays that groups specified include
files. You can use groups to

• Document the use of specific include files


• Retrieve or apply groups of include files

You can apply

• A single group name to an include file


• A single group name to multiple include files
• Multiple group names to collections of multiple include files

To... Specify groups as a...


Apply one group name to Character array.
include files
Apply different group names Cell array of character arrays such that the
to include files number of group names that you specify
matches the number of elements you specify for
filenames.
• Description:

The addIncludeFiles function adds specified include files to the project's build
information. The MATLAB Coder software stores the include files in a vector. The
function adds the filenames to the end of the vector in the order that you specify
them.

21-143
21 Generating C/C++ Code from MATLAB Code

In addition to the required buildinfo and filenames arguments, you can specify
optional paths and groups arguments. You can specify each optional argument as a
character array or a cell array of character arrays.

If You Specify an Optional The Function...


Argument as a...
Character array Applies the character array to the include files it adds to the
build information
Cell array of character arrays Pairs each character array with a specified include file. Thus,
the length of the cell array must match the length of the cell
array you specify for filenames.

If you choose to specify groups, but omit paths, specify a null string ('') for paths.

addIncludePaths

• Purpose: Add include paths to build information.


• Syntax: addIncludePaths(buildinfo, paths, groups)

groups is optional.
• Arguments:

buildinfo
Build information stored in RTW.BuildInfo.
paths
A character array or cell array of character arrays that specifies include file paths
to be added to the build information. The function adds the paths to the end of a
vector in the order that you specify them.

The function removes duplicate include file entries that

• You specify as input


• Already exist in the include path vector
• Have a path that matches the path of a matching filename

A duplicate entry consists of an exact match of a path string and corresponding


filename.

21-144
Customize the Post-Code-Generation Build Process

groups (optional)
A character array or cell array of character arrays that groups specified include
paths. You can use groups to

• Document the use of specific include paths


• Retrieve or apply groups of include paths

You can apply

• A single group name to an include path


• A single group name to multiple include paths
• Multiple group names to collections of multiple include paths

To Specify groups as a
Apply one group name to Character array.
include paths
Apply different group Cell array of character arrays such that the number
names to include paths of group names that you specify matches the
number of elements you specify for paths.
• Description:

The addIncludePaths function adds specified include paths to the project's build
information. The MATLAB Coder software stores the include paths in a vector. The
function adds the paths to the end of the vector in the order that you specify them.

In addition to the required buildinfo and paths arguments, you can specify an
optional groups argument. You can specify groups as a character array or a cell
array of character arrays.

If You Specify an Optional Argument as The Function


a
Character array Applies the character array to the include
paths it adds to the build information.
Cell array of character arrays Pairs each character array with a specified
include path. Thus, the length of the cell array
must match the length of the cell array you
specify for paths.
21-145
21 Generating C/C++ Code from MATLAB Code

addLinkFlags

• Purpose: Add link options to build information.


• Syntax: addLinkFlags(buildinfo, options, groups)

groups is optional.
• Arguments:

buildinfo
Build information stored in RTW.BuildInfo.
options
A character array or cell array of character arrays that specifies the linker options
to be added to the build information. The function adds each option to the end of
a linker option vector. If you specify multiple options within a single character
array, for example '-MD -Gy', the function adds the string to the vector as a
single element. For example, if you add '-MD -Gy' and then '-T', the vector
consists of two elements, as shown below.
'-MD -Gy' '-T'
groups (optional)
A character array or cell array of character arrays that groups specified linker
options. You can use groups to

• Document the use of specific linker options


• Retrieve or apply groups of linker options

You can apply

• A single group name to one or more linker options


• Multiple group names to collections of linker options (available for nonmakefile
build environments only)

To Specify groups as a.
Apply one group name to Character array.
linker options
Apply different group Cell array of character arrays such that the number
names to linker options of group names matches the number of elements you
specify for options.

21-146
Customize the Post-Code-Generation Build Process

• Description:

The addLinkFlags function adds specified linker options to the project's build
information. The MATLAB Coder software stores the linker options in a vector. The
function adds options to the end of the vector based on the order in which you specify
them.

In addition to the required buildinfo and options arguments, you can use an
optional groups argument to group your options.

addLinkObjects

• Purpose: Add link objects to build information.


• Syntax: addLinkObjects(buildinfo, linkobjs, paths, priority,
precompiled, linkonly, groups)

The arguments except buildinfo , linkobjs, and paths are optional. If you specify
an optional argument, you must specify the optional arguments preceding it.
• Arguments:

buildinfo
Build information stored in RTW.BuildInfo.
linkobjs
A character array or cell array of character arrays that specifies the filenames
of linkable objects to be added to the build information. The function adds the
filenames that you specify in the function call to a vector that stores the object
filenames in priority order. If you specify multiple objects that have the same
priority (see priority below), the function adds them to the vector based on the
order in which you specify the object filenames in the cell array.

The function removes duplicate link objects that

• You specify as input


• Already exist in the linkable object filename vector
• Have a path that matches the path of a matching linkable object filename

A duplicate entry consists of an exact match of a path string and corresponding


linkable object filename.
paths

21-147
21 Generating C/C++ Code from MATLAB Code

A character array or cell array of character arrays that specifies paths to the
linkable objects. If you specify a character array, the path string applies to all
linkable objects.
priority (optional)
A numeric value or vector of numeric values that indicates the relative priority of
each specified link object. Lower values have higher priority. The default priority
is 1000.
precompiled (optional)
The logical value true or false or a vector of logical values that indicates
whether each specified link object is precompiled.

Specify true if the link object has been prebuilt for faster compiling and linking
and exists in a specified location.

If precompiled is false (the default), the MATLAB Coder build process creates
the link object in the build folder.

This argument is ignored if linkonly equals true.


linkonly (optional)
The logical value true or false or a vector of logical values that indicates
whether each specified link object is to be used only for linking.

Specify true if the MATLAB Coder build process should not build, nor generate
rules in the makefile for building, the specified link object, but should include it
when linking the final executable. For example, you can use this to incorporate
link objects for which source files are not available. If linkonly is true, the value
of precompiled is ignored.

If linkonly is false (the default), rules for building the link objects are added
to the makefile. In this case, the value of precompiled determines which
subsection of the added rules is expanded, START_PRECOMP_LIBRARIES (true)
or START_EXPAND_LIBRARIES (false). The software performs the expansion
of the START_PRECOMP_LIBRARIES or START_EXPAND_LIBRARIES macro only
if your code generation target uses the template makefile approach for building
code.
groups (optional)

21-148
Customize the Post-Code-Generation Build Process

A character array or cell array of character arrays that groups specified link
objects. You can use groups to

• Document the use of specific link objects


• Retrieve or apply groups of link objects

You can apply

• A single group name to a linkable object


• A single group name to multiple linkable objects
• Multiple group name to collections of multiple linkable objects

To. Specify groups as a


Apply one group name to Character array.
link objects
Apply different group Cell array of character arrays such that the number
names to link objects of group names matches the number elements you
specify for linkobjs.

The default value of groups is {''}.


• Description:

The addLinkObjects function adds specified link objects to the project's build
information. The MATLAB Coder software stores the link objects in a vector in
relative priority order. If multiple objects have the same priority or you do not specify
priorities, the function adds the objects to the vector based on the order in which you
specify them.

In addition to the required buildinfo, linkobjs, and paths arguments, you can
specify the optional arguments priority, precompiled, linkonly, and groups.
You can specify paths and groups as a character array or a cell array of character
arrays.

If You Specify paths or groups as The Function...


a...
Character array Applies the character array to the objects it
adds to the build information.

21-149
21 Generating C/C++ Code from MATLAB Code

If You Specify paths or groups as The Function...


a...
Cell array of character arrays Pairs each character array with a specified
object. Thus, the length of the cell array must
match the length of the cell array you specify
for linkobjs.

Similarly, you can specify priority, precompiled, and linkonly as a value or


vector of values.

If You Specify priority, The Function


precompiled, or linkonly as a
Value Applies the value to the objects it adds to the
build information.
Vector of values Pairs each value with a specified object. Thus,
the length of the vector must match the length
of the cell array you specify for linkobjs.

If you choose to specify an optional argument, you must specify the optional
arguments preceding it. For example, to specify that objects are precompiled using
the precompiled argument, you must specify the priority argument that precedes
precompiled. You could pass the default priority value 1000, as shown below.
addLinkObjects(myBuildInfo, 'test1', '/proj/lib/lib1', 1000, true);

addNonBuildFiles

• Purpose: Add nonbuild-related files to build information.


• Syntax: addNonBuildFiles(buildinfo, filenames, paths, groups)

paths and groups are optional.


• Arguments:

buildinfo
Build information stored in RTW.BuildInfo.
filenames
A character array or cell array of character arrays that specifies names of
nonbuild-related files to be added to the build information.
21-150
Customize the Post-Code-Generation Build Process

The filename strings can include wildcard characters, provided that the dot
delimiter (.) is present. Examples are '*.*', '*.DLL', and '*.D*'.

The function adds the filenames to the end of a vector in the order that you specify
them.

The function removes duplicate nonbuild file entries that

• Already exist in the nonbuild file vector


• Have a path that matches the path of a matching filename

A duplicate entry consists of an exact match of a path string and corresponding


filename.
paths (optional)
A character array or cell array of character arrays that specifies paths to the
nonbuild files. The function adds the paths to the end of a vector in the order that
you specify them. If you specify a single path as a character array, the function
uses that path for all files.
groups (optional)
A character array or cell array of character arrays that groups specified nonbuild
files. You can use groups to

• Document the use of specific nonbuild files


• Retrieve or apply groups of nonbuild files

You can apply

• A single group name to a nonbuild file


• A single group name to multiple nonbuild files
• Multiple group names to collections of multiple nonbuild files

To Specify groups as a.
Apply one group name to Character array.
nonbuild files

21-151
21 Generating C/C++ Code from MATLAB Code

To Specify groups as a.
Apply different group names Cell array of character arrays such that the
to nonbuild files number of group names that you specify
matches the number of elements you specify for
filenames.
• Description:

The addNonBuildFiles function adds specified nonbuild-related files, such as


DLL files required for a final executable, or a README file, to the project's build
information. The MATLAB Coder software stores the nonbuild files in a vector. The
function adds the filenames to the end of the vector in the order that you specify
them.

In addition to the required buildinfo and filenames arguments, you can specify
optional paths and groups arguments. You can specify each optional argument as a
character array or a cell array of character arrays.

If You Specify an Optional Argument The Function


as a
Character array Applies the character array to the nonbuild files it adds to the
build information.
Cell array of character arrays Pairs each character array with a specified nonbuild file. Thus,
the length of the cell array must match the length of the cell
array you specify for filenames.

If you choose to specify groups, but omit paths, specify a null string ('') for paths.

addSourceFiles

• Purpose: Add source files to build information.


• Syntax: addSourceFiles(buildinfo, filenames, paths, groups)

paths and groups are optional.


• Arguments:

buildinfo
Build information stored in RTW.BuildInfo.
filenames

21-152
Customize the Post-Code-Generation Build Process

A character array or cell array of character arrays that specifies names of the
source files to be added to the build information.

The filename strings can include wildcard characters, provided that the dot
delimiter (.) is present. Examples are '*.*', '*.c', and '*.c*'.

The function adds the filenames to the end of a vector in the order that you specify
them.

The function removes duplicate source file entries that

• You specify as input


• Already exist in the source file vector
• Have a path that matches the path of a matching filename

A duplicate entry consists of an exact match of a path string and corresponding


filename.
paths (optional)
A character array or cell array of character arrays that specifies paths to the
source files. The function adds the paths to the end of a vector in the order that
you specify them. If you specify a single path as a character array, the function
uses that path for all files.
groups (optional)
A character array or cell array of character arrays that groups specified source
files. You can use groups to

• Document the use of specific source files


• Retrieve or apply groups of source files

You can apply

• A single group name to a source file


• A single group name to multiple source files
• Multiple group names to collections of multiple source files

21-153
21 Generating C/C++ Code from MATLAB Code

To Specify group as a
Apply one group name to Character array.
source files
Apply different group names to Cell array of character arrays such that the
source files number of group names that you specify
matches the number of elements you specify for
filenames.
• Description:

The addSourceFiles function adds specified source files to the project's build
information. The MATLAB Coder software stores the source files in a vector. The
function adds the filenames to the end of the vector in the order that you specify
them.

In addition to the required buildinfo and filenames arguments, you can specify
optional paths and groups arguments. You can specify each optional argument as a
character array or a cell array of character arrays.

If You Specify an Optional The Function


Argument as a.
Character array Applies the character array to the source files it adds to the build
information.
Cell array of character arrays Pairs each character array with a specified source file. Thus, the
length of the cell array must match the length of the cell array
you specify for filenames.

If you choose to specify groups, but omit paths, specify a null string ('') for paths.

addSourcePaths

• Purpose: Add source paths to build information.


• Syntax: addSourcePaths(buildinfo, paths, groups)

groups is optional.
• Arguments:

buildinfo

21-154
Customize the Post-Code-Generation Build Process

Build information stored in RTW.BuildInfo.


paths
A character array or cell array of character arrays that specifies source file paths
to be added to the build information. The function adds the paths to the end of a
vector in the order that you specify them.

The function removes duplicate source file entries that

• You specify as input


• Already exist in the source path vector
• Have a path that matches the path of a matching filename

A duplicate entry consists of an exact match of a path string and corresponding


filename.

Note: The MATLAB Coder software does not check whether a specified path
string is valid.

groups (optional)
A character array or cell array of character arrays that groups specified source
paths. You can use groups to

• Document the use of specific source paths


• Retrieve or apply groups of source paths

• Description:

The addSourcePaths function adds specified source paths to the project's build
information. The MATLAB Coder software stores the source paths in a vector. The
function adds the paths to the end of the vector in the order that you specify them.

In addition to the required buildinfo and paths arguments, you can specify an
optional groups argument . You can specify groups as a character array or a cell
array of character arrays.

21-155
21 Generating C/C++ Code from MATLAB Code

If You Specify an Optional Argument as The Function


a
Character array Applies the character array to the source paths
it adds to the build information.
Cell array of character arrays Pairs each character array with a specified
source path. Thus, the length of the character
array or cell array must match the length of
the cell array you specify for paths.

Note: The MATLAB Coder software does not check whether a specified path string is
valid.

addTMFTokens

• Purpose: Add template makefile (TMF) tokens that provide build-time information for
makefile generation.
• Syntax: addTMFTokens(buildinfo, tokennames, tokenvalues, groups)

groups is optional.
• Arguments:

buildinfo
Build information stored in RTW.BuildInfo.
tokennames
A character array or cell array of character arrays that specifies names of
TMF tokens (for example, '|>CUSTOM_OUTNAME<|') to be added to the build
information. The function adds the token names to the end of a vector in the order
that you specify them.

If you specify a token name that already exists in the vector, the first instance
takes precedence and its value used for replacement.
tokenvalues
A character array or cell array of character arrays that specifies TMF token
values corresponding to the previously-specified TMF token names. The function
adds the token values to the end of a vector in the order that you specify them.
groups (optional)

21-156
Customize the Post-Code-Generation Build Process

A character array or cell array of character arrays that groups specified TMF
tokens. You can use groups to

• Document the use of specific TMF tokens


• Retrieve or apply groups of TMF tokens

You can apply

• A single group name to a TMF token


• A single group name to multiple TMF tokens
• Multiple group names to collections of multiple TMF tokens

To Specify groups as a
Apply one group name to Character array.
TMF tokens
Apply different group names Cell array of character arrays such that the
to TMF tokens number of group names that you specify
matches the number of elements you specify for
tokennames.
• Description:

Call the addTMFTokens function inside a post code generation command to provide
build-time information to help customize makefile generation. The tokens specified
in the addTMFTokens function call must be handled appropriately in the template
makefile (TMF) for the target selected for your project. For example, if your post
code generation command calls addTMFTokens to add a TMF token named |
>CUSTOM_OUTNAME<| that specifies an output file name for the build, the TMF must
act on the value of |>CUSTOM_OUTNAME<| to achieve the desired result.

The addTMFTokens function adds specified TMF token names and values to the
project's build information. The MATLAB Coder software stores the TMF tokens in
a vector. The function adds the tokens to the end of the vector in the order that you
specify them.

In addition to the required buildinfo, tokennames, and tokenvalues arguments,


you can specify an optional groups argument. You can specify groups as a character
array or a cell array of character arrays.

21-157
21 Generating C/C++ Code from MATLAB Code

If You Specify an Optional Argument The Function


as a
Character array Applies the character array to the TMF tokens it adds to the
build information.
Cell array of character arrays Pairs each character array with a specified TMF token. Thus,
the length of the cell array must match the length of the cell
array you specify for tokennames.

findIncludeFiles

• Purpose: Find and add include (header) files to build information.


• Syntax: findIncludeFiles(buildinfo, extPatterns)

extPatterns is optional.
• Arguments:

buildinfo
Build information stored in RTW.BuildInfo.
extPatterns (optional)
A cell array of character arrays that specify patterns of file name extensions for
which the function is to search. Each pattern

• Must start with *.


• Can include a combination of alphanumeric and underscore (_) characters

The default pattern is *.h.

Examples of valid patterns include


*.h
*.hpp
*.x*
• Description:

The findIncludeFiles function

• Searches for include files, based on specified file name extension patterns, in the
source and include paths recorded in a project's build information object

21-158
Customize the Post-Code-Generation Build Process

• Adds the files found, along with their full paths, to the build information object
• Deletes duplicate entries

getCompileFlags

• Purpose: Get compiler options from build information.


• Syntax: options = getCompileFlags(buildinfo, includeGroups,
excludeGroups)

includeGroups and excludeGroups are optional.


• Input arguments:

buildinfo
Build information stored in RTW.BuildInfo.
includeGroups (optional)
A character array or cell array of character arrays that specifies groups of
compiler flags you want the function to return.
excludeGroups (optional)
A character array or cell array of character arrays that specifies groups of
compiler flags you do not want the function to return.
• Output arguments:

Compiler options stored in the project's build information.


• Description:

The getCompileFlags function returns compiler options stored in the project's build
information. Using optional includeGroups and excludeGroups arguments, you
can selectively include or exclude groups of options the function returns.

If you choose to specify excludeGroups and omit includeGroups, specify a null


string ('') for includeGroups.

getDefines

• Purpose: Get preprocessor macro definitions from build information.


• Syntax: [macrodefs, identifiers, values] = getDefines(buildinfo,
includeGroups, excludeGroups)

21-159
21 Generating C/C++ Code from MATLAB Code

includeGroups and excludeGroups are optional.


• Input arguments:

buildinfo
Build information stored in RTW.BuildInfo.
includeGroups (optional)
A character array or cell array of character arrays that specifies groups of macro
definitions you want the function to return.
excludeGroups (optional)
A character array or cell array of character arrays that specifies groups of macro
definitions you do not want the function to return.
• Output arguments:

Preprocessor macro definitions stored in the project's build information. The function
returns the macro definitions in three vectors.

Vector Description
macrodefs Complete macro definitions with -D prefix
identifiers Names of the macros
values Values assigned to the macros (anything specified
to the right of the first equals sign) ; the default is
an empty string ('')
• Description:

The getDefines function returns preprocessor macro definitions stored in the


project's build information. When the function returns a definition, it automatically

• Prepends a -D to the definition if the -D was not specified when the definition was
added to the build information
• Changes a lowercase -d to -D

Using optional includeGroups and excludeGroups arguments, you can selectively


include or exclude groups of definitions the function is to return.

If you choose to specify excludeGroups and omit includeGroups, specify a null


string ('') for includeGroups.

21-160
Customize the Post-Code-Generation Build Process

getFullFileList

• Purpose: Get All files from project's build information.


• Syntax: [fPathNames, names] = getFullFileList(buildinfo, fcase)

fcase is optional.
• Input arguments:

buildinfo
Build information stored in RTW.BuildInfo.
fcase (optional)
The string 'source', 'include', or 'nonbuild'. If the argument is omitted,
the function returns all the files from the build information object.

If You Specify The Function


'source' Returns source files from the build information
object.
'include' Returns include files from the build information
object.
'nonbuild' Returns nonbuild files from the build information
object.
• Output arguments:

Fully-qualified file paths and file names for files stored in the project's build
information.

Note: Usually it is unnecessary to resolve the path of every file in the project build
information, because the makefile for the project build will resolve file locations based
on source paths and rules. Therefore, getFullFileList returns the path for each
file only if a path was explicitly associated with the file when it was added, or if you
called updateFilePathsAndExtensions to resolve file paths and extensions before
calling getFullFileList.
• Description:

The getFullFileList function returns the fully-qualified paths and names of all
files, or files of a selected type (source, include, or nonbuild), stored in the project's
build information.

21-161
21 Generating C/C++ Code from MATLAB Code

getIncludeFiles

• Purpose: Get include files from build information.


• Syntax: files = getIncludeFiles(buildinfo, concatenatePaths,
replaceMatlabroot, includeGroups, excludeGroups)

includeGroups and excludeGroups are optional.


• Input arguments:

buildinfo
Build information stored in RTW.BuildInfo.
concatenatePaths
The logical value true or false.

If You Specify The Function


true Concatenates and returns each filename with its
corresponding path.
false Returns only filenames.

replaceMatlabroot
The logical value true or false.

If You Specify The Function


true Replaces the token $(MATLAB_ROOT) with the
absolute path string for your MATLAB installation
folder.
false Does not replace the token $(MATLAB_ROOT).

includeGroups (optional)
A character array or cell array of character arrays that specifies groups of include
files you want the function to return.
excludeGroups (optional)
A character array or cell array of character arrays that specifies groups of include
files you do not want the function to return.
21-162
• Output arguments:
Customize the Post-Code-Generation Build Process

Names of include files stored in the project's build information.


• Description:

The getIncludeFiles function returns the names of include files stored in the
project's build information. Use the concatenatePaths and replaceMatlabroot
arguments to control whether the function includes paths and your MATLAB
root definition in the output it returns. Using optional includeGroups and
excludeGroups arguments, you can selectively include or exclude groups of include
files the function returns.

If you choose to specify excludeGroups and omit includeGroups, specify a null


string ('') for includeGroups.

getIncludePaths

• Purpose: Get include paths from build information.


• Syntax: files=getIncludePaths(buildinfo, replaceMatlabroot,
includeGroups, excludeGroups)

includeGroups and excludeGroups are optional.


• Input arguments:

buildinfo
Build information stored in RTW.BuildInfo.
replaceMatlabroot
The logical value true or false.

If You Specify The Function


true Replaces the token $(MATLAB_ROOT) with the
absolute path string for your MATLAB installation
folder.
false Does not replace the token $(MATLAB_ROOT).

includeGroups (optional)
A character array or cell array of character arrays that specifies groups of include
paths you want the function to return.
excludeGroups (optional)

21-163
21 Generating C/C++ Code from MATLAB Code

A character array or cell array of character arrays that specifies groups of include
paths you do not want the function to return.
• Output arguments:

Paths of include files stored in the build information object.


• Description:

The getIncludePaths function returns the names of include file paths stored in
the project's build information. Use the replaceMatlabroot argument to control
whether the function includes your MATLAB root definition in the output it returns.
Using optional includeGroups and excludeGroups arguments, you can selectively
include or exclude groups of include file paths the function returns.

If you choose to specify excludeGroups and omit includeGroups, specify a null


string ('') for includeGroups.

getLinkFlags

• Purpose: Get link options from build information.


• Syntax: options=getLinkFlags(buildinfo, includeGroups,
excludeGroups)

includeGroups and excludeGroups are optional.


• Input arguments:

buildinfo
Build information stored in RTW.BuildInfo.
includeGroups (optional)
A character array or cell array that specifies groups of linker flags you want the
function to return.
excludeGroups (optional)
A character array or cell array that specifies groups of linker flags you do not
want the function to return. To exclude groups and not include specific groups,
specify an empty cell array ('') for includeGroups.
• Output arguments:

Linker options stored in the project's build information.


• Description:

21-164
Customize the Post-Code-Generation Build Process

The getLinkFlags function returns linker options stored in the project's build
information. Using optional includeGroups and excludeGroups arguments, you
can selectively include or exclude groups of options the function returns.

If you choose to specify excludeGroups and omit includeGroups, specify a null


string ('') for includeGroups.

getNonBuildFiles

• Purpose: Get nonbuild-related files from build information.


• Syntax: files=getNonBuildFiles(buildinfo, concatenatePaths,
replaceMatlabroot, includeGroups, excludeGroups)

includeGroups and excludeGroups are optional.


• Input arguments:

buildinfo
Build information stored in RTW.BuildInfo.
concatenatePaths
The logical value true or false.

If You Specify The Function


true Concatenates and returns each filename with its
corresponding path.
false Returns only filenames.

replaceMatlabroot
The logical value true or false.

If You Specify The Function


true Replaces the token $(MATLAB_ROOT) with the
absolute path string for your MATLAB installation
folder.
false Does not replace the token $(MATLAB_ROOT).

includeGroups (optional) 21-165


21 Generating C/C++ Code from MATLAB Code

A character array or cell array of character arrays that specifies groups of


nonbuild files you want the function to return.
excludeGroups (optional)
A character array or cell array of character arrays that specifies groups of
nonbuild files you do not want the function to return.
• Output arguments:

Names of nonbuild files stored in the project's build information.


• Description:

The getNonBuildFiles function returns the names of nonbuild-related files,


such as DLL files required for a final executable, or a README file, stored in the
project's build information. Use the concatenatePaths and replaceMatlabroot
arguments to control whether the function includes paths and your MATLAB
root definition in the output it returns. Using optional includeGroups and
excludeGroups arguments, you can selectively include or exclude groups of nonbuild
files the function returns.

If you choose to specify excludeGroups and omit includeGroups, specify a null


string ('') for includeGroups.

getSourceFiles
• Purpose: Get source files from project's build information.
• Syntax: srcfiles=getSourceFiles(buildinfo, concatenatePaths,
replaceMatlabroot, includeGroups, excludeGroups)

includeGroups and excludeGroups are optional.


• Input arguments:

buildinfo
Build information stored in RTW.BuildInfo.
concatenatePaths
The logical value true or false.

If You Specify The Function


true Concatenates and returns each filename with its
corresponding path.

21-166
Customize the Post-Code-Generation Build Process

If You Specify The Function


false Returns only filenames.

Note: Usually it is unnecessary to resolve the path of every file in the


project build information, because the makefile for the project build will
resolve file locations based on source paths and rules. Therefore, specifying
true for concatenatePaths returns the path for each file only if a path
was explicitly associated with the file when it was added, or if you called
updateFilePathsAndExtensions to resolve file paths and extensions before
calling getSourceFiles.

replaceMatlabroot
The logical value true or false.

If You Specify The Function


true Replaces the token $(MATLAB_ROOT) with the
absolute path string for your MATLAB installation
folder.
false Does not replace the token $(MATLAB_ROOT).

includeGroups (optional)
A character array or cell array of character arrays that specifies groups of source
files you want the function to return.
excludeGroups (optional)
A character array or cell array of character arrays that specifies groups of source
files you do not want the function to return.
• Output arguments:

Names of source files stored in the project's build information.


• Description:

The getSourceFiles function returns the names of source files stored in the
project's build information. Use the concatenatePaths and replaceMatlabroot
arguments to control whether the function includes paths and your MATLAB
root definition in the output it returns. Using optional includeGroups and
21-167
21 Generating C/C++ Code from MATLAB Code

excludeGroups arguments, you can selectively include or exclude groups of source


files the function returns.

If you choose to specify excludeGroups and omit includeGroups, specify a null


string ('') for includeGroups.

getSourcePaths

• Purpose: Get source paths from build information.


• Syntax: files=getSourcePaths(buildinfo, replaceMatlabroot,
includeGroups, excludeGroups)

includeGroups and excludeGroups are optional.


• Input arguments:

buildinfo
Build information stored in RTW.BuildInfo.
replaceMatlabroot
The logical value true or false.

If You Specify The Function


true Replaces the token $(MATLAB_ROOT) with the
absolute path string for your MATLAB installation
folder.
false Does not replace the token $(MATLAB_ROOT).

includeGroups (optional)
A character array or cell array of character arrays that specifies groups of source
paths you want the function to return.
excludeGroups (optional)
A character array or cell array of character arrays that specifies groups of source
paths you do not want the function to return.
• Output arguments:

Paths of source files stored in the project's build information.


• Description:
21-168
Customize the Post-Code-Generation Build Process

The getSourcePaths function returns the names of source file paths stored in
the project build information. Use the replaceMatlabroot argument to control
whether the function includes your MATLAB root definition in the output it returns.
Using optional includeGroups and excludeGroups arguments, you can selectively
include or exclude groups of source file paths that the function returns.

If you choose to specify excludeGroups and omit includeGroups, specify a null


string ('') for includeGroups.

packNGo

• Purpose: Package generated code in zip file for relocation.


• Syntax: packNGo(buildinfo, propVals...)

propVals is optional.
• Arguments:

buildinfo
Build information loaded from the build folder.
propVals (optional)
A cell array of property-value pairs that specify packaging details.

To Specify Property With Value


Package generated code files in a zip file 'packType' 'flat' (default)
as a single, flat folder.
Package generated code files 'packType' 'hierarchical'
hierarchically in a primary zip file.

The value of the 'nestedZipFiles'


property determines whether the primary
zip file contains secondary zip files or
folders.
Create a primary zip file that contains 'nestedZipFiles' true (default)
three secondary zip files:

• mlrFiles.zip — files in your


matlabroot folder tree

21-169
21 Generating C/C++ Code from MATLAB Code

To Specify Property With Value


• sDirFiles.zip — files in and under
your build folder
• otherFiles.zip — required files not
in the matlabroot or start folder
trees

Paths for files in the secondary zip files


are relative to the root folder of the
primary zip file.
Create a primary zip file that contains 'nestedZipFiles' false
folders, for example, your build folder and
matlabroot.
Specify a file name for the primary zip file. 'fileName' 'string'

Default:'untitled.zip'
If you omit the .zip file
extension, the function
adds it.
Include only the minimal header files 'minimalHeaders' true (default)
required to build the code in the zip file.
Include header files found on the include 'minimalHeaders' false
path in the zip file.
Include the html folder for your code 'includeReport' true (default is false)
generation report.
Direct packNGo not to error out on parse 'ignoreParseError' true (default is false)
errors.
Direct packNGo not to error out if files are 'ignoreFileMissing' true (default is false)
missing.
• Description:

The packNGo function packages the following code files in a compressed zip file so you
can relocate, unpack, and rebuild them in another development environment.

• Source files (for example, .c and .cpp files)


• Header files (for example, .h and .hpp files)

21-170
Customize the Post-Code-Generation Build Process

• Nonbuild-related files (for example, .dll files required for a final executable file
and .txt informational files)
• MAT-file that contains the build information object (.mat file)

Use this function to relocate files so that they can be recompiled for a specific target
environment, or rebuilt in a development environment in which MATLAB is not
installed.

By default, the packNGo function packages the files as a flat folder structure in a zip
file, foo.zip. The zip file is located in the current working folder.

You can customize the output by specifying property name and value pairs as
previously described.

After relocating the zip file, use a standard zip utility to unpack the compressed file.
• Limitations:

The following limitations apply to use of the packNGo function:

• The function operates on source files only, such as *.c, *.cpp, and *.h files. The
function does not support compile flags, defines, or makefiles.
• The function does not package example main source and header files that you
generate using the default configuration settings. To package the example
main files, configure code generation to generate and compile the example main
function, generate your code, and then package the build files.
• Unnecessary files might be included. The function might find additional files from
source paths and include paths recorded in the build information, even if they are
not used.
• packNGo does not package the code generated for MEX targets.
• See Also:

• “Package Code for Other Development Environments” on page 25-44

updateFilePathsAndExtensions

• Purpose: Update files in project build information with missing paths and file
extensions.
• Syntax: updateFilePathsAndExtensions(buildinfo, extensions)

21-171
21 Generating C/C++ Code from MATLAB Code

extensions is optional.
• Arguments:

buildinfo
Build information stored in RTW.BuildInfo.
extensions (optional)
A cell array of character arrays that specifies the extensions (file types) of files
for which to search and include in the update processing. By default, the function
searches for files with a .c extension. The function checks files and updates
paths and extensions based on the order in which you list the extensions in the
cell array. For example, if you specify {'.c' '.cpp'}, and a folder contains
myfile.c and myfile.cpp, an instance of myfile is updated to myfile.c.
• Description:

Using paths that already exist in a project's build information, the


updateFilePathsAndExtensions function checks whether file references in the
build information need to be updated with a path or file extension. This function can
be particularly useful for

• Maintaining build information for a toolchain that requires the use of file
extensions
• Updating multiple customized instances of build information for a given project

updateFileSeparator

• Purpose: Change file separator used in project's build information.


• Syntax: updateFileSeparator(buildinfo, separator)
• Arguments:

buildinfo
Build information stored in RTW.BuildInfo.
separator
A character array that specifies the file separator \ (Windows) or / (UNIX®) to be
applied to file path specifications.
• Description:

21-172
Customize the Post-Code-Generation Build Process

The updateFileSeparator function changes instances of the current file separator


(/ or \) in a project's build information to the specified file separator.

The default value for the file separator matches the value returned by the MATLAB
command filesep. For makefile based builds, you can override the default by
defining a separator with the MAKEFILE_FILESEP macro in the template makefile.
If the GenerateMakefile parameter is set, the MATLAB Coder software overrides
the default separator and updates the build information after evaluating the
PostCodeGenCommand configuration parameter.

Write Post-Code-Generation Command


A post-code-generation command is a MATLAB file that typically calls functions that
get data from or add data to the build information object. For example, you can access
the project name in the variable projectName and the RTW.BuildInfo object in the
variable buildInfo. You can write the command as a script or a function.

If You Write the Command as a Then the


Script Script can gain access to the project
(top-level function) name and the build
information directly.
Function Function can receive the project name and
the build information as arguments.

If your post-code-generation command calls user-defined functions, make sure that the
functions are on the MATLAB path. If the build process cannot find a function that you
use in your command, the process fails.

You can call combinations of build information functions to customize the post-code-
generation build. See “Write and Use Post-Code-Generation Command at the Command
Line” on page 21-175

Write Post-Code-Generation Command as a Script

Set PostCodeGenCommand to the script name.

At the command line, enter:

cfg = coder.config('lib');

21-173
21 Generating C/C++ Code from MATLAB Code

cfg.PostCodeGenCommand = 'ScriptName';

Write Post-Code-Generation Command as a Function

Set PostCodeGenCommand to the function signature. When you define the command as a
function, you can specify an arbitrary number of input arguments. If you want to access
the project name, include projectName as an argument. If you want to modify or access
build information, add buildInfo as an argument.

At the command line, enter:


cfg = coder.config('lib');
cfg.PostCodeGenCommand = 'FunctionName(projectName, buildInfo)';

Use Post-Code-Generation Command to Customize Build


After you have written a post-code-generation command, you must include this command
in the build processing. You can include the command from the project settings dialog box
or the command line.

Use Post-Code-Generation Command in the MATLAB Coder App.

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Click More Settings.
3 On the Custom Code tab, set the Post-code-generation command parameter.

How you use the PostCodeGenCommand option depends on whether you write the
command as a script or a function. See “Use Post-Code-Generation Command at the
Command Line” on page 21-174 and “Use Post-Code-Generation Command in the
MATLAB Coder App.” on page 21-174.

Use Post-Code-Generation Command at the Command Line

Set the PostCodeGenCommand option for the code generation configuration object
(coder.MexCodeConfig, coder.CodeConfig or coder.EmbeddedCodeConfig).

How you use the PostCodeGenCommand option depends on whether you write the
command as a script or a function. See “Use Post-Code-Generation Command at the
Command Line” on page 21-174 and “Use Post-Code-Generation Command in the
MATLAB Coder App.” on page 21-174.

21-174
Customize the Post-Code-Generation Build Process

Write and Use Post-Code-Generation Command at the Command Line


The following example shows how to write and use a post-code-generation command as a
function. The setbuildargs function takes the build information object as a parameter,
sets up link options, and adds them to the build information object.

1 Create a post-code-generation command as a function, setbuildargs, which takes


the buildInfo object as a parameter:

function setbuildargs(buildInfo)
% The example being compiled requires pthread support.
% The -lpthread flag requests that the pthread library be included
% in the build
linkFlags = {'-lpthread'};
buildInfo.addLinkFlags(linkFlags);
2 Create a code generation configuration object. Set the PostCodeGenCommand option
to 'setbuildargs(buildInfo)' so that this command is included in the build
processing:
cfg = coder.config('mex');
cfg.PostCodeGenCommand = 'setbuildargs(buildInfo)';
3 Using the -config option, generate a MEX function passing the configuration object
to codegen. For example, for the function foo that has no input parameters:

codegen -config cfg foo

21-175
21 Generating C/C++ Code from MATLAB Code

Troubleshooting

Run-time Stack Overflow


If your C compiler reports a run-time stack overflow, set the value of the maximum
stack usage parameter to be less than the available stack size. In a project, in the
project settings dialog box Memory tab, set the Stack usage max parameter.
For command-line configuration objects (coder.MexCodeConfig, coder.CodeConfig,
coder.EmbeddedCodeConfig), set the StackUsageMax parameter.

21-176
22

Verify Generated C/C++ Code

• “Generation of Traceable Code” on page 22-2


• “Code Generation Reports” on page 22-10
• “Enable Code Generation Reports” on page 22-28
• “Run-Time Error Detection and Reporting in Standalone C/C++ Code” on page
22-29
• “Generate Standalone Code That Detects and Reports Run-Time Errors” on page
22-31
• “Testing Code Generated from MATLAB Code” on page 22-33
22 Verify Generated C/C++ Code

Generation of Traceable Code


In this section...
“Code Traceability” on page 22-2
“Generate Traceable Code” on page 22-2
“Format of Traceability Tags” on page 22-4
“Location of Comments in Generated Code” on page 22-5
“Traceability Limitations” on page 22-9

Code Traceability
You can configure MATLAB Coder to generate C code and MEX functions that include
the MATLAB source code as comments. Including this information in the generated code
enables you to:

• Correlate the generated code with your source code.


• Understand how the generated code implements your algorithm.
• Evaluate the quality of the generated code.

In these generated comments, a traceability tag immediately precedes each line of source
code. This traceability tag provides details about the location of the source code. For more
information, see “Format of Traceability Tags” on page 22-4.

For Embedded Coder projects, (requires an Embedded Coder license), you can also
generate C/C++ code that includes the MATLAB function help text. The function help
text is the first comment after the MATLAB function signature. It is displayed in the
function banner of the generated code. The function help text provides information about
the capabilities of the function and how to use it. For more information, see “Tracing
Between Generated C Code and MATLAB Code”.

Generate Traceable Code


To generate more traceable code, include MATLAB source code as comments.

Use the MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .

22-2
Generation of Traceable Code

2 Click More Settings.


3 On the Code Appearance tab, under Comments, select the MATLAB source
code as comments check box.

Use the Command-Line Interface


For MEX Targets

Use the MATLABSourceComments option of the MEX configuration object. For example,
to compile the file foo.m and include the source code as comments in the generated MEX
function:

1 In the MATLAB workspace, define the MEX configuration object by issuing a


constructor command:
mexcfg = coder.config('mex');
2 At the command line, enable the MATLABSourceComments:
mexcfg.MATLABSourceComments = true;
3 Using the -config option, pass the configuration object to codegen. For example, to
generate a MEX function for a function foo that has no input parameters:
codegen -config mexcfg foo

For C/C++ Libraries

Use the MATLABSourceComments option of the code generation configuration object.


For example, to compile the file foo.m and include the source code as comments in the
generated code for a C static library:

1 Create a code generation configuration object and enable the


MATLABSourceComments option. For example, to create a configuration object for a
static library:
cfg = coder.config('lib');
% If an Embedded Coder license is available,
% cfg is a coder.EmbeddedCodeConfig object,
% otherwise it's a coder.CodeConfig object
cfg.MATLABSourceComments = true;
2 Using the -config option, pass the configuration object to codegen. For example, to
generate a library for a function foo that has no input parameters:
codegen -config cfg foo

22-3
22 Verify Generated C/C++ Code

For Embedded Coder projects (requires an Embedded Coder license), you can also
include the function help text in the generated code function banner by using the
MATLABFcnDesc option. For more information, see “Tracing Between Generated C Code
and MATLAB Code”.
For C/C++ Executables

Use the MATLABSourceComments option of the code generation configuration object.


For example, to compile the file foo.m and include the source code as comments in the
generated code for a C executable:

1 Create a code generation configuration object and enable the


MATLABSourceComments option. For example, to create a configuration object for a
library:

cfg = coder.config('exe');
% If an Embedded Coder license is available,
% cfg is a coder.EmbeddedCodeConfig object,
% otherwise it's a coder.CodeConfig object
cfg.MATLABSourceComments = true;
2 Using the -config option, pass the configuration object to codegen. For example, to
generate an executable for a function foo that has no input parameters:

codegen -config cfg main.c foo


% You must specify a main file when generating an executable

For Embedded Coder projects, (requires an Embedded Coder license), you can also
include the function help text in the function banner of the generated code by using the
MATLABFcnDesc option. For more information, see “Tracing Between Generated C Code
and MATLAB Code”.

Format of Traceability Tags


In the generated code, traceability tags appear immediately before the MATLAB source
code in the comment. The format of the tag is:
<filename>:<line number>.

For example, the comment indicates that the code x = r * cos(theta); appears at
line 4 in the source file straightline.m.

/* 'straightline:4' x = r * cos(theta); */

22-4
Generation of Traceable Code

Note: With an Embedded Coder license, the traceability tags in the code generation
report are hyperlinks to the MATLAB source code. For more information, see “Tracing
Between Generated C Code and MATLAB Code”.

Location of Comments in Generated Code


The generated comments containing the source code and traceability tag appear in the
generated code as follows.

Straight-Line Source Code

In straight-line source code without if, while, for or switch statements, the comment
containing the source code precedes the generated code that implements the source code
statement. This comment appears after user comments that precede the generated code.

For example, in the following code, the user comment, /* Convert polar to
Cartesian */, appears before the generated comment containing the first line of source
code, together with its traceability tag,
/* 'straightline:4' x = r * cos(theta); */.
MATLAB Code

function [x, y] = straightline(r,theta)


%#codegen
% Convert polar to Cartesian
x = r * cos(theta);
y = r * sin(theta);
Commented C Code

void straightline(double r, double theta, double *x, double *y)


{
/* Convert polar to Cartesian */
/* 'straightline:4' x = r * cos(theta); */
*x = r * cos(theta);

/* 'straightline:5' y = r * sin(theta); */
*y = r * sin(theta);
}

If Statements

The comment for the if statement immediately precedes the code that implements the
statement. This comment appears after user comments that precede the generated code.

22-5
22 Verify Generated C/C++ Code

The comments for the elseif and else clauses appear immediately after the code that
implements the clause, and before the code generated for statements in the clause.

MATLAB Code

function y = ifstmt(u,v)
%#codegen
if u > v
y = v + 10;
elseif u == v
y = u * 2;
else
y = v - 10;
end

Commented C Code

double ifstmt(double u, double v)


{
double y;

/* 'ifstmt:3' if u > v */
if (u > v) {
/* 'ifstmt:4' y = v + 10; */
y = v + 10.0;
} else if (u == v) {
/* 'ifstmt:5' elseif u == v */
/* 'ifstmt:6' y = u * 2; */
y = u * 2.0;
} else {
/* 'ifstmt:7' else */
/* 'ifstmt:8' y = v - 10; */
y = v - 10.0;
}

return y;
}

For Statements

The comment for the for statement header immediately precedes the generated code
that implements the header. This comment appears after user comments that precede
the generated code.

22-6
Generation of Traceable Code

MATLAB Code

function y = forstmt(u)
%#codegen
y = 0;
for i=1:u
y = y + 1;
end

Commented C Code

double forstmt(double u)
{
double y;
int i;

/* 'forstmt:3' y = 0; */
y = 0.0;

/* 'forstmt:4' for i=1:u */


for (i = 0; i < (int)u; i++) {
/* 'forstmt:5' y = y + 1; */
y++;
}

return y;
}

While Statements

The comment for the while statement header immediately precedes the generated code
that implements the statement header. This comment appears after user comments that
precede the generated code.
MATLAB Code

function y = subfcn(y)
coder.inline('never');
while y < 100
y = y + 1;
end

Commented C Code

void subfcn(double *y)

22-7
22 Verify Generated C/C++ Code

{
/* 'subfcn:2' coder.inline('never'); */
/* 'subfcn:3' while y < 100 */
while (*y < 100.0) {
/* 'subfcn:4' y = y + 1; */
(*y)++;
}
}

Switch Statements

The comment for the switch statement header immediately precedes the generated code
that implements the statement header. This comment appears after user comments that
precede the generated code. The comments for the case and otherwise clauses appear
immediately after the generated code that implements the clause, and before the code
generated for statements in the clause.
MATLAB Code

function y = switchstmt(u)
%#codegen
y = 0;
switch u
case 1
y = y + 1;
case 3
y = y + 2;
otherwise
y = y - 1;
end

Commented C Code

double switchstmt(double u)
{
double y;

/* 'switchstmt:3' y = 0; */
/* 'switchstmt:4' switch u */
switch ((int)u) {
case 1:
/* 'switchstmt:5' case 1 */
/* 'switchstmt:6' y = y + 1; */
y = 1.0;
break;

22-8
Generation of Traceable Code

case 3:
/* 'switchstmt:7' case 3 */
/* 'switchstmt:8' y = y + 2; */
y = 2.0;
break;

default:
/* 'switchstmt:9' otherwise */
/* 'switchstmt:10' y = y - 1; */
y = -1.0;
break;
}

return y;
}

Traceability Limitations
For MATLAB Coder, there are traceability limitations.

• You cannot include MATLAB source code as comments for:

• MathWorks toolbox functions


• P-code
• The appearance or location of comments can vary depending on the following
conditions:

• Even if the implementation code is eliminated, for example, due to constant


folding, comments can still appear in the generated code.
• If a complete function or code block is eliminated, comments can be eliminated
from the generated code.
• For certain optimizations, the comments can be separated from the generated
code.
• Even if you do not choose to include source code comments in the generated code,
the generated code includes legally required comments from the MATLAB source
code.

22-9
22 Verify Generated C/C++ Code

Code Generation Reports

In this section...
“Code Generation Report Overview” on page 22-10
“Generating and Opening Reports” on page 22-12
“Names and Locations of Reports” on page 22-12
“MATLAB Code in a Report” on page 22-12
“Call Stack Information in a Report” on page 22-14
“Generated C/C++ Code in a Report” on page 22-16
“Build Summary Information in a Report” on page 22-17
“Errors and Warnings in a Report” on page 22-17
“MATLAB Code Variables in a Report” on page 22-18
“Target Build Information in a Report” on page 22-23
“Keyboard Shortcuts for a Report” on page 22-24
“Searching in a Report” on page 22-26
“Report Limitations” on page 22-26

Code Generation Report Overview


At code generation time, MATLAB Coder produces a report. The report helps you
to verify that your MATLAB code is suitable for code generation and to debug code
generation issues in your code.

The report provides links to your MATLAB code and C/C++ code files. It also provides
compile-time type information for the variables and expressions in your MATLAB code.
This information helps you to find sources of error messages and to understand type
propagation rules.

Here is an example of a code generation report.

22-10
Code Generation Reports

The report provides:

• MATLAB code information, including a list of functions and classes.


• Call stack information, providing information on the nesting of function calls.
• Links to generated C/C++ code files.
• Summary of build results, including type of target and number of warnings or errors.
• List of error and warning messages.
• List of variables in your MATLAB code.
• Target build log of compilation and linking activities

22-11
22 Verify Generated C/C++ Code

Generating and Opening Reports


• Using the MATLAB Coder app:

After code generation, on the Generate Code page, the MATLAB Coder app
generates a code generation report and provides a link to the report. If the code
generation report is enabled, or build errors occur, the Build Log tab also provides a
link to the report. To view the report, click the report link.
• Using the codegen command:

If the code generation report is enabled, or build errors occur, MATLAB Coder
generates a code generation report and provides a link to the report. To open the
report, click the report link. If you specify the LaunchReport option when you
generate code, MATLAB Coder opens the report.

Names and Locations of Reports


MATLAB Coder produces code generation reports in the following locations. The top-level
HTML file at each location is index.html.

• For MEX functions:


output_folder/mex/primary_function_name/html
• For C/C++ executables:
output_folder/exe/primary_function_name/html
• For C/C++ libraries:
output_folder/lib/primary_function_name/html

Note: The default output folder is codegen, but you can specify a different folder. For
more information, see “Configure Build Settings” on page 21-26.

MATLAB Code in a Report


To view your MATLAB code, click the MATLAB code tab. The code generation report
displays the code for the function or class highlighted in the list.

The MATLAB code tab provides:

22-12
Code Generation Reports

• A list of the MATLAB functions and classes. Depending on the build results, the
report displays icons next to each function or class name:


Errors in function or class.

Warnings in function or class.

Completed build, no errors or warnings.
• A filter control. You can use Filter functions and methods to sort functions and
methods by:

• Size
• Complexity
• Class
• An optional highlight control to highlight potential data type issues in the generated
C/C++ code. This option requires an Embedded Coder license. See “Highlight
Potential Data Type Issues in a Report”.

Local Functions

In the function list on the MATLAB code tab, the code generation report annotates the
local function with the name of the parent function.

For example, if the MATLAB function fcn1 contains the local function local_fcn1, and
fcn2 contains the local function local_fcn2, the report displays:

fcn1 > local_fcn1


fcn2 > local_fcn2

Specializations

If your MATLAB function calls the same function with different types of inputs, the code
generation report numbers these specializations in the function list on the MATLAB
code tab.

For example, if the function fcn calls the function subfcn with different types of inputs:

function y = fcn(u) %#codegen


% Specializations
y = y + subfcn(single(u));
y = y + subfcn(double(u));

22-13
22 Verify Generated C/C++ Code

The code generation report numbers the specializations in the function list:
fcn > subfcn > 1
fcn > subfcn > 2

Extrinsic Functions

The report highlights the extrinsic functions that are supported only within the
MATLAB environment.

Call Stack Information in a Report


The code generation report provides call stack information:

• On the Call stack tab.


• In the list of Calls at the top right of the report.

This list shows the calls from and to the function or method. If more than one function
calls a function, this list provides details of each call-site. Otherwise, the list is
disabled.

Call Stack Information on the Call stack Tab

To view call stack information, click the Call stack tab.

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.

The call stack displays a separate tree for each entry point function. You can easily
distinguish between shared and entry-point specific functions. If you click a shared

22-14
Code Generation Reports

function, the report highlights instances of this function. If you click an entry-point
specific function, the report highlights only that instance.

For example, in the following call stack, ezep1 and ezep2 are entry-point functions.
identity is an entry-point specific function, called only by ezep1. Functions ezep3 and
shared are shared functions.

Entry-point functions

Entry-point specific function

The Calls List

If more than one function calls a function, or if the functions calls other functions, the
Calls list provides details of each call site. To navigate between call sites, select a call
site from the Calls list. If the function is not called more than once, this list is disabled.

If you select the entry-point function ezep2 in the call stack, the Calls list displays the
other call site in ezep1.

22-15
22 Verify Generated C/C++ Code

Generated C/C++ Code in a Report


To view a list of the generated C or C++ files, click the C code tab. The code generation
report displays a list of the generated files in the Target Source Files pane. To view the
code for a file, click the file.

If you generate a MEX function, a list of support files that the code generation software
uses appears in the Interface Source Files pane of the C code tab. By default, this list
is collapsed.

When you generate an example main function, by default, the code generation report
does not include the generated example main files. If you configure code generation to
generate and compile an example main function, and then you generate code, example
main files appear in the code generation report. A list of source and header files for the
example main function appears in the Example Source Files pane of the C code tab.

Tracing Generated Code to MATLAB Source Code

You can configure codegen to generate C code that includes the MATLAB source code
as comments. In these generated comments, codegen precedes each line of source code
with a traceability tag that provides details about the location of the source code. See
“Generation of Traceable Code” on page 22-2.

For code generated using the Embedded Coder software, these traceability tags are
hyperlinks. To go the relevant line in the source code in the MATLAB editor, click the
tag.

Navigating to MATLAB Source Files for Generated C/C++ Code

To open the MATLAB source code file associated with a generated C/C++ function, click
the link at the top of the code pane.

Navigating to Type Definitions

To see the definition for a generated C/C++ data type, click the data type in the
generated C/C++ code pane.

Custom Code in a Report

The report displays custom code with color syntax highlighting. To learn what these
colors mean and how to customize color settings, see “Check Syntax as You Type”.

22-16
Code Generation Reports

Build Summary Information in a Report


To view a summary of the build results, including type of target and number of errors or
warnings, click the Summary tab.

Errors and Warnings in a Report


MATLAB Coder reports errors and warnings. If errors occur during the build, MATLAB
Coder does not generate code. The report lists the messages in the order that MATLAB
Coder detects them. It is a best practice to address the first message in the list, because
often subsequent errors and warnings are related to the first message. If the build
produces warnings, but no errors, MATLAB Coder does generate code.

The code generation report:

• Lists errors and warnings on the All Messages tab. The report lists these messages
in chronological order.
• Highlights errors and warnings on the MATLAB code pane.
• Records compilation and linking errors and warnings on the Target Build Log tab.
If the code generation software detects compilation warnings, you see a message on
the All Messages tab. The code generation software detects compilation warnings
only for MEX output or if you use a supported compiler for other types of output.
For a list of supported compilers, see http://www.mathworks.com/support/
compilers/current_release/.

Errors and Warnings in the All Messages Tab

If errors or warnings occur during the build, click the All Messages tab to view a
complete list of these messages. The code generation report marks messages as either:

Error

Warning

To locate the incorrect line of code for an error or warning, click the message in the list.
The code generation report highlights errors in the list. It highlights MATLAB code in
red and warnings in orange. To go to the error in the source file, click the line number
next to the incorrect line of code in the MATLAB code pane.

22-17
22 Verify Generated C/C++ Code

Note: You can fix errors only in the source file.

Error and Warning Information in Your MATLAB Code

If errors or warnings occur during the build, the code generation report underlines them
in your MATLAB code. The report underlines errors in red and warnings in orange. To
learn more about a particular error or warning, place your cursor over the underlined
text.

Compilation and Linking Errors and Warnings

The code generation report highlights compilation and linking errors and warnings in red
on the Target Build Log tab. For errors, the code generation report opens to the Target
Build Log tab so that you can view the build log. For warnings, the report opens to the
All Messages tab. A message instructs you to view the warnings on the Target Build
Log tab.

MATLAB Code Variables in a Report


The report provides compile-time type information for the variables and expressions
in your MATLAB code, including name, type, size, complexity, and class. It also
provides type information for fixed-point data types, including word length and fraction
length. You can use this type information to find the sources of error messages and to
understand type propagation rules.

You can view information about the variables in your MATLAB code:

• On the Variables tab, view the list.


• In your MATLAB code, place your cursor over the variable name.

In the MATLAB code, an orange variable name indicates a compile-time constant


argument to an entry-point or a specialized function. The information for a constant
argument includes the value. The information about constant arguments helps you
to understand generated function signatures. It also helps you to see when code
generation created function specializations for different constant argument values.

Variables on the Variables Tab

To view a list of the variables in your MATLAB function, click the Variables tab. The
report displays a complete list of variables in the order that they appear in the function

22-18
Code Generation Reports

that you selected on the MATLAB code tab. Clicking a variable in the list highlights
instances of that variable, and scrolls the MATLAB code pane so that you can view the
first instance.

As applicable, the report provides the following information about each variable:

• Order
• Name
• Type
• Size
• Complexity
• Class
• DataTypeMode (DT mode) — for fixed-point data types only. For more information,
see “Data Type and Scaling Properties”.
• Signed — sign information for built-in data types, signedness information for fixed-
point data types.
• Word length (WL) — for fixed-point data types only.
• Fraction length (FL) — for fixed-point data types only.

Note: For more information on viewing fixed-point data types, see “Use Fixed-Point Code
Generation Reports”.

The report displays a column only if at least one variable in the code has information in
that column. For example, if the code does not contain fixed-point data types, the report
does not display the DT mode, WL, or FL columns.
Sorting Variables on the Variables Tab

By default, the report lists the variables in the order that they appear in the selected
function.

To sort the variables, click the column headings on the Variables tab. To sort the
variables by multiple columns, hold down the Shift key when you click the column
headings.

To restore the list to the original order, click the Order column heading.

22-19
22 Verify Generated C/C++ Code

Structures on the Variables Tab

To display structure field properties, expand the structure on the Variables tab.

If you sort the variables by type, size, complexity, or class, it is possible that a structure
and its fields do not appear sequentially in the list. To restore the list to the original
order, click the Order column heading.
Variable-Size Arrays in the Variables Tab

For variable-size arrays, the Size field includes information about the computed
maximum size of the array. The size of each array dimension that varies is prefixed with
a colon :. The size of an unbounded dimension is :?.

In the following report, variables A and B are variable-size. The second dimension of A
has a maximum size of 100. The size of the second dimension of B is :?.

If you declare a variable-size array, and then 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 sizes of its dimensions do not change during
execution.

22-20
Code Generation Reports

For information about how to use the size information for variable-size arrays, see
“Variable-Size Data Definition for Code Generation” on page 7-3.
Renamed Variables in the Variables Tab

If your MATLAB function reuses a variable with a different size, type, or complexity,
the code generation software attempts to create separate, uniquely named variables. For
more information, see “Reuse the Same Variable with Different Properties” on page 5-11.
The report numbers the renamed variables in the list on the Variables tab. When you
place your cursor over a renamed variable, the report highlights only the instances of this
variable that share data type, size, and complexity.

For example, suppose that your code uses the variable t to hold a scalar double, and
reuses it outside the for-loop to hold a vector of doubles. In the list on the Variables tab,
the report displays two variables, t>1 and t>2,

Viewing Information About Variables and Expressions in Your MATLAB Function Code

To view information about a particular variable or expression in your MATLAB function


code, on the MATLAB code pane, place your cursor over the variable name or expression.
The report highlights variables and expressions in different colors:
Green, when the variable has data type information at this location in the code

For variable-size arrays, the Size field includes information on the computed maximum
size of the array. The size of each array dimension that varies is prefixed with a colon :.

22-21
22 Verify Generated C/C++ Code

Green with orange text, when a constant argument has data type and value information

When the variable is a compile-time constant argument to an entry-point or a specialized


function:

• The variable name is orange.


• The information for the variable includes the value.

If you export the value as a variable to the base workspace, you can use the Workspace
browser to view detailed information about the variable.

To export the value to the base workspace:

1 Click the Value link.


2 In the Export Constant Value dialog box, specify the Variable name.
3 Click OK.

The variable and its value appear in the Workspace browser.

Pink, when the variable has no data type information

22-22
Code Generation Reports

Purple, information about expressions

You can also view information about expressions in your MATLAB code. On the
MATLAB code pane, place your cursor over an expression. The report highlights
expressions in purple and provides more detailed information.

Red, when there is error information

Target Build Information in a Report


If the build completes, MATLAB Coder provides target build information on the Target
Build Log tab, including:

• Build folder

Clicking this link changes the MATLAB current folder to the build folder.
• Make wrapper

The batch file name that MATLAB Coder used for this build.
• Build log

If compilation or linking errors occur, the code generation report opens to the Target
Build Log tab so that you can view the build log.

22-23
22 Verify Generated C/C++ Code

Keyboard Shortcuts for a Report


You can use keyboard shortcut settings to perform actions in the code generation report.

This table lists actions that you can associate with a keyboard shortcut. The keyboard
shortcuts are defined in your MATLAB preferences. See “Define Keyboard Shortcuts”.

Action Default Keyboard Shortcut for a Windows


Platform
Zoom in Ctrl+Plus
Zoom out Ctrl+Minus
Evaluate selected MATLAB code F9
Open help for selected MATLAB code F1
Open selected MATLAB code Ctrl+D
Step backward through files that you Alt+Left
opened in the code pane
Step forward through files that you opened Alt+Right
in the code pane
Refresh F5
Search Ctrl+F

22-24
Code Generation Reports

Alternatively, you can select these actions from a context menu. To open the context
menu, right-click anywhere in the report.

This table lists keyboard shortcuts that help you navigate between panes and tabs in
the code generation report. To advance through data in the selected pane, use the Tab
key. These keyboard shortcuts override the keyboard shortcut settings in your MATLAB
preferences. See “Define Keyboard Shortcuts”.

To select Use
MATLAB code tab Ctrl+M
Call stack tab Ctrl+K
C code Tab Ctrl+C
Code Pane Ctrl+W
Summary Tab Ctrl+S
All Messages Tab Ctrl+A
Variables Tab Ctrl+V
Target Build Log Tab Ctrl+T

22-25
22 Verify Generated C/C++ Code

Searching in a Report
Use the keyboard shortcut associated with Find in your MATLAB preferences. For
example, on a Windows platform, the default keyboard shortcut for Find is Ctrl+F.

Report Limitations
The report displays information about the variables and expressions in your MATLAB
code with the following limitations:

varargin and varargout

The report does not support varargin and varargout arrays.

Loop Unrolling

The report does not display full information for unrolled loops. It displays data types of
one arbitrary iteration.

Dead Code

The report does not display information about dead code.

Structures

The report does not provide complete information about structures.

• The report does not provide information about all structure fields in the struct()
constructor.
• If a structure has a nonscalar field, and an expression accesses an element of this
field, the report does not provide information for the field.

Column Headings on the Variables Tab

If you scroll through the list of variables, the report does not display the column headings
on the Variables tab.

Multiline Matrices

On the MATLAB code pane, the report does not support selection of multiline matrices.
It supports only selection of individual lines at a time. For example, if you place your
cursor over the following matrix, you cannot select the entire matrix.

22-26
Code Generation Reports

out1 = [1 2 3;
4 5 6];
The report does support selection of single line matrices.
out1 = [1 2 3; 4 5 6];

22-27
22 Verify Generated C/C++ Code

Enable Code Generation Reports


In this section...
“Enable Code Generation Reports with the MATLAB Coder App” on page 22-28
“Enable Code Generation Reports at the Command Line” on page 22-28

Enable Code Generation Reports with the MATLAB Coder App


1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Click More Settings.
3 On the Debugging tab, select the Always create a code generation report check
box.
4 If you want the app to open the report, select the Automatically launch a report
if one is generated check box.

Enable Code Generation Reports at the Command Line


Use the codegen function -report option. To generate a standalone C/C++ static
library and code generation report for a function foo that has no input parameters, at
the MATLAB command line, enter:
codegen -config:lib -report foo

If you want the code generation or error report to automatically open, use the -
launchreport option instead of the -report option.

22-28
Run-Time Error Detection and Reporting in Standalone C/C++ Code

Run-Time Error Detection and Reporting in Standalone C/C++


Code
You can generate standalone libraries and executables that detect and report run-time
errors, such as out-of-bounds array indexing. If the generated code detects an error, it
reports the error and terminates the program.

During development, before you generate C/C++ code, it is a best practice to test the
generated code by running the MEX version of your algorithm. However, some errors
occur only on the target hardware. To detect these errors, generate the standalone C/C
++ code with run-time error detection enabled. Run-time error detection can affect the
performance of the generated code. If performance is a consideration for your application,
do not generate production code with run-time error detection enabled.

By default, run-time error detection is disabled for standalone libraries and executables.
To enable run-time error detection and reporting for standalone libraries and
executables:

• At the command line, use the code configuration property RuntimeChecks.

cfg = coder.config('lib'); % or 'dll' or 'exe'


cfg.RuntimeChecks = true;
codegen -config cfg myfunction
• In the MATLAB Coder app, in the project settings dialog box, on the Debugging
pane, select the Generate run-time error checks check box.

Run-time error detection and reporting in standalone code has these requirements and
limitations:

• The error reporting software uses fprintf to write error messages to stderr. It
uses abort to terminate the application. If fprintf and abort are not available,
you must provide them. The abort function abruptly terminates the program. If your
system supports signals, you can catch the abort signal (SIGABRT) so that you can
control the program termination.
• Error messages are in English only.
• Some error checks require double-precision support. Therefore, the hardware on
which the generated code runs must support double-precision operations.
• If the program terminates, the error detection and reporting software does not
display the run-time stack. To inspect the stack, attach a debugger. Additionally, the

22-29
22 Verify Generated C/C++ Code

error detection and reporting software does not release resources, such as allocated
memory.
• If the program terminates, the error detection and reporting software does not release
resources, such as allocated memory.
• In standalone code, the function error does not report an error and does not
terminate execution.
• In standalone code, if called with more than 1 argument, the function assert
does not report an error and does not terminate execution. If called with a single
argument, for example, assert(cond), if cond is not a constant true value, reports
an error and terminates execution.

Related Examples
• “Generate Standalone Code That Detects and Reports Run-Time Errors” on page
22-31

More About
• “Why Test MEX Functions in MATLAB?” on page 20-2

22-30
Generate Standalone Code That Detects and Reports Run-Time Errors

Generate Standalone Code That Detects and Reports Run-Time


Errors
This example shows how to generate C/C++ libraries or executables that detect and
report run-time errors such as out-of-bounds array indexing. If the generated code
detects an error, it reports a message and terminates the program. You can detect and fix
errors that occur only on the target hardware.

Write the function getelement that indexes into one structure field using the value of
the other structure field.
function y = getelement(S)
y = S.A(S.u);
end

Create a code configuration object for a standalone library or executable. For example,
create a code configuration object for a static library. Enable the code generation report.
cfg = coder.config('lib');
cfg.GenerateReport = true;

Enable generation of run-time error detection and reporting.


cfg.RuntimeChecks = true;

Define an example input that you can use to specify the properties of the input argument.
S.A = ones(2,2);
S.u = 0;

Generate code.
codegen -config cfg getelement -args {S}

To open the code generation report, click the View report link.

When the report opens, you see the generated C code. You can see the code that checks
for an error and calls a function to report the error. For example, if the code detects an
out-of-bounds array indexing error, it calls rtDynamicBoundsError to report the error
and terminate the program.
/* Include Files */
#include "rt_nonfinite.h"
#include "getelement.h"

22-31
22 Verify Generated C/C++ Code

#include "getelement_rtwutil.h"
#include <stdio.h>
#include <stdlib.h>

/* Variable Definitions */
static rtBoundsCheckInfo emlrtBCI = { 1, 4, 2, 5, "S.A", "getelement",
"C:\\coder\\runtime checks\\getelement.m", 0 };

static rtDoubleCheckInfo emlrtDCI = { 2, 5, "getelement",


"C:\\coder\\runtime checks\\getelement.m", 1 };

/* Function Definitions */

/*
* Arguments : const struct0_T *S
* Return Type : double
*/
double getelement(const struct0_T *S)
{
double d0;
int i0;
d0 = S->u;
if (d0 != (int)floor(d0)) {
rtIntegerError(d0, &emlrtDCI);
}

i0 = (int)d0;
if (!((i0 >= 1) && (i0 <= 4))) {
rtDynamicBoundsError(i0, 1, 4, &emlrtBCI);
}

return S->A[i0 - 1];


}

The error reporting software uses fprintf to write error messages to stderr. It uses
abort to terminate the application. If fprintf and abort are not available, you must
provide them. The abort function abruptly terminates the program. If your system
supports signals, you can catch the abort signal (SIGABRT) so that you can control the
program termination.

More About
• “Run-Time Error Detection and Reporting in Standalone C/C++ Code” on page 22-29

22-32
Testing Code Generated from MATLAB Code

Testing Code Generated from MATLAB Code


MATLAB Coder helps you to test your generated code.

If you use the MATLAB Coder app to generate a MEX function, you can test the MEX
function in the app. If you use codegen to generate a MEX function, test the MEX
function by using coder.runTest.

If you have Embedded Coder, you can verify the numerical behavior of generated C/C++
code by using software-in-the-loop (SIL) or processor-in-the-loop (PIL) execution. You can
also produce a profile of execution times.

More About
• “Verify MEX Functions in the MATLAB Coder App” on page 20-8
• “Verify MEX Functions at the Command Line” on page 20-9
• “Code Verification Through Software-in-the-Loop and Processor-in-the-Loop
Execution”
• “Execution Time Profiling for SIL and PIL”

22-33
23

Code Replacement for MATLAB Code

• “What Is Code Replacement?” on page 23-2


• “Code Replacement Libraries” on page 23-4
• “Code Replacement Terminology” on page 23-6
• “Code Replacement Limitations” on page 23-9
• “Replace Code Generated from MATLAB Code” on page 23-10
• “Choose a Code Replacement Library” on page 23-12
23 Code Replacement for MATLAB Code

What Is Code Replacement?


Code replacement is a technique to change the code that the code generator produces for
functions and operators to meet application code requirements. For example, you can
replace generated code to meet requirements such as:

• Optimization for a specific run-time environment, including, but not limited to,
specific target hardware.
• Integration with existing application code.
• Compliance with a standard, such as AUTOSAR.
• Modification of code behavior, such as enabling or disabling nonfinite or inline
support.
• Application- or project-specific code requirements, such as:

• Elimination of math.h.
• Elimination of system header files.
• Elimination of calls to memcpy or memset.
• Use of BLAS.
• Use of a specific BLAS.

To apply this technique, configure the code generator to apply a code replacement
library (CRL) during code generation. By default, the code generator does not apply a
code replacement library. You can choose from the following libraries that MathWorks
provides:

• GNU C99 extensions—GNU1 gcc math library, which provides C99 extensions as
defined by compiler option -std=gnu99.
• AUTOSAR 4.0—Produces code that more closely aligns with the AUTOSAR standard.
Requires an Embedded Coder license.
• Intel IPP for x86-64 (Windows)—Generates calls to the Intel® Performance Primitives
(IPP) library for the x86-64 Windows platform.
• Intel IPP/SSE for x86-64 (Windows)—Generates calls to the IPP and Streaming SIMD
Extensions (SSE) libraries for the x86-64 Windows platform.
• Intel IPP for x86-64 (Windows using MinGW compiler)—Generates calls to the IPP
library for the x86-64 Windows platform and MinGW compiler.

1. GNU is a registered trademark of the Free Software Foundation.

23-2
What Is Code Replacement?

• Intel IPP/SSE for x86-64 (Windows using MinGW compiler)—Generates calls to the
IPP and SSE libraries for the x86-64 Windows platform and MinGW compiler.
• Intel IPP for x86/Pentium (Windows)—Generates calls to the IPP library for the x86/
Pentium Windows platform.
• Intel IPP/SSE for x86/Pentium (Windows)—Generates calls to the Intel Performance
IPP and SSE libraries for the x86/Pentium Windows platform.
• Intel IPP for x86-64 (Linux)—Generates calls to the IPP library for the x86-64 Linux
platform.
• Intel IPP/SSE with GNU99 extensions for x86-64 (Linux)—Generates calls to the
GNU libraries for IPP and SSE, with GNU C99 extensions, for the x86-64 Linux
platform.

Libraries that include GNU99 extensions are intended for use with the GCC compiler. If
use one of those libraries with another compiler, generated code might not compile.

Depending on the product licenses that you have, other libraries might be available . If
you have an Embedded Coder license, you can view and choose from other libraries and
you can create custom code replacement libraries.

Related Examples
• “Replace Code Generated from MATLAB Code” on page 23-10
• “Choose a Code Replacement Library” on page 23-12

More About
• “Code Replacement Libraries” on page 23-4
• “Code Replacement Terminology” on page 23-6
• “Code Replacement Limitations” on page 23-9

23-3
23 Code Replacement for MATLAB Code

Code Replacement Libraries


A code replacement library consists of one or more code replacement tables that specify
application-specific implementations of functions and operators. For example, a library
for a specific embedded processor specifies function and operator replacements that
optimize generated code for that processor.

A code replacement table contains one or more code replacement entries, with each entry
representing a potential replacement for a function or operator. Each entry maps a
conceptual representation of a function or operator to an implementation representation
and priority.

Table Entry Description


Component
Conceptual Identifies the table entry and contains match criteria for the code
representation generator. Consists of:

• Function name or a key. The function name identifies most


functions. For operators and some functions, a string called
a key identifies a function or operator. For example, function
name 'cos' and operator key 'RTW_OP_ADD'.
• Conceptual arguments that observe code generator naming
('y1', 'u1', 'u2', ...), with corresponding I/O types (output or
input) and data types.
• Other attributes, such as an algorithm, fixed-point saturation,
and rounding modes, which identify matching criteria for the
function or operator.

23-4
Code Replacement Libraries

Table Entry Description


Component
Implementation Specifies replacement code. Consists of:
representation
• Function name. For example, 'cos_dbl' or 'u8_add_u8_u8'.
• Implementation arguments, with corresponding I/O types
(output or input) and data types.
• Parameters that provide additional implementation details,
such as header and source file names and paths of build
resources.
Priority Defines the entry priority relative to other entries in the table. The
value can range from 0 to 100, with 0 being the highest priority. If
multiple entries have the same priority, the code generator uses the
first match with that priority.

When the code generator looks for a match in a code replacement library, it creates and
populates a call site object with the function or operator conceptual representation. If
a match exists, the code generator uses the matched code replacement entry populated
with the implementation representation and uses it to generate code.

The code generator searches the tables in a code replacement library for a match in the
order that the tables appear in the library. If the code generator finds multiple matches
within a table, the priority determines the match. The code generator uses a higher-
priority entry over a similar entry with a lower priority.

Related Examples
• “Replace Code Generated from MATLAB Code” on page 23-10
• “Choose a Code Replacement Library” on page 23-12

More About
• “What Is Code Replacement?” on page 23-2
• “Code Replacement Terminology” on page 23-6

23-5
23 Code Replacement for MATLAB Code

Code Replacement Terminology


Term Definition
Cache hit A code replacement entry for a function or operator,
defined in the specified code replacement library,
for which the code generator finds a match.
Cache miss A conceptual representation of a function or
operator for which the code generator does not find
a match.
Call site object Conceptual representation of a function or operator
that the code generator uses when it encounters
a call site for a function or operator. The code
generator uses the object to query the code
replacement library for a conceptual representation
match. If a match exists, the code generator returns
a code replacement object, fully populated with
the conceptual representation, implementation
representation, and priority, and uses that object to
generate replacement code.
Code replacement library One or more code replacement tables that specify
application-specific implementations of functions
and operators. When configured to use a code
replacement library, the code generator uses
criteria defined in the library to search for matches.
If a match is found, the code generator replaces
code that it generates by default with application-
specific code defined in the library.
Code replacement table One or more code replacement table entries.
Provides a way to group related or shared entries
for use in different libraries.
Code replacement entry Represents a potential replacement for a function
or operator. Maps a conceptual representation
of a function or operator to an implementation
representation and priority.
Conceptual argument Represents an input or output argument for a
function or operator being replaced. Conceptual
arguments observe naming conventions ('y1',

23-6
Code Replacement Terminology

Term Definition
'u1', 'u2', ...) and data types familiar to the code
generator.
Conceptual representation Represents match criteria that the code generator
uses to qualify functions and operators for
replacement. Consists of:

• Function or operator name or key


• Conceptual arguments with type, dimension,
and complexity specification for inputs and
output

Attributes, such as an algorithm and fixed-point
saturation and rounding modes
Implementation argument Represents an input or output argument for a C
or C++ replacement function. Implementation
arguments observe C/C++ name and data type
specifications.
Implementation representation Specifies C or C++ replacement function prototype.
Consists of:

• Function name (for example, 'cos_dbl' or


'u8_add_u8_u8')
• Implementation arguments specifying type,
type qualifiers, and complexity for the function
inputs and output
• Parameters that provide build information, such
as header and source file names and paths of
build resources and compile and link flags
Key A string that identifies a function or operator
that is being replaced. A function name or key
appears in the conceptual representation of a code
replacement entry. The key RTW_OP_ADD identifies
the addition operator.

23-7
23 Code Replacement for MATLAB Code

Term Definition
Priority Defines the match priority for a code replacement
entry relative to other entries, which have the
same name and conceptual argument list, within
a code replacement library. The priority can
range from 0 to 100, with 0 being the highest
priority. The default is 100. If a library provides
two implementations for a function or operator, the
implementation with the higher priority shadows
the one with the lower priority.

More About
• “What Is Code Replacement?” on page 23-2
• “Code Replacement Libraries” on page 23-4

23-8
Code Replacement Limitations

Code Replacement Limitations


Code replacement verification — It is possible that code replacement behaves differently
than you expect. For example, data types that you observe in code generator input might
not match what the code generator uses as intermediate data types during an operation.
Verify code replacements by examining generated code.

Related Examples
• “Replace Code Generated from MATLAB Code” on page 23-10

More About
• “Code Replacement Libraries” on page 23-4

23-9
23 Code Replacement for MATLAB Code

Replace Code Generated from MATLAB Code


This example shows how to replace generated code using a code replacement library.
Code replacement is a technique for changing the code that the code generator produces
for functions and operators to meet application code requirements.

Prepare for Code Replacement

1 Make sure that you have installed required software. Required software is:

• MATLAB
• MATLAB Coder
• C compiler

Some code replacement libraries available in your development environment require


Embedded Coder.

For instructions on installing MathWorks products, see the MATLAB installation


documentation. If you have installed MATLAB and want to see which other
MathWorks products are installed, in the MATLAB Command Window, enter ver.
2 Identify an existing MATLAB function or create a new MATLAB function for which
you want the code generator to replace code.

Choose a Code Replacement Library

If you are not sure which library to use, explore available libraries.

Configure Code Generator To Use Code Replacement Library

1 Configure the code generator to apply a code replacement library during code
generation for the MATLAB function. Do one of the following:

• In a project, on the Custom Code tab, set the Code replacement library
parameter.
• In a code configuration object, set the CodeReplacementLibrary parameter.
2 Configure the code generator to produce only code. Before you build an executable,
verify your code replacements. Do one of the following:

• In a project, in the Generate dialog box, select the Generate code only check
box.

23-10
Replace Code Generated from MATLAB Code

• In a code configuration object, set the GenCodeOnly parameter.

Include Code Replacement Information In Code Generation Report

If you have an Embedded Coder license, you can configure the code generator to include
a code replacement section in the code generation report. The additional information
helps you verify code replacements. For more information, see “Review and Test Code
Replacements” in the Embedded Coder documentation.

Generate Replacement Code

Generate C/C++ code from the MATLAB code. If you configured the code generator to
produce a report, generate a code generation report. For example, in the MATLAB Coder
app, on the Generate Code page, click Generate. Or, at the command prompt, enter:
codegen -report myFunction -args {5} -config cfg

The code generator produces the code and displays the report.

Verify Code Replacements

Verify code replacements by examining the generated code. Code replacement can
sometimes behave differently than you expect. For example, data types that you
observe in the code generator input might not match what the code generator uses as
intermediate data types during an operation.

Related Examples
• “Choose a Code Replacement Library” on page 23-12
• “Configure Build Settings” on page 21-26

More About
• “What Is Code Replacement?” on page 23-2
• “Code Replacement Libraries” on page 23-4
• “Code Replacement Terminology” on page 23-6
• “Code Replacement Limitations” on page 23-9

External Websites
• Supported Compilers

23-11
23 Code Replacement for MATLAB Code

Choose a Code Replacement Library


In this section...
“About Choosing a Code Replacement Library” on page 23-12
“Explore Available Code Replacement Libraries” on page 23-12
“Explore Code Replacement Library Contents” on page 23-12

About Choosing a Code Replacement Library


By default, the code generator does not use a code replacement library.

If you are considering using a code replacement library:

1 Explore available libraries. Identify one that best meets your application needs.

• Consider the lists of application code replacement requirements and libraries that
MathWorks provides in “What Is Code Replacement?” on page 23-2.
• See “Explore Available Code Replacement Libraries” on page 23-12.
2 Explore the contents of the library. See “Explore Code Replacement Library
Contents” on page 23-12.

If you do not find a suitable library and you have an Embedded Coder license, you can
create a custom code replacement library. For more information, see “What Is Code
Replacement Customization?” in the Embedded Coder documentation.

Explore Available Code Replacement Libraries


You can select the code replacement library to use for code generation in a project, on the
Custom Code tab, by setting the Code replacement library parameter. Alternatively,
in a code configuration object, set the CodeReplacementLibrary parameter.

Explore Code Replacement Library Contents


Use the Code Replacement Viewer to explore the content of a code replacement library.

1 At the command prompt, type crviewer.


>> crviewer

23-12
Choose a Code Replacement Library

The viewer opens. To view the content of a specific library, specify the name of the
library as an argument in single quotes. For example:
>> crviewer('GNU C99 extensions')

2 In the left pane, select the name of a library. The viewer displays information about
the library in the right pane.
3 In the left pane, expand the library, explore the list of tables it contains, and select a
table from the list. In the middle pane, the viewer displays the function and operator
entries that are in that table, along with abbreviated information for each entry.
4 In the middle pane, select a function or operator. The viewer displays information
from the table entry in the right pane.

If you select an operator entry that specifies net slope fixed-point parameters
(instantiated from entry class RTW.TflCOperationEntryGenerator or
RTW.TflCOperationEntryGenerator_NetSlope), the viewer displays an
additional tab that shows fixed-point settings.

See Code Replacement Viewer for details on what the viewer displays.

Related Examples
• “Replace Code Generated from MATLAB Code” on page 23-10

More About
• “Code Replacement Libraries” on page 23-4
• “Code Replacement Terminology” on page 23-6
• “Code Replacement Limitations” on page 23-9

23-13
24

Custom Toolchain Registration

• “Custom Toolchain Registration” on page 24-2


• “About coder.make.ToolchainInfo” on page 24-6
• “Create and Edit Toolchain Definition File” on page 24-8
• “Toolchain Definition File with Commentary” on page 24-10
• “Create and Validate ToolchainInfo Object” on page 24-16
• “Register the Custom Toolchain” on page 24-17
• “Use the Custom Toolchain” on page 24-19
• “Troubleshooting Custom Toolchain Validation” on page 24-20
• “Prevent Circular Data Dependencies with One-Pass or Single-Pass Linkers” on page
24-24
24 Custom Toolchain Registration

Custom Toolchain Registration

In this section...
“What Is a Custom Toolchain?” on page 24-2
“What Is a Factory Toolchain?” on page 24-2
“What is a Toolchain Definition?” on page 24-3
“Key Terms” on page 24-4
“Typical Workflow” on page 24-4

What Is a Custom Toolchain?


You can add support for software build tools to MATLAB Coder software. For example,
you can add support for a third-party compiler/linker/archiver (toolchain) to your
MATLAB Coder software. This customization can be useful when the added toolchain
has support and optimizations for a specific type of processor or hardware. These added
toolchains are called custom toolchains.

What Is a Factory Toolchain?


MATLAB Coder software includes factory-default support for a set of toolchains. These
toolchains are called factory toolchains to distinguish them from custom toolchains. If
you install factory toolchains on your host computer, MATLAB Coder can automatically
detect and use them. Support for factory toolchains depends on the host operating
system. Toolchains are identified by the compiler in the toolchain. A complete list of
supported toolchains (compilers) is available at http://www.mathworks.com/support/
compilers/.

24-2
Custom Toolchain Registration

What is a Toolchain Definition?

A toolchain definition provides MATLAB Coder software with information about the
software build tools, such as the compiler, linker, archiver. MATLAB Coder software
uses this information, along with a configuration object or project, to build the generated
code. This approach can be used when generating static libraries, dynamic libraries, and
executables. MEX-file generation uses a different approach. To specify which compiler to
use for MEX-function generation, see “Setting Up the C or C++ Compiler”.

MATLAB Coder software comes with a set of registered factory toolchain definitions.
You can create and register custom toolchain definitions. You can customize and manage
toolchain definitions. You can share custom toolchain definitions with others running
MATLAB Coder software.

If you install toolchain software for one of the factory toolchains, MATLAB Coder
can automatically detect and use the toolchain software. For more information about

24-3
24 Custom Toolchain Registration

factory toolchains in MATLAB Coder software, see http://www.mathworks.com/support/


compilers/.

Key Terms
It is helpful to understand the following concepts:

• Toolchain — Software that can create a binary executable and libraries from source
code. A toolchain can include:

• Prebuild tools that set up the environment


• Build tools, such as an Assembler, C compiler, C++ Compiler, Linker, Archiver,
that build a binary executable from source code
• Postbuild tools that download and run the executable on the hardware, and clean
up the environment
• Custom toolchain — A toolchain that you define and register for use by MATLAB
Coder software
• Factory toolchains — Toolchains that are predefined and registered in MATLAB
Coder software
• Registered toolchains — The sum of custom and factory toolchain definitions
registered in MATLAB Coder software
• ToolchainInfo object — An instance of the coder.make.ToolchainInfo class that
contains a toolchain definition. You save the ToolchainInfo object as a MAT file,
register the file with MATLAB Coder. Then you can configure MATLAB Coder to load
the ToolchainInfo object during code generation.
• Toolchain definition file — A MATLAB file that defines the properties of a toolchain.
You use this file to create a ToolchainInfo object.

Note: This documentation also refers to the ToolchainInfo object as a


coder.make.ToolchainInfo object.

Typical Workflow
The typical workflow for creating and using a custom toolchain definition is:

1 “Create and Edit Toolchain Definition File” on page 24-8

24-4
Custom Toolchain Registration

a Create a toolchain definition file that returns a coder.make.ToolchainInfo


object.
b Update the file with information about the custom toolchain.
2 “Create and Validate ToolchainInfo Object” on page 24-16

a Use the toolchain definition file to create a ToolchainInfo object in the


MATLAB workspace.
b Validate the ToolchainInfo object.
c Fix validation issues by updating the toolchain definition file, and creating/
validating the updated ToolchainInfo object.
d Create a valid ToolchainInfo object and save it to a MAT-file.
3 “Register the Custom Toolchain” on page 24-17

a Create an rtwTargetInfo.m file and update it with information about the MAT-
file.
b Register the custom toolchain in MATLAB Coder software using the
rtwTargetInfo.m file.
4 “Use the Custom Toolchain” on page 24-19

a Configure MATLAB Coder software to use the custom toolchain.


b Build and run an executable using the custom toolchain.

This workflow requires an iterative approach, with multiple cycles to arrive at a


finished version of the custom ToolchainInfo object. You will need access to detailed
information about the custom toolchain.

For a tutorial example of this workflow, see “Adding a Custom Toolchain”.

For more information about the ToolchainInfo object, see “About


coder.make.ToolchainInfo” on page 24-6.

24-5
24 Custom Toolchain Registration

About coder.make.ToolchainInfo
The following properties in coder.make.ToolchainInfo represent your custom
toolchain:

• coder.make.ToolchainInfo.PrebuildTools – Tools used before compiling the


source files into object files.
• coder.make.ToolchainInfo.BuildTools – Tools used for compiling source files
and linking/archiving them to form a binary.
• coder.make.ToolchainInfo.PostbuildTools – Tools used after the linker/
archiver is invoked.
• coder.make.ToolchainInfo.BuilderApplication – Tools used to call the
PrebuildTools, BuildTools, and PostbuildTools. For example: gmake, nmake.

Each configuration in coder.make.ToolchainInfo.BuildConfigurations


applies a set of options to the build tools specified by
coder.make.ToolchainInfo.BuildTools. By default, these configurations alter the
way the assembler, compiler, linker, and archiver operate to produce faster builds, faster
runs, and debug.

If you instantiate coder.make.ToolchainInfo to support building sources that involve


assembler, C, or C++ files, the coder.make.ToolchainInfo object contains the default
set of build tools shown here.

24-6
About coder.make.ToolchainInfo

24-7
24 Custom Toolchain Registration

Create and Edit Toolchain Definition File


This example shows how to create a toolchain definition file by copying and pasting an
example file. You then update the relevant elements, and add or remove other elements
as needed for your custom toolchain. This is the first step in the typical workflow for
creating and using a custom toolchain definition. For more information about the
workflow, see “Typical Workflow” on page 24-4.

1 Review the list of registered toolchains. In the MATLAB Command Window, enter:

coder.make.getToolchains

The resulting output includes the list of factory toolchains for your host computer
environment, and previously-registered custom toolchains. For example, the
following output shows the factory toolchains for a host computer running 64-bit
Windows and no custom toolchains.

ans =

'Microsoft Visual C++ 2012 v11.0 | nmake (64-bit Windows)'


'Microsoft Visual C++ 2010 v10.0 | nmake (64-bit Windows)'
'Microsoft Visual C++ 2008 v9.0 | nmake (64-bit Windows)'
'Microsoft Windows SDK v7.1 | nmake (64-bit Windows)'
2 Create the folder of example files from the “Adding a Custom Toolchain” example by
entering the following command in the MATLAB Command Window:

coderdemo_setup('coderdemo_intel_compiler');
3 Copy the example toolchain definition file to another location and rename it. For
example:

copyfile('intel_tc.m','../newtoolchn_tc.m')
4 Open the new toolchain definition file in the MATLAB Editor. For example:

cd ../
edit newtoolchn_tc.m
5 Edit the contents of the new toolchain definition file, providing information for the
custom toolchain.

For expanded commentary on an example toolchain definition file, see “Toolchain


Definition File with Commentary” on page 24-10.

24-8
Create and Edit Toolchain Definition File

For reference information about the class attributes and methods you can use in the
toolchain definition file, see coder.make.ToolchainInfo.
6 Save your changes to the toolchain definition file.

Next, create and validate a coder.make.ToolchainInfo object from the toolchain


definition file, as described in “Create and Validate ToolchainInfo Object” on page
24-16

24-9
24 Custom Toolchain Registration

Toolchain Definition File with Commentary


In this section...
“Steps Involved in Writing a Toolchain Definition File” on page 24-10
“Write a Function That Creates a ToolchainInfo Object” on page 24-10
“Setup” on page 24-11
“Macros” on page 24-11
“C Compiler” on page 24-12
“C++ Compiler” on page 24-12
“Linker” on page 24-13
“Archiver” on page 24-13
“Builder” on page 24-14
“Build Configurations” on page 24-14

Steps Involved in Writing a Toolchain Definition File


This example shows how to create a toolchain definition file and explains each of the
steps involved. The example is based on the definition file used in “Adding a Custom
Toolchain”. For more information about the workflow, see “Typical Workflow” on page
24-4.

Write a Function That Creates a ToolchainInfo Object


function tc = intel_tc
% INTEL_TC Creates a Intel v12.1 ToolchainInfo object.
% This can be used as a template to add other toolchains on Windows.

% Copyright 2012 The MathWorks,Inc.

tc = coder.make.ToolchainInfo('BuildArtifact','nmake makefile');
tc.Name = 'Intel v12.1 | nmake makefile (64-bit Windows)';
tc.Platform = 'win64';
tc.SupportedVersion = '12.1';

tc.addAttribute('TransformPathsWithSpaces');
tc.addAttribute('RequiresCommandFile');
tc.addAttribute('RequiresBatchFile');

The preceding code:

• Defines a function, intel_tc, that creates a coder.make.ToolchainInfo object


and assigns it to a handle, tc.

24-10
Toolchain Definition File with Commentary

• Overrides the BuildArtifact property to create a makefile for nmake instead of for
gmake.
• Assigns values to the Name, Platform, and SupportedVersion properties for
informational and display purposes.
• Adds three custom attributes to Attributes property that are required by this
toolchain.
• 'TransformPathsWithSpaces' converts paths that contain spaces to short
Windows paths.
• 'RequiresCommandFile' generates a linker command file that calls the linker. This
avoids problems with calls that exceed the command line limit of 256 characters.
• 'RequiresBatchFile' creates a .bat file that calls the builder application.

Setup
% ------------------------------
% Setup
% ------------------------------
% Below we are using %ICPP_COMPILER12% as root folder where Intel Compiler is
% installed. You can either set an environment variable or give full path to the
% compilervars.bat file
tc.ShellSetup{1} = 'call %ICPP_COMPILER12%\bin\compilervars.bat intel64';

The preceding code:

• Assigns a system call to the ShellSetup property.


• The coder.make.ToolchainInfo.setup method runs these system calls before it
runs tools specified by PrebuildTools property.
• Calls compilervars.bat, which is shipped with the Intel compilers, to get the set of
environment variables for Intel compiler and linkers.

Macros
% ------------------------------
% Macros
% ------------------------------
tc.addMacro('MW_EXTERNLIB_DIR',['$(MATLAB_ROOT)\extern\lib\' tc.Platform '\microsoft']);
tc.addMacro('MW_LIB_DIR',['$(MATLAB_ROOT)\lib\' tc.Platform]);
tc.addMacro('CFLAGS_ADDITIONAL','-D_CRT_SECURE_NO_WARNINGS');
tc.addMacro('CPPFLAGS_ADDITIONAL','-EHs -D_CRT_SECURE_NO_WARNINGS');
tc.addMacro('LIBS_TOOLCHAIN','$(conlibs)');
tc.addMacro('CVARSFLAG','');

tc.addIntrinsicMacros({'ldebug','conflags','cflags'});

24-11
24 Custom Toolchain Registration

The preceding code:

• Uses coder.make.ToolchainInfo.addMacro method to define macros and assign


values to them.
• Uses coder.make.ToolchainInfo.addIntrinsicMacros to define macros whose
values are specified by the toolchain, outside the scope of your MathWorks software.

C Compiler
% ------------------------------
% C Compiler
% ------------------------------

tool = tc.getBuildTool('C Compiler');

tool.setName('Intel C Compiler');
tool.setCommand('icl');
tool.setPath('');

tool.setDirective('IncludeSearchPath','-I');
tool.setDirective('PreprocessorDefine','-D');
tool.setDirective('OutputFlag','-Fo');
tool.setDirective('Debug','-Zi');

tool.setFileExtension('Source','.c');
tool.setFileExtension('Header','.h');
tool.setFileExtension('Object','.obj');

tool.setCommandPattern('|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<||>OUTPUT<|');

The preceding code:

• Creates a build tool object for the C compiler


• Assigns values to the build tool object properties
• Creates directives and file extensions using name-value pairs
• Sets a command pattern.
• You can use setCommandPattern method to control the use of space characters in
commands. For example, the two bars in OUTPUT_FLAG<||>OUTPUT do not permit a
space character between the output flag and the output.

C++ Compiler
% ------------------------------
% C++ Compiler
% ------------------------------

tool = tc.getBuildTool('C++ Compiler');

24-12
Toolchain Definition File with Commentary

tool.setName('Intel C++ Compiler');


tool.setCommand('icl');
tool.setPath('');

tool.setDirective('IncludeSearchPath','-I');
tool.setDirective('PreprocessorDefine','-D');
tool.setDirective('OutputFlag','-Fo');
tool.setDirective('Debug','-Zi');

tool.setFileExtension('Source','.cpp');
tool.setFileExtension('Header','.hpp');
tool.setFileExtension('Object','.obj');

tool.setCommandPattern('|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<||>OUTPUT<|');

The preceding code:

• Creates a build tool object for the C++ compiler


• Is very similar to the build tool object for the C compiler

Linker
% ------------------------------
% Linker
% ------------------------------

tool = tc.getBuildTool('Linker');

tool.setName('Intel C/C++ Linker');


tool.setCommand('xilink');
tool.setPath('');

tool.setDirective('Library','-L');
tool.setDirective('LibrarySearchPath','-I');
tool.setDirective('OutputFlag','-out:');
tool.setDirective('Debug','');

tool.setFileExtension('Executable','.exe');
tool.setFileExtension('Shared Library','.dll');

tool.DerivedFileExtensions = horzcat(tool.DerivedFileExtensions,{ ...


['_' tc.Platform '.lib'],...
['_' tc.Platform '.exp']});

tool.setCommandPattern('|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<||>OUTPUT<|');

The preceding code:

• Creates a build tool object for the linker


• Assigns values to the coder.make.BuildTool.DerivedFileExtensions

Archiver
% ------------------------------

24-13
24 Custom Toolchain Registration

% Archiver
% ------------------------------

tool = tc.getBuildTool('Archiver');

tool.setName('Intel C/C++ Archiver');


tool.setCommand('xilib');
tool.setPath('');

tool.setDirective('OutputFlag','-out:');

tool.setFileExtension('Static Library','.lib');

tool.setCommandPattern('|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<||>OUTPUT<|');

The preceding code:

• Creates a build tool object for the archiver.

Builder
% ------------------------------
% Builder
% ------------------------------

tc.setBuilderApplication(tc.Platform);

The preceding code:

• Gives the value of coder.make.ToolchainInfo.Platform as the argument for


setting the value of BuilderApplication. This sets the default values of the builder
application based on the platform. For example, when Platform is win64, this line
sets the delete command to 'del'; the display command to 'echo', the file separator
to '\', and the include directive to '!include'.

Build Configurations
% --------------------------------------------
% BUILD CONFIGURATIONS
% --------------------------------------------

optimsOffOpts = {'/c /Od'};


optimsOnOpts = {'/c /O2'};
cCompilerOpts = '$(cflags) $(CVARSFLAG) $(CFLAGS_ADDITIONAL)';
cppCompilerOpts = '$(cflags) $(CVARSFLAG) $(CPPFLAGS_ADDITIONAL)';
linkerOpts = {'$(ldebug) $(conflags) $(LIBS_TOOLCHAIN)'};
sharedLinkerOpts = horzcat(linkerOpts,'-dll -def:$(DEF_FILE)');
archiverOpts = {'/nologo'};

% Get the debug flag per build tool


debugFlag.CCompiler = '$(CDEBUG)';
debugFlag.CppCompiler = '$(CPPDEBUG)';
debugFlag.Linker = '$(LDDEBUG)';

24-14
Toolchain Definition File with Commentary

debugFlag.Archiver = '$(ARDEBUG)';

cfg = tc.getBuildConfiguration('Faster Builds');


cfg.setOption('C Compiler',horzcat(cCompilerOpts,optimsOffOpts));
cfg.setOption('C++ Compiler',horzcat(cppCompilerOpts,optimsOffOpts));
cfg.setOption('Linker',linkerOpts);
cfg.setOption('Shared Library Linker',sharedLinkerOpts);
cfg.setOption('Archiver',archiverOpts);

cfg = tc.getBuildConfiguration('Faster Runs');


cfg.setOption('C Compiler',horzcat(cCompilerOpts,optimsOnOpts));
cfg.setOption('C++ Compiler',horzcat(cppCompilerOpts,optimsOnOpts));
cfg.setOption('Linker',linkerOpts);
cfg.setOption('Shared Library Linker',sharedLinkerOpts);
cfg.setOption('Archiver',archiverOpts);

cfg = tc.getBuildConfiguration('Debug');
cfg.setOption('C Compiler',horzcat(cCompilerOpts,optimsOffOpts,debugFlag.CCompiler));
cfg.setOption ...
('C++ Compiler',horzcat(cppCompilerOpts,optimsOffOpts,debugFlag.CppCompiler));
cfg.setOption('Linker',horzcat(linkerOpts,debugFlag.Linker));
cfg.setOption('Shared Library Linker',horzcat(sharedLinkerOpts,debugFlag.Linker));
cfg.setOption('Archiver',horzcat(archiverOpts,debugFlag.Archiver));

tc.setBuildConfigurationOption('all','Download','');
tc.setBuildConfigurationOption('all','Execute','');
tc.setBuildConfigurationOption('all','Make Tool','-f $(MAKEFILE)');

The preceding code:

• Creates each build configuration object.


• Sets the value of each option for a given build configuration object.

24-15
24 Custom Toolchain Registration

Create and Validate ToolchainInfo Object


This example shows how to create and validate a coder.make.ToolchainInfo object from
the toolchain definition file.

Before you create and validate a ToolchainInfo object, create and edit a toolchain
definition file, as described in “Create and Edit Toolchain Definition File” on page 24-8.

1 Use the function defined by the toolchain definition file to create a


coder.make.ToolchainInfo object and assign the object to a handle. For
example, the MATLAB Command Window, enter:
tc = newtoolchn_tc
2 Use the coder.make.ToolchainInfo.validate method with the
coder.make.ToolchainInfo object. For example, enter:

tc.validate

If the coder.make.ToolchainInfo object contains errors, the validation method


displays error messages in the MATLAB Command Window.
3 Search the toolchain definition file for items named in the error message (without
quotes) and update the values.
4 Repeat the process of creating and validating the ToolchainInfo object until there
are no more errors.

Next, register the custom toolchain, as described in “Register the Custom Toolchain” on
page 24-17.

For more information, see “Troubleshooting Custom Toolchain Validation” on page


24-20.

24-16
Register the Custom Toolchain

Register the Custom Toolchain


Before you register the custom toolchain, create and validate the ToolchainInfo object,
as described in “Create and Validate ToolchainInfo Object” on page 24-16.

1 Use the save function to create a MATLAB-formatted binary file (MAT-file) from
the coder.make.ToolchainInfo object in the MATLAB workspace variables. For
example, enter:

save newtoolchn_tc tc

The new .mat file appears in the Current Folder.


2 Create a new MATLAB function called rtwTargetInfo.m.
3 Copy and paste the following text into rtwTargetInfo.m:
function rtwTargetInfo(tr)
% RTWTARGETINFO Target info callback

tr.registerTargetInfo(@loc_createToolchain);

end

% -------------------------------------------------------------------------
% Create the ToolchainInfoRegistry entries
% -------------------------------------------------------------------------
function config = loc_createToolchain

config(1) = coder.make.ToolchainInfoRegistry;
config(1).Name = '<mytoolchain v#.#> | <buildartifact (platform)>';
config(1).FileName = fullfile('<yourdir>','<mytoolchain_tc.mat>');
config(1).TargetHWDeviceType = {'<devicetype>'};
config(1).Platform = {'<win64>'};

% To register more custom toolchains:


% 1) Copy and paste the five preceding 'config' lines.
% 2) Increment the index of config().
% 3) Replace the values between angle brackets.
% 4) Remove the angle brackets.

end

4 Replace the items between angle brackets with real values, and remove the angle
brackets:

• Name — Provide a unique name for the toolchain definition file using the
recommended format: name, version number, build artifact, and platform.
• FileName — The full path and name of the MAT-file.
• TargetHWDeviceType — The platform or platforms supported by the custom
toolchain.

24-17
24 Custom Toolchain Registration

• Platform — The host operating system supported by the custom toolchain. For
all platforms, use the following wildcard: '*'

For more information, refer to the corresponding ToolchainInfo properties in


“Properties”.

Here are some example entries for an Intel toolchain that uses nmake, based on
“Adding a Custom Toolchain”:
config(1) = coder.make.ToolchainInfoRegistry;
config(1).Name = 'Intel v12.1 | nmake makefile (64-bit Windows)';
config(1).FileName = fullfile(fileparts(mfilename('fullpath')),'intel_tc.mat');
config(1).TargetHWDeviceType = {'ARM9','ARM10','ARM11'};
config(1).Platform = {computer('arch')};

5 Save the new rtwTargetInfo.m file to a folder that is on the MATLAB path.
6 List all of the rtwTargetInfo.m files on the MATLAB path. Using the MATLAB
Command Window, enter:
which -all rtwTargetInfo
7 Verify that the rtwTargetInfo.m file you just created appears in the list of files.
8 Reset TargetRegistry so it picks up the custom toolchain from the
rtwTargetInfo.m file:

RTW.TargetRegistry.getInstance('reset');

Next, use the custom toolchain, as described in “Use the Custom Toolchain” on page
24-19.

24-18
Use the Custom Toolchain

Use the Custom Toolchain


You can use a custom toolchain when generating a static or dynamic library or an
executable. You cannot use one to generate MEX functions. To specify which compiler to
use for MEX-function generation, see “Setting Up the C or C++ Compiler”).

Before using the custom toolchain, register the custom toolchain, as described in
“Register the Custom Toolchain” on page 24-17.

1 Use coder.config to create a configuration object. For example:

cfg = coder.config('exe');
2 Get the value of config(end).Name from the rtwTargetInfo.m file. Then assign
that value to the cfg.Toolchain property:

cfg.Toolchain = 'mytoolchain v#.#' | 'buildartifact (platform)'

With the “Adding a Custom Toolchain” example, this would look like:
cfg.Toolchain = 'Intel v12.1 | nmake makefile (64-bit Windows)';

3 Perform other steps required to generate code, as described in “Deployment”. For


example, specify the path and file name of the source code:
cfg.CustomSource = 'filename_main.c';
cfg.CustomInclude = pwd;
4 When you generate code using the codegen function, specify the configuration object
that uses the custom toolchain. For example:
codegen -config cfg filename

You have completed the full workflow of creating and using a custom toolchain described
in “Custom Toolchain Registration” on page 24-2.

24-19
24 Custom Toolchain Registration

Troubleshooting Custom Toolchain Validation


In this section...
“Build Tool Command Path Incorrect” on page 24-20
“Build Tool Not in System Path” on page 24-20
“Tool Path Does Not Exist” on page 24-21
“Unsupported Platform” on page 24-21
“Toolchain is Not installed” on page 24-22
“Project or Configuration is Using the Template Makefile” on page 24-22
“Skipped Validation of Build Tool “Download” or “Execute”” on page 24-23

Build Tool Command Path Incorrect


If the path or command file name are not correct, validation displays:

Cannot find file 'path+command'. The file does not exist.

Consider the following two lines from an example toolchain definition file:

tool.setCommand('abc');
tool.setPath('/toolchain/');
To correct this issue:

• Check that the build tool is installed.


• Review the arguments given for the tool.setCommand and tool.setPath lines in
toolchain definition file.

Build Tool Not in System Path


When the build tool’s path is not provided and the command file is not in the system
path, validation displays:

Cannot find 'command'. It is not in the system path.

Consider the following two lines from an example toolchain definition file:

tool.setCommand('icl');

24-20
Troubleshooting Custom Toolchain Validation

tool.setPath('');

Because the argument for setPath() is '' instead of an absolute path, the build tool
must be on the system path.

To correct this issue:

• Use coder.make.ToolchainInfo.ShellSetup property to add the path to the


toolchain installation.
• Use your system setup to add the toolchain installation directory to system
environment path.

Otherwise, replace '' with the absolute path of the command file.

Tool Path Does Not Exist


If the path of the build tool path is provided, but does not exist, validation displays:

Path 'toolpath' does not exist.

To correct this issue:

• Check the actual path of the build tool. Then, update the value of
coder.make.BuildTool.setPath in the toolchain definition file.
• Use your system setup to add the toolchain installation directory to system
environment path. Then, set the value of coder.make.BuildTool.setPath to ''.

Unsupported Platform
If the toolchain is not supported on the host computer platform, validation displays:
Toolchain 'tlchn' is supported on a 'pltfrma' platform. However, you are running on a 'pltfrmb' platform.

To correct this issue:

• Check the coder.make.ToolchainInfo.Platform property in your toolchain


definition file for errors.
• Update or replace the toolchain definition file with one that supports your host
computer platform.
• Change host computer platforms.

24-21
24 Custom Toolchain Registration

Toolchain is Not installed


If the toolchain is not installed, validation displays:

Toolchain is not installed

To correct this issue, install the expected toolchain, or verify that you selected the correct
toolchain, as described in “Use the Custom Toolchain” on page 24-19.

Project or Configuration is Using the Template Makefile


By default, MATLAB Coder tries to use the selected build toolchain to build the
generated code. However, if the makefile configuration options detailed in the following
sections are not set to their default value, MATLAB Coder cannot use the toolchain and
reverts to using the template makefile approach for building the generated code.

MATLAB Coder Project Settings

Project Settings Dialog Box All Settings Default Setting


Parameter Name
Generate makefile Yes
Make command make_rtw
Template makefile default_tmf
Compiler optimization level Off

Command-line Configuration Parameters for the codegen function

coder.CodeConfig or Default Value


coder.EmbeddedCodeConfig Parameter Name
GenerateMakefile 'true'
MakeCommand 'make_rtw'
TemplateMakefile 'default_tmf'
CCompilerOptimization 'Off'

To use the toolchain approach, reset your configuration options to these default values
manually or:

• To reset settings for project project_name, at the MATLAB command line, enter:

24-22
Troubleshooting Custom Toolchain Validation

coder.make.upgradeMATLABCoderProject(project_name)
• To reset command-line settings for configuration object config, create an updated
configuration object new_config and then use new_config with the codegen
function in subsequent builds. At the MATLAB command line, enter:
new_config = coder.make.upgradeCoderConfigObject(config);

Skipped Validation of Build Tool “Download” or “Execute”


Even though the Validation Report states “Toolchain Validation Result: Passed” it
includes one or both of the following notes:
### Validation of build tool "Download"
Skipped. No "Download" build tool is specified.
### Validation of build tool "Execute"
Skipped. "Execute" build tool "$(PRODUCT)" cannot be validated.

To correct this issue, update the toolchain definition file and re-register the updated
toolchain. For more information, see:

• “Create and Edit Toolchain Definition File” on page 24-8


• “Create and Validate ToolchainInfo Object” on page 24-16
• “Register the Custom Toolchain” on page 24-17

24-23
24 Custom Toolchain Registration

Prevent Circular Data Dependencies with One-Pass or Single-Pass


Linkers
Symptom: During a software build, a build error occurs; variables don't resolve correctly.

If your toolchain uses a one-pass or single-pass linker, prevent circular data


dependencies by adding the StartLibraryGroup and EndLibraryGroup linker directives
to the toolchain definition file.

For example, if the linker is like GNU gcc, then the directives are '-Wl,--start-
group' and '-Wl,--end-group', as shown here:

% ------------------------------
% Linker
% ------------------------------

tool = tc.getBuildTool('Linker');

tool.setName( 'GNU Linker');


tool.setCommand( 'gcc');
tool.setPath( '');

tool.setDirective( 'Library', '-l');


tool.setDirective( 'LibrarySearchPath', '-L');
tool.setDirective( 'OutputFlag', '-o');
tool.setDirective( 'Debug', '-g');
tool.addDirective( 'StartLibraryGroup', {'-Wl,--start-group'});
tool.addDirective( 'EndLibraryGroup', {'-Wl,--end-group'});

tool.setFileExtension( 'Executable', '');


tool.setFileExtension( 'Shared Library', '.so');

24-24
25

Deploying Generated Code

• “Call a C Static Library Function from C Code” on page 25-2


• “Call a C/C++ Static Library Function from MATLAB Code” on page 25-4
• “Call Generated C/C++ Functions” on page 25-6
• “Use a C Dynamic Library in a Microsoft Visual Studio Project” on page 25-9
• “Specify External File Locations” on page 25-12
• “Code Generation of Matrices and Arrays” on page 25-16
• “Incorporate Generated Code Using an Example Main Function” on page 25-18
• “Use an Example C Main in an Application” on page 25-21
• “Package Code for Other Development Environments” on page 25-44
• “Structure of Generated Example C/C++ Main Function” on page 25-49
• “Troubleshoot Failures in Deployed Code” on page 25-53
25 Deploying Generated Code

Call a C Static Library Function from C Code


This example shows how to call a generated C library function from C code. It uses the C
static library function absval described in “Call a C/C++ Static Library Function from
MATLAB Code” on page 25-4.

1 Write a main function in C that does the following:

• Includes the generated header file, which contains the function prototypes for the
library function.
• Calls the initialize function before calling the library function for the first time.
• Calls the terminate function after calling the library function for the last time.

Here is an example of a C main function that calls the library function absval:
/*
** main.c
*/
#include <stdio.h>
#include <stdlib.h>
#include "absval.h"

int main(int argc, char *argv[])


{
absval_initialize();

printf("absval(-2.75)=%g\n", absval(-2.75));

absval_terminate();

return 0;
}
2 Configure your target to integrate this custom C main function with your generated
code, as described in “Specify External File Locations” on page 25-12.

For example, you can define a configuration object that points to the custom C code:

a Create a configuration object. At the MATLAB prompt, enter:


cfg = coder.config('exe');
b Set custom code properties on the configuration object, as in these example
commands:

25-2
Call a C Static Library Function from C Code

cfg.CustomSource = 'main.c';
cfg.CustomInclude = 'c:\myfiles';
3 Generate the C executable. Use the -args option to specify that the input is a real,
scalar double. At the MATLAB prompt, enter:
codegen -config cfg absval -args {0}
4 Call the executable. For example:
absval(-2.75)

25-3
25 Deploying Generated Code

Call a C/C++ Static Library Function from MATLAB Code


This example shows how to call a C/C++ library function from MATLAB code that is
suitable for code generation.

Suppose you have a MATLAB file absval.m that contains the following function:
function y = absval(u) %#codegen
y = abs(u);
end

To generate a C static library function and call it from MATLAB code:

1 Generate the C library for absval.m.


codegen -config:lib absval -args {0.0}

Here are key points about this command:

• The -config:lib option instructs MATLAB Coder to generate absval as a C


static library function.

The default target language is C. To change the target language to C++, see
“Specify a Language for Code Generation” on page 21-28.
• MATLAB Coder creates the library absval.lib (or absval.a on Linus
Torvalds' Linux) and header file absval.h in the folder /emcprj/
rtwlib/absval. It also generates the functions absval_initialize and
absval_terminate in the C library.
• The -args option specifies the class, size, and complexity of the primary function
input u by example, as described in “Define Input Properties by Example at the
Command Line” on page 21-50.
2 Write a MATLAB function to call the generated library:
%#codegen
function y = callabsval

% Call the initialize function before


% calling the C function for the first time
coder.ceval('absval_initialize');

y = -2.75;
y = coder.ceval('absval',y);

25-4
Call a C/C++ Static Library Function from MATLAB Code

% Call the terminate function after


% calling the C function for the last time
coder.ceval('absval_terminate');
The MATLAB function callabsval uses the interface coder.ceval to call the
generated C functions absval_initialize, absval, and absval_terminate.
You must use this function to call C functions from generated code. For more
information, see “Call Generated C/C++ Functions” on page 25-6.
3 Convert the code in callabsval.m to a MEX function so that you can call the C
library function absval directly from the MATLAB prompt.

a Generate the MEX function using codegen as follows:

• Create a code generation configuration object for a MEX function:


cfg = coder.config
• On Microsoft Windows platforms, use this command:
codegen -config cfg callabsval codegen/lib/absval/absval.lib
codegen/lib/absval/absval.h
By default, this command creates, in the current folder, a MEX function
named callabsval_mex

On the Linus Torvalds' Linux platform, use this command:


codegen -config cfg callabsval codegen/lib/absval/absval.a
codegen/lib/absval/absval.h
b At the MATLAB prompt, call the C library by running the MEX function. For
example, on Windows:
callabsval_mex

25-5
25 Deploying Generated Code

Call Generated C/C++ Functions


In this section...
“Conventions for Calling Functions in Generated Code” on page 25-6
“How to Call C/C++ Functions from MATLAB Code” on page 25-6
“Calling Initialize and Terminate Functions” on page 25-7
“Calling C/C++ Functions with Multiple Outputs” on page 25-8
“Calling C/C++ Functions that Return Arrays” on page 25-8

Conventions for Calling Functions in Generated Code


When generating code, MATLAB Coder uses the following calling conventions:

• Passes arrays by reference as inputs.


• Returns arrays by reference as outputs.
• Unless you optimize your code by using the same variable as both input and output,
passes scalars by value as inputs. In that case, MATLAB Coder passes the scalar by
reference.
• Returns scalars by value for single-output functions.
• Returns scalars by reference:

• For functions with multiple outputs.


• When you use the same variable as both input and output.

For more information about optimizing your code by using the same variable as both
input and output, see “Eliminate Redundant Copies of Function Inputs” on page
29-7.

How to Call C/C++ Functions from MATLAB Code


You can call the C/C++ functions generated for libraries as custom C/C++ code from
MATLAB functions that are suitable for code generation. For static libraries, you must
use the coder.ceval function to wrap the function calls, as in this example:

function y = callmyCFunction %#codegen

25-6
Call Generated C/C++ Functions

y = 1.5;
y = coder.ceval('myCFunction',y);
end
Here, the MATLAB function callmyCFunction calls the custom C function
myCFunction, which takes one input argument.

For dynamically-linked libraries, you can also use coder.ceval.

There are additional requirements for calling C/C++ functions from the MATLAB code in
the following situations:

• You want to call generated C/C++ libraries or executables from a MATLAB function.
Call housekeeping functions generated by MATLAB Coder, as described in “Calling
Initialize and Terminate Functions” on page 25-7.
• You want to call C/C++ functions that are generated from MATLAB functions that
have more than one output, as described in “Calling C/C++ Functions with Multiple
Outputs” on page 25-8.
• You want to call C/C++ functions that are generated from MATLAB functions that
return arrays, as described in “Calling C/C++ Functions that Return Arrays” on page
25-8.

Calling Initialize and Terminate Functions


When you convert a MATLAB function to a C/C++ library function or a C/C++
executable, MATLAB Coder automatically generates two housekeeping functions that
you must call along with the C/C++ function.

Housekeeping Function When to Call


primary_function_name_initialize Before you call your C/C++ executable
or library function for the first time
primary_function_name_terminate After you call your C/C++ executable
or library function for the last time

From C/C++ code, you can call these functions directly. However, to call them from
MATLAB code that is suitable for code generation, you must use the coder.ceval
function. coder.ceval is a MATLAB Coder function, but is not supported by the
native MATLAB language. Therefore, if your MATLAB code uses this function, use
coder.target to disable these calls in MATLAB and replace them with equivalent
functions.

25-7
25 Deploying Generated Code

Calling C/C++ Functions with Multiple Outputs


Although MATLAB Coder can generate C/C++ code from MATLAB functions that have
multiple outputs, the generated C/C++ code cannot return multiple outputs directly
because the C/C++ language does not support multiple return values. Instead, you can
achieve the effect of returning multiple outputs from your C/C++ function by using
coder.wref with coder.ceval.

Calling C/C++ Functions that Return Arrays


Although MATLAB Coder can generate C/C++ code from MATLAB functions that
return values as arrays, the generated code cannot return arrays by value because the
C/C++ language is limited to returning single, scalar values. Instead, you can return
arrays from your C/C++ function by reference as pointers by using coder.wref with
coder.ceval.

25-8
Use a C Dynamic Library in a Microsoft Visual Studio Project

Use a C Dynamic Library in a Microsoft Visual Studio Project


This example shows how to create and configure a simple Microsoft Visual Studio®
Win32 Console Application project that calls a dynamic library (DLL) that MATLAB
Coder generates. This example uses Microsoft Visual Studio 2013. In other versions of
Microsoft Visual Studio, you might encounter a different procedure.

Generate a C Dynamic Library

1 Create a MATLAB function foo.


function c = foo(a) %#codegen
c = sqrt(a);
end
2 Save it as foo.m in a local writable folder, for example, c:\dll_test.
3 Generate a DLL for the MATLAB function foo. Use the -args option to specify that
the input a is a real double.
codegen -report -config:dll foo -args {0}

On Microsoft Windows systems, codegen generates a C dynamic library, foo.dll,


and supporting files in the default folder, codegen/dll/foo.

Create a Microsoft Visual Studio Project

In Microsoft Visual Studio, create an empty Win32 Console Application project. In


Microsoft Visual Studio 2013:

1 On the Start page window, select File > New > Project.
2 In the New Product dialog box, select Installed > Templates > Visual C++ >
Win32 > Win32 Console Application and enter a name.
3 In the Win32 Application Wizard, select Application Settings. Select the Empty
project check box.
4 Click Finish.

Configure the Platform

Verify that the project configuration specifies the architecture that matches your
computer. By default, MATLAB Coder builds a DLL for the platform that you are
working on, but Microsoft Visual Studio builds for Win32. In Microsoft Visual Studio
2013:

25-9
25 Deploying Generated Code

1 Select Build > Configuration Manager.


2 In the Configuration Manager, set Active solution platform to match your
platform.

Configure the Solution Version

Configure the project to use the release version of the C run-time library. By default,
the Microsoft Visual Studio project uses the debug version of the C run-time library.
However, by default, the DLL that MATLAB Coder generates uses the release version. In
Microsoft Visual Studio 2013:

1 Select Build > Configuration Manager.


2 In the Configuration Manager, set Active solution configuration to Release.

Configure Additional Directories and Dependencies

1 Select Project > Properties.


2 Under Configuration Properties > C/C++ > General, add the folder c:
\dll_test\codegen\dll\foo to Additional Include Directories.
3 Under Configuration Properties > Linker > General, add the folder c:
\dll_test\codegen\dll\foo to Additional Library Directories.
4 Under Configuration Properties > Linker > Input, add foo.lib to Additional
Dependencies.

Create a main.c File

Create a main.c file that calls foo.dll. The main.c function must:

• Include the generated header file, which contains the function prototypes for the
library function.
• Call the initialize function before calling the library function for the first time.
• Call the terminate function after calling the library function for the last time.

For example:
#include "foo.h"
#include "foo_initialize.h"
#include "foo_terminate.h"
#include <stdio.h>

25-10
Use a C Dynamic Library in a Microsoft Visual Studio Project

int main()
{
foo_initialize();
printf("%f\n", foo(25));
foo_terminate();
getchar();
return 0;
}

Add the main.c File to the Project

1 Select Project > Add Existing Item.


2 Navigate to the folder that contains the main.c file.
3 Select the main.c file.

Build and Run the Executable

1 Build the executable. Select Build > Build Solution.


2 Make the .dll accessible to the executable. Either copy foo.dll to the folder
containing the executable or add the folder containing foo.dll to your path.
3 Run the executable.

25-11
25 Deploying Generated Code

Specify External File Locations


In this section...
“External File Locations for External Code Integration” on page 25-12
“Specify External Files in a Class Derived from coder.ExternalDependency” on page
25-12
“Specify External Files in MATLAB Code Using coder.updateBuildInfo” on page
25-12
“Specify External Files Using the MATLAB Coder App” on page 25-13
“Specify External Files at the Command Line” on page 25-13
“Specify External Files with Configuration Objects” on page 25-14

External File Locations for External Code Integration


To integrate external code with generated C/C++ code, you must specify the locations of
your external source files, header files, and libraries to MATLAB Coder.

You can specify the file locations:

• In a class definition file, when you derive a class from coder.ExternalDependency


• In your MATLAB code using the coder.updateBuildInfo function
• In the project settings dialog box
• From the command line
• In the configuration object

Specify External Files in a Class Derived from coder.ExternalDependency


When you derive a class from coder.ExternalDependency, you write a method
updateBuildInfo that specifies the locations of the external files required for the build.
See coder.ExternalDependency.

Specify External Files in MATLAB Code Using coder.updateBuildInfo


In your MATLAB code, you can call coder.updateBuildInfo to specify the locations of
external files. See coder.updateBuildInfo.

25-12
Specify External File Locations

Specify External Files Using the MATLAB Coder App


1 On the Generate Code page, to open the Generate dialog box, click the Generate
arrow .
2 In the Generate dialog box, set the Build Type to one of the following:

• Source Code
• Static Library
• Dynamic Library
• Executable
3 Click More Settings.
4 On the Custom Code tab, under Custom C-code to include in generated files,
specify Source file and Header file. Source file specifies that the code appear at
the top of generated C/C++ source files. Header file specifies that the code appear at
the top of generated header files.

Custom Code Property Description


Under Additional files and directories to be built, provide an absolute path or a path relative
to the project folder.
Include directories Specifies a list of folders that contain custom header, source,
object, or library files. Separate list items with a semicolon.
Source files Specifies additional custom C/C++ files to be compiled with the
MATLAB file. Separate list items with a semicolon.
Libraries Specifies the names of object or library files to be linked with the
generated code. Separate list items with a semicolon.
Under Custom C-code to include in generated files
Source file Specifies code to appear at the top of generated C/C++ source
files.
Header file Specifies custom code to appear at the top of generated header
files

Specify External Files at the Command Line


When you compile MATLAB function with MATLAB Coder, you can specify custom C/
C++ files — such as source, header, and library files — on the command line along with

25-13
25 Deploying Generated Code

your MATLAB file. For example, suppose you want to generate an embeddable C code
executable that integrates a custom C function myCfcn with a MATLAB function myMfcn
that has no input parameters. The custom source and header files for myCfcn reside in
the folder C:\custom. You can use the following command to generate the code:

codegen C:\custom\myCfcn.c C:\custom\myCfcn.h myMfcn

Specify External Files with Configuration Objects


You can specify custom C/C++ files by setting custom code properties on configuration
objects.

1 Define a configuration object, as described in “Creating Configuration Objects” on


page 21-35.

For example:

cc = coder.config('lib');
2 Set one or more of the custom code properties.

Custom Code Property Description


CustomInclude Specifies a list of folders that contain custom header, source,
object, or library files.

Note: If your folder path name contains spaces, you must enclose
it in double quotes:
cc.CustomInclude = '"C:\Program Files\MATLAB\work"'
CustomSource Specifies additional custom C/C++ files to be compiled with the
MATLAB file.
CustomLibrary Specifies the names of object or library files to be linked with the
generated code.
CustomSourceCode Specifies code to insert at the top of each generated C/C++ source
file.
CustomHeaderCode Specifies custom code to insert at the top of each generated C/C++
header file.

For example:

25-14
Specify External File Locations

cc.CustomInclude = 'C:\custom\src C:\custom\lib';


cc.CustomSource = 'cfunction.c';
cc.CustomLibrary = 'chelper.obj clibrary.lib';
cc.CustomSourceCode = '#include "cgfunction.h"';
3 Compile the MATLAB code specifying the code generation configuration object.

Note: If you generate code for a function that has input parameters, you must specify
the inputs. “Primary Function Input Specification” on page 21-45

codegen -config cc myFunc


4 Call custom C/C++ functions.

From... Call...
C/C++ source code Custom C/C++ functions directly
MATLAB code, compiled on the Custom C/C++ functions using
MATLAB Coder path coder.ceval.

For example, from MATLAB code:


...
y = 2.5;
y = coder.ceval('myFunc',y);
...

25-15
25 Deploying Generated Code

Code Generation of Matrices and Arrays


MATLAB and MATLAB Coder software store matrix data and arrays (1-D, 2-D, ...) in
column-major format as a vector. Column-major format orders elements in a matrix
starting from the first column, top to bottom, and then moving to the next column. For
example, in the following 3x3 matrix:
A =
1 2 3
4 5 6
7 8 9
translates to an array of length 9 in the following order:
A(1) = A(1,1) = 1;
A(2) = A(2,1) = 4;
A(3) = A(3,1) = 7;
A(4) = A(1,2) = 2;
A(5) = A(2,2) = 5;
and so on.

In column-major format, the software accesses the next element of an array in memory
by incrementing the first index of the array. For example, the software stores these
element pairs sequentially in memory:

• A(i) and A(i+1)


• B(i,j) and B(i+1,j)
• C(i,j,k) and C(i+1,j,k)

For more information on the internal representation of MATLAB data, see “MATLAB
Data” in the MATLAB External Interfaces document.

Code generation software uses column-major format because:

• Much of the software that supports signal and array processing uses column-major
format: MATLAB, LAPack, Fortran90, DSP libraries.
• A column is equivalent to a channel in frame-based processing. In this case, column-
major storage is more efficient than row-major storage.
• A column-major array is self-consistent with its component submatrices:

• A column-major 2-D array is a simple concatenation of 1-D arrays.


• A column-major 3-D array is a simple concatenation of 2-D arrays.

25-16
Code Generation of Matrices and Arrays

• The stride is the number of memory locations to index to the next element in the
same dimension. The stride of the first dimension is one element. The stride of the
nth dimension element is the product of sizes of the lower dimensions.
• Row-major n-D arrays have their stride of 1 for the highest dimension. Submatrix
manipulations typically access a scattered data set in memory, which does not
allow for efficient indexing.

C typically uses row-major format. MATLAB uses column-major format. You cannot
configure the code generation software to generate code with row-major ordering. If you
are integrating legacy C code with the generated code, consider transposing the row-
major data in your legacy C code into column-major format as a 1-D array.

25-17
25 Deploying Generated Code

Incorporate Generated Code Using an Example Main Function


In this section...
“Workflow for Using an Example Main Function” on page 25-18
“Control Example Main Generation Using the MATLAB Coder App” on page 25-19
“Control Example Main Generation Using the Command-Line Interface” on page
25-19

When you build an application that uses generated C/C++ code, you must provide a C/C+
+ main function that calls the generated code.

By default, for code generation of C/C++ source code, static libraries, dynamic libraries,
and executables, MATLAB Coder generates an example C/C++ main function. This
function is a template that can help you incorporate generated C/C++ code into your
application. The example main function declares and initializes data, including
dynamically allocated data. It calls entry-point functions but does not use values that the
entry point functions return.

MATLAB Coder generates source and header files for the example main function in the
examples subfolder of the build folder. For C code generation, it generates the files
main.c and main.h. For C++ code generation, it generates the files main.cpp and
main.h.

Do not modify the files main.c and main.h in the examples subfolder. If you do, when
you regenerate code, MATLAB Coder does not regenerate the example main files. It
warns you that it detects changes to the generated files. Before using the example main
function, copy the example main source and header files to a location outside of the build
folder. Modify the files in the new location to meet the requirements of your application.

The packNGo function and the Package option of the MATLAB Coder app do not
package the example main source and header files when you generate the files using
the default configuration settings. To package the example main files, configure code
generation to generate and compile the example main function, generate your code, and
then package the build files.

Workflow for Using an Example Main Function


1 Prepare your MATLAB code for code generation.
2 Check for run-time issues.

25-18
Incorporate Generated Code Using an Example Main Function

3 Make sure that example main generation is enabled.


4 Generate C/C++ code for the entry-point functions.
5 Copy the example main files from the examples subfolder to a different folder.
6 Modify the example main files in the new folder to meet the requirements of your
application.
7 Deploy the example main and generated code for the platform that you want.
8 Build the application.

For an example that shows how to generate an example main and use it to build an
executable, see “Use an Example C Main in an Application” on page 25-21.

Control Example Main Generation Using the MATLAB Coder App


1 On the Generate Code page, to open the Generate dialog box, click the Generate
arrow .
2 In the Generate dialog box, set the Build Type to one of the following:

• Source Code
• Static Library
• Dynamic Library
• Executable
3 Click More Settings.
4 On the All Settings tab, under Advanced, set Generate example main to one of
the following:

Set To For
Do not generate an example main Not generating an example C/C++ main
function function
Generate, but do not compile, Generating an example C/C++ main
an example main function (default) function but not compiling it
Generate and compile an example Generating an example C/C++ main
main function function and compiling it

Control Example Main Generation Using the Command-Line Interface


1 Create a code configuration object for 'lib', 'dll', or 'exe'. For example:

25-19
25 Deploying Generated Code

cfg = coder.config('lib'); % or dll or exe


2 Set the GenerateExampleMain property.

Set To For
'DoNotGenerate' Not generating an example C/C++ main
function
'GenerateCodeOnly' (default) Generating an example C/C++ main
function but not compiling it
'GenerateCodeAndCompile' Generating an example C/C++ main
function and compiling it

For example:
cfg.GenerateExampleMain = 'GenerateCodeOnly';

Related Examples
• “Structure of Generated Example C/C++ Main Function” on page 25-49
• “Call a C Static Library Function from C Code” on page 25-2

More About
• “Specifying main Functions for C/C++ Executables” on page 21-24

25-20
Use an Example C Main in an Application

Use an Example C Main in an Application


This example shows how to build a C executable from MATLAB code that implements a
simple Sobel filter to perform edge detection on images. The executable reads an image
from the disk, applies the Sobel filtering algorithm, and then saves the modified image.

The example shows how to generate and modify an example main function that you can
use when you build the executable.

In this section...
“Prerequisites” on page 25-21
“Create a Folder and Copy Relevant Files” on page 25-22
“Run the Sobel Filter on the Image” on page 25-24
“Generate and Test a MEX Function” on page 25-26
“Generate an Example Main Function for sobel.m” on page 25-26
“Copy the Example Main Files” on page 25-29
“Modify the Generated Example Main Function” on page 25-29
“Generate the Sobel Filter Application” on page 25-42
“Run the Sobel Filter Application” on page 25-42
“Display the Resulting Image” on page 25-42

Prerequisites
To complete this example, install the following products:

• MATLAB
• MATLAB Coder
• 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”.

25-21
25 Deploying Generated Code

Create a Folder and Copy Relevant Files


The files you use in this example are:

File Name File Type Description


sobel.m Function code MATLAB implementation of
a Sobel filtering algorithm.
sobel.m takes an image
(represented as a double
matrix) and a threshold
value as inputs. The
algorithm detects edges in
the image (based on the
threshold value). sobel.m
returns a modified image
displaying the edges.
hello.jpg Image file Image that the Sobel filter
modifies.

Contents of File sobel.m

function edgeImage = sobel(originalImage, threshold) %#codegen

% edgeImage = sobel(originalImage, threshold)


% Sobel edge detection. Given a normalized image (with double values)
% return an image where the edges are detected w.r.t. threshold value.

assert(all(size(originalImage) <= [1024 1024]));


assert(isa(originalImage, 'double'));
assert(isa(threshold, 'double'));

k = [1 2 1; 0 0 0; -1 -2 -1];
H = conv2(double(originalImage),k, 'same');
V = conv2(double(originalImage),k','same');
E = sqrt(H.*H + V.*V);
edgeImage = uint8((E > threshold) * 255);

25-22
Use an Example C Main in an Application

Contents of hello.jpg

To copy the example files to a local working folder:

1 Create a local working folder. For example, c:\coder\edge_detection.


2 Navigate to the working folder.
3 Copy the files sobel.m and hello.jpg from the examples folder sobel to your
working folder.

copyfile(fullfile(docroot, 'toolbox', 'coder', 'examples', 'sobel'))

25-23
25 Deploying Generated Code

Run the Sobel Filter on the Image


1 Read the original image into a MATLAB matrix and display it.

im = imread('hello.jpg');
2 Display the image as a basis for comparison to the result of the Sobel filter.

image(im);

3 The Sobel filtering algorithm operates on grayscale images. Convert the color image
to an equivalent grayscale image with normalized values (0.0 for black, 1.0 for
white).
gray = (0.2989 * double(im(:,:,1)) + 0.5870 * double(im(:,:,2)) + 0.1140 * double(im(:,:,3)))/255;

25-24
Use an Example C Main in an Application

4 To run the MATLAB function for the Sobel filter, pass the grayscale image matrix
gray and a threshold value to the function sobel. This example uses 0.7 for a
threshold value.

edgeIm = sobel(gray, 0.7);


5 To display the modified image, reformat the matrix edgeIm with the function
repmat so that you can pass it to the image command.

im3 = repmat(edgeIm, [1 1 3]);


image(im3);

25-25
25 Deploying Generated Code

Generate and Test a MEX Function


1 To test that generated code is functionally equivalent to the original MATLAB code
and that run-time errors do not occur, generate a MEX function.

codegen -report sobel

codegen generates a MEX function named sobel_mex in the current working


folder.
2 To run the MEX function for the Sobel filter, pass the grayscale image matrix gray
and a threshold value to the function sobel_mex. This example uses 0.7 for a
threshold value.

edgeImMex = sobel_mex(gray, 0.7);


3 To display the modified image, reformat the matrix edgeImMex with the function
repmat so that you can pass it to the image command.

im3Mex = repmat(edgeImMex, [1 1 3]);


image(im3Mex);

This image is the same as the image created using the MATLAB function.

Generate an Example Main Function for sobel.m


Although you can write a custom main function for your application, an example main
function provides a template to help you incorporate the generated code.

To generate an example main function for the Sobel filter:

1 Create a configuration object for a C static library.

cfg = coder.config('lib');

For configuration objects for C/C++ source code, static libraries, dynamic libraries,
and executables, the setting GenerateExampleMain controls generation of the
example main function. The setting is set to 'GenerateCodeOnly' by default,
which generates the example main function but does not compile it. For this
example, do not change the value of the GenerateExampleMain setting.
2 Generate a C static library using the configuration object.

codegen -report -config cfg sobel

25-26
Use an Example C Main in an Application

The generated files for the static library are in the folder codegen/lib/sobel. The
example main files are in the subfolder codegen/lib/sobel/examples.

Contents of Example Main File main.c

/*
* main.c
*
* Code generation for function 'main'
*
*/

/*************************************************************************/
/* This automatically generated example C main file shows how to call */
/* entry-point functions that MATLAB Coder generated. You must customize */
/* this file for your application. Do not modify this file directly. */
/* Instead, make a copy of this file, modify it, and integrate it into */
/* your development environment. */
/* */
/* This file initializes entry-point function arguments to a default */
/* size and value before calling the entry-point functions. It does */
/* not store or use any values returned from the entry-point functions. */
/* If necessary, it does pre-allocate memory for returned values. */
/* You can use this file as a starting point for a main function that */
/* you can deploy in your application. */
/* */
/* After you copy the file, and before you deploy it, you must make the */
/* following changes: */
/* * For variable-size function arguments, change the example sizes to */
/* the sizes that your application requires. */
/* * Change the example values of function arguments to the values that */
/* your application requires. */
/* * If the entry-point functions return values, store these values or */
/* otherwise use them as required by your application. */
/* */
/*************************************************************************/
/* Include files */
#include "rt_nonfinite.h"
#include "sobel.h"
#include "main.h"
#include "sobel_terminate.h"
#include "sobel_emxAPI.h"
#include "sobel_initialize.h"

25-27
25 Deploying Generated Code

/* Function Declarations */
static emxArray_real_T *argInit_d1024xd1024_real_T(void);
static double argInit_real_T(void);
static void main_sobel(void);

/* Function Definitions */
static emxArray_real_T *argInit_d1024xd1024_real_T(void)
{
emxArray_real_T *result;
static int iv2[2] = { 2, 2 };

int b_j0;
int b_j1;

/* Set the size of the array.


Change this size to the value that the application requires. */
result = emxCreateND_real_T(2, iv2);

/* Loop over the array to initialize each element. */


for (b_j0 = 0; b_j0 < result->size[0U]; b_j0++) {
for (b_j1 = 0; b_j1 < result->size[1U]; b_j1++) {
/* Set the value of the array element.
Change this value to the value that the application requires. */
result->data[b_j0 + result->size[0] * b_j1] = argInit_real_T();
}
}

return result;
}

static double argInit_real_T(void)


{
return 0.0;
}

static void main_sobel(void)


{
emxArray_uint8_T *edgeImage;
emxArray_real_T *originalImage;
emxInitArray_uint8_T(&edgeImage, 2);

/* Initialize function 'sobel' input arguments. */


/* Initialize function input argument 'originalImage'. */
originalImage = argInit_d1024xd1024_real_T();

25-28
Use an Example C Main in an Application

/* Call the entry-point 'sobel'. */


sobel(originalImage, argInit_real_T(), edgeImage);
emxDestroyArray_uint8_T(edgeImage);
emxDestroyArray_real_T(originalImage);
}

int main(int argc, const char * const argv[])


{
(void)argc;
(void)argv;

/* Initialize the application.


You do not need to do this more than one time. */
sobel_initialize();

/* Invoke the entry-point functions.


You can call entry-point functions multiple times. */
main_sobel();

/* Terminate the application.


You do not need to do this more than one time. */
sobel_terminate();
return 0;
}

/* End of code generation (main.c) */

Copy the Example Main Files


Do not modify the files main.c and main.h in the examples subfolder. If you do, when
you regenerate code, MATLAB Coder does not regenerate the example main files. It
warns you that it detects changes to the generated files.

Copy the files main.c and main.h from the folder codegen/lib/sobel/examples to
another location. For this example, copy the files to the current working folder. Modify
the files in the new location.

Modify the Generated Example Main Function


• “Modify the Function main” on page 25-30
• “Modify the Initialization Function argInit_d1024xd1024_real_T” on page 25-32

25-29
25 Deploying Generated Code

• “Write the Function saveImage” on page 25-34


• “Modify the Function main_sobel” on page 25-36
• “Modify the Function Declarations” on page 25-37
• “Modify the Include Files” on page 25-37
• “Contents of Modified File main.c” on page 25-38

The example main function declares and initializes data, including dynamically allocated
data, to zero values. It calls entry-point functions with arguments set to zero values, but
it does not use values returned from the entry-point functions.

The C main function must meet the requirements of your application. This example
modifies the example main function to meet the requirements of the Sobel filter
application.

This example modifies the file main.c so that the Sobel filter application:

• Reads in the grayscale image from a binary file.


• Applies the Sobel filtering algorithm.
• Saves the modified image to a binary file.

Modify the Function main

Modify the function main to:

• Accept the file containing the grayscale image data and a threshold value as input
arguments.
• Call the function main_sobel with the address of the grayscale image data stream
and the threshold value as input arguments.

In the function main:

1 Remove the declarations void(argc) and (void)argv.


2 Declare the variable filename to hold the name of the binary file containing the
grayscale image data.

const char *filename;


3 Declare the variable threshold to hold the threshold value.

double threshold;

25-30
Use an Example C Main in an Application

4 Declare the variable fd to hold the address of the grayscale image data that the
application reads in from filename.
FILE *fd;
5 Add an if statement that checks for three arguments.
if (argc != 3) {
printf("Expected 2 arguments: filename and threshold\n");
exit(-1);
}
6 Assign the input argument argv[1] for the file containing the grayscale image data
to filename.
filename = argv[1];
7 Assign the input argument argv[2] for the threshold value to threshold,
converting the input from a string to a numeric double.
threshold = atof(argv[2]);
8 Open the file containing the grayscale image data whose name is specified in
filename. Assign the address of the data stream to fd.
fd = fopen(filename, "rb");
9 To verify that the executable can open filename, write an if-statement that exits
the program if the value of fd is NULL.
if (fd == NULL) {
exit(-1);
}
10 Replace the function call for main_sobel by calling main_sobel with input
arguments fd and threshold.
main_sobel(fd, threshold);
11 Close the grayscale image file after calling sobel_terminate.
fclose(fd);

Modified Function main


int main(int argc, const char * const argv[])
{
const char *filename;
double threshold;

25-31
25 Deploying Generated Code

FILE *fd;

if (argc != 3) {
printf("Expected 2 arguments: filename and threshold\n");
exit(-1);
}

filename = argv[1];
threshold = atof(argv[2]);
fd = fopen(filename, "rb");
if (fd == NULL) {
exit(-1);
}
/* Initialize the application.
You do not need to do this more than one time. */
sobel_initialize();

/* Invoke the entry-point functions.


You can call entry-point functions multiple times. */
main_sobel(fd, threshold);

/* Terminate the application.


You do not need to do this more than one time. */
sobel_terminate();

fclose(fd);

return 0;
}

Modify the Initialization Function argInit_d1024xd1024_real_T

In the example main file, the function argInit_d1024xd1024_real_T creates a


dynamically allocated variable-size array (emxArray) for the image that you pass to the
Sobel filter. This function initializes the emxArray to a default size and the elements of
the emxArray to 0. It returns the initialized emxArray.

For the Sobel filter application, modify the function to read the grayscale image data
from a binary file into the emxArray.

In the function argInit_d1024xd1024_real_T:

1 Replace the input argument void with the argument FILE *fd. This variable
points to the grayscale image data that the function reads in.

25-32
Use an Example C Main in an Application

static emxArray_real_T *argInit_d1024xd1024_real_T(FILE *fd)


2 Change the values of the variable iv2 to match the dimensions of the grayscale
image matrix gray. iv2 holds the size values for the dimensions of the emxArray
that argInit_d1024xd1024_real_T creates.

static int iv2[2] = { 484, 648 };

MATLAB stores matrix data in column-major format, while C stores matrix data in
row-major format. Declare the dimensions accordingly.
3 Define a variable element to hold the values read in from the grayscale image data.

double element;
4 Change the for-loop construct to read data points from the normalized image into
element by adding an fread command to the inner for-loop.

fread(&element, 1, sizeof(element), fd);


5 Inside the for-loop, assign element as the value set for the emxArray data.

result->data[b_j0 + result->size[0] * b_j1] = element;

Modified Initialization Function argInit_d1024xd1024_real_T

static emxArray_real_T *argInit_d1024xd1024_real_T(FILE *fd)


{
emxArray_real_T *result;
static int iv2[2] = { 484, 648 };

int b_j0;
int b_j1;
double element;

/* Set the size of the array.


Change this size to the value that the application requires. */
result = emxCreateND_real_T(2, iv2);

/* Loop over the array to initialize each element. */


for (b_j0 = 0; b_j0 < result->size[0U]; b_j0++) {
for (b_j1 = 0; b_j1 < result->size[1U]; b_j1++) {
/* Set the value of the array element.
Change this value to the value that the application requires. */
fread(&element, 1, sizeof(element), fd);
result->data[b_j0 + result->size[0] * b_j1] = element;

25-33
25 Deploying Generated Code

}
}

return result;
}

Write the Function saveImage

The MATLAB function sobel.m interfaces with MATLAB arrays, but the Sobel filter
application interfaces with binary files.

To save the image modified by the Sobel filtering algorithm to a binary file, create a
function saveImage. The function saveImage writes data from an emxArray into
a binary file. It uses a construction that is similar to the one used by the function
argInit_d1024xd1024_real_T.

In the file main.c:

1 Define the function saveImage that takes the address of emxArray edgeImage as
an input and has output type void.

static void saveImage(emxArray_uint8_T *edgeImage)


{
}
2 Define the variables b_j0 and b_j1 like they are defined in the function
argInit_d1024xd1024_real_T.

int b_j0;
int b_j1;
3 Define the variable element to store data read from the emxArray.

uint8_T element;
4 Open a binary file edge.bin for writing the modified image. Assign the address of
edge.bin to FILE *fd.

FILE *fd = fopen("edge.bin", "wb");


5 To verify that the executable can open edge.bin, write an if-statement that exits
the program if the value of fd is NULL.

if (fd == NULL) {
exit(-1);
}

25-34
Use an Example C Main in an Application

6 Write a nested for-loop construct like the one in the function


argInit_d1024xd1024_real_T.

for (b_j0 = 0; b_j0 < edgeImage->size[0U]; b_j0++)


{
for (b_j1 = 0; b_j1 < edgeImage->size[1U]; b_j1++)
{
}
}
7 Inside the inner for-loop, assign the values from the modified image data to
element.

element = edgeImage->data[b_j0 + edgeImage->size[0] * b_j1];


8 After the assignment for element, write the value from element to the file
edge.bin.

fwrite(&element, 1, sizeof(element), fd);


9 After the for-loop construct, close fd.

fclose(fd);

Function saveImage

static void saveImage(emxArray_uint8_T *edgeImage)


{
int b_j0;
int b_j1;
uint8_T element;

FILE *fd = fopen("edge.bin", "wb");


if (fd == NULL) {
exit(-1);
}
/* Loop over the array to save each element. */
for (b_j0 = 0; b_j0 < edgeImage->size[0U]; b_j0++) {
for (b_j1 = 0; b_j1 < edgeImage->size[1U]; b_j1++) {
element = edgeImage->data[b_j0 + edgeImage->size[0] * b_j1];
fwrite(&element, 1, sizeof(element), fd);
}
}
fclose(fd);
}

25-35
25 Deploying Generated Code

Modify the Function main_sobel

In the example main function, the function main_sobel creates emxArrays


for the data for the grayscale and modified images. It calls the function
argInit_d1024xd1024_real_T to initialize the emxArray for the grayscale
image. main_sobel passes both emxArrays and the threshold value of 0 that the
initialization function argInit_real_T returns to the function sobel. When the
function main_sobel ends, it discards the result of the function sobel.

For the Sobel filter application, modify the function main_sobel to:

• Take the address of the grayscale image data and the threshold value as inputs.
• Read the data from the address using argInit_d1024xd1024_real_T.
• Pass the data to the Sobel filtering algorithm with the threshold value threshold.
• Save the result using saveImage.

In the function main_sobel:

1 Replace the input arguments to the function with the arguments FILE *fd and
double threshold.

static void main_sobel(FILE *fd, double threshold)


2 Pass the input argument fd to the function call for
argInit_d1024xd1024_real_T.

originalImage = argInit_d1024xd1024_real_T(fd);
3 Replace the threshold value input in the function call to sobel with threshold.

sobel(originalImage, threshold, edgeImage);


4 After calling the function sobel, call the function saveImage with the input
edgeImage.

saveImage(edgeImage);

Modified Function main_sobel

static void main_sobel(FILE *fd, double threshold)


{
emxArray_uint8_T *edgeImage;
emxArray_real_T *originalImage;
emxInitArray_uint8_T(&edgeImage, 2);

25-36
Use an Example C Main in an Application

/* Initialize function 'sobel' input arguments. */


/* Initialize function input argument 'originalImage'. */
originalImage = argInit_d1024xd1024_real_T(fd);

/* Call the entry-point 'sobel'. */


sobel(originalImage, threshold, edgeImage);

saveImage(edgeImage);

emxDestroyArray_uint8_T(edgeImage);
emxDestroyArray_real_T(originalImage);
}

Modify the Function Declarations

To match the changes that you made to the function definitions, make the following
changes to the function declarations:

1 Change the input of the function *argInit_d1024xd1024_real_T to FILE *fd.

static emxArray_real_T *argInit_d1024xd1024_real_T(FILE *fd);


2 Change the inputs of the function main_sobel to FILE *fd and double
threshold.

static void main_sobel(FILE *fd, double threshold);


3 Add the function saveImage.

static void saveImage(emxArray_uint8_T *edgeImage);

Modified Function Declarations


/* Function Declarations */
static emxArray_real_T *argInit_d1024xd1024_real_T(FILE *fd);
static void saveImage(emxArray_uint8_T *edgeImage);
static double argInit_real_T(void);
static void main_sobel(FILE *fd, double threshold);

Modify the Include Files

For input/output functions that you use in main.c, add the header file stdio.h to the
included files list.
#include <stdio.h>

25-37
25 Deploying Generated Code

Modified Include Files


/* Include Files */
#include <stdio.h>

#include "rt_nonfinite.h"
#include "sobel.h"
#include "main.h"
#include "sobel_terminate.h"
#include "sobel_emxAPI.h"
#include "sobel_initialize.h"

Contents of Modified File main.c

main.c
/*
* main.c
*
* Code generation for function 'main'
*
*/

/*************************************************************************/
/* This automatically generated example C main file shows how to call */
/* entry-point functions that MATLAB Coder generated. You must customize */
/* this file for your application. Do not modify this file directly. */
/* Instead, make a copy of this file, modify it, and integrate it into */
/* your development environment. */
/* */
/* This file initializes entry-point function arguments to a default */
/* size and value before calling the entry-point functions. It does */
/* not store or use any values returned from the entry-point functions. */
/* If necessary, it does pre-allocate memory for returned values. */
/* You can use this file as a starting point for a main function that */
/* you can deploy in your application. */
/* */
/* After you copy the file, and before you deploy it, you must make the */
/* following changes: */
/* * For variable-size function arguments, change the example sizes to */
/* the sizes that your application requires. */
/* * Change the example values of function arguments to the values that */
/* your application requires. */
/* * If the entry-point functions return values, store these values or */
/* otherwise use them as required by your application. */

25-38
Use an Example C Main in an Application

/* */
/*************************************************************************/
/* Include Files */
#include <stdio.h>

#include "rt_nonfinite.h"
#include "sobel.h"
#include "main.h"
#include "sobel_terminate.h"
#include "sobel_emxAPI.h"
#include "sobel_initialize.h"

/* Function Declarations */
static emxArray_real_T *argInit_d1024xd1024_real_T(FILE *fd);
static void saveImage(emxArray_uint8_T *edgeImage);
static double argInit_real_T(void);
static void main_sobel(FILE *fd, double threshold);

/* Function Definitions */

static emxArray_real_T *argInit_d1024xd1024_real_T(FILE *fd)


{
emxArray_real_T *result;
static int iv2[2] = { 484, 648 };

int b_j0;
int b_j1;
double element;

/* Set the size of the array.


Change this size to the value that the application requires. */
result = emxCreateND_real_T(2, iv2);

/* Loop over the array to initialize each element. */


for (b_j0 = 0; b_j0 < result->size[0U]; b_j0++) {
for (b_j1 = 0; b_j1 < result->size[1U]; b_j1++) {
/* Set the value of the array element.
Change this value to the value that the application requires. */
fread(&element, 1, sizeof(element), fd);
result->data[b_j0 + result->size[0] * b_j1] = element;
}
}

return result;

25-39
25 Deploying Generated Code

static void saveImage(emxArray_uint8_T *edgeImage)


{
int b_j0;
int b_j1;
uint8_T element;

FILE *fd = fopen("edge.bin", "wb");


if (fd == NULL) {
exit(-1);
}
/* Loop over the array to save each element. */
for (b_j0 = 0; b_j0 < edgeImage->size[0U]; b_j0++) {
for (b_j1 = 0; b_j1 < edgeImage->size[1U]; b_j1++) {
element = edgeImage->data[b_j0 + edgeImage->size[0] * b_j1];
fwrite(&element, 1, sizeof(element), fd);
}
}
fclose(fd);
}

/*
* Arguments : void
* Return Type : double
*/
static double argInit_real_T(void)
{
return 0.0;
}

static void main_sobel(FILE *fd, double threshold)


{
emxArray_uint8_T *edgeImage;
emxArray_real_T *originalImage;
emxInitArray_uint8_T(&edgeImage, 2);

/* Initialize function 'sobel' input arguments. */


/* Initialize function input argument 'originalImage'. */
originalImage = argInit_d1024xd1024_real_T(fd);

/* Call the entry-point 'sobel'. */


sobel(originalImage, threshold, edgeImage);

25-40
Use an Example C Main in an Application

saveImage(edgeImage);

emxDestroyArray_uint8_T(edgeImage);
emxDestroyArray_real_T(originalImage);
}

int main(int argc, const char * const argv[])


{
const char *filename;
double threshold;
FILE *fd;

if (argc != 3) {
printf("Expected 2 arguments: filename and threshold\n");
exit(-1);
}

filename = argv[1];
threshold = atof(argv[2]);
fd = fopen(filename, "rb");
if (fd == NULL) {
exit(-1);
}
/* Initialize the application.
You do not need to do this more than one time. */
sobel_initialize();

/* Invoke the entry-point functions.


You can call entry-point functions multiple times. */
main_sobel(fd, threshold);

/* Terminate the application.


You do not need to do this more than one time. */
sobel_terminate();

fclose(fd);

return 0;
}

/* End of code generation (main.c) */

25-41
25 Deploying Generated Code

Generate the Sobel Filter Application


1 Navigate to the working folder if you are not currently in it.
2 Create a configuration object for a C standalone executable.
cfg = coder.config('exe');
3 Generate a C standalone executable for the Sobel filter using the configuration object
and the modified main function.
codegen -report -config cfg sobel main.c main.h

By default, if you are running MATLAB on a Windows platform, the executable


sobel.exe is generated in the current working folder. If you are running MATLAB on a
platform other than Windows, the file extension is the corresponding extension for that
platform. By default, the code generated for the executable is in the folder codegen/
exe/sobel.

Run the Sobel Filter Application


1 Create the MATLAB matrix gray if it is not currently in your MATLAB workspace:
im = imread('hello.jpg');
gray = (0.2989 * double(im(:,:,1)) + 0.5870 * double(im(:,:,2)) + 0.1140 * double(im(:,:,3)))/255;

2 Write the matrix gray into a binary file using the fopen and fwrite commands.
The application reads in this binary file.
fid = fopen('gray.bin', 'w');
fwrite(fid, gray, 'double');
fclose(fid);
3 Run the executable, passing to it the file gray.bin and the threshold value 0.7.

To run the example in MATLAB on a Windows platform:


system('sobel.exe gray.bin 0.7');

The executable generates the file edge.bin.

Display the Resulting Image


1 Read the file edge.bin into a MATLAB matrix edgeImExe using the fopen and
fread commands.

25-42
Use an Example C Main in an Application

fd = fopen('edge.bin', 'r');
edgeImExe = fread(fd, size(gray), 'uint8');
fclose(fd);
2 Pass the matrix edgeImExe to the function repmat and display the image.

im3Exe = repmat(edgeImExe, [1 1 3]);


image(im3Exe);

The image matches the images from the MATLAB and MEX functions.

Related Examples
• “Structure of Generated Example C/C++ Main Function” on page 25-49
• “Incorporate Generated Code Using an Example Main Function” on page 25-18
• “Call a C Static Library Function from C Code” on page 25-2

25-43
25 Deploying Generated Code

Package Code for Other Development Environments


In this section...
“When to Package Code” on page 25-44
“Package Generated Code Using the MATLAB Coder App” on page 25-44
“Package Generated Code at the Command Line” on page 25-45
“Specify packNGo Options” on page 25-47

When to Package Code


To relocate the generated code files to another development environment, such as a
system or an integrated development environment (IDE) that does not include MATLAB,
use the packNGo function at the command line or the Package option in the MATLAB
Coder app. The files are packaged in a compressed file that you can relocate and unpack
using a standard zip utility.

See “Package Generated Code Using the MATLAB Coder App” on page 25-44 and
“Package Generated Code at the Command Line” on page 25-45.

Package Generated Code Using the MATLAB Coder App


This example shows how to package generated code into a zip file for relocation using the
Package option in the MATLAB Coder app. By default, MATLAB Coder creates the zip
file in the current working folder.

1 In a local writable folder, for example c:\work, write a function foo that takes two
double inputs.

function y = foo(A,B)
y = A + B;
end
2 Open the MATLAB Coder app. On the MATLAB Toolstrip Apps tab, under Code
Generation, click the MATLAB Coder app icon.
3 On the Select Source Files page, enter the name of the entry-point function foo.
Click Next to go to the Define Input Types page.
4 Specify that inputs A and B are scalar doubles. Click Next to go to the Check for
Run-Time Issues page.

25-44
Package Code for Other Development Environments

5 Check for run-time issues. In the Check for Run-Time Issues dialog box, enter
code that calls foo with scalar double inputs. For example:

foo(1,2)
Click Check for Issues.

To check for run-time issues, the app generates and runs a MEX function. The app
does not find issues for foo. Click Next to go to the Generate Code page.
6 In the Generate dialog box, set the Build Type to Source Code, Static
Library, Dynamic Library, or Executable. You cannot package the code
generated for MEX targets.
7 Click Generate. Click Next to go to the Finish Workflow page.
8 On the Finish Workflow page, click Package.
9 When prompted, save the package file using the default path and file name. By
default, MATLAB Coder derives the name of the package file from the project name,
in this case foo_pkg.zip, and saves it in the current working folder. This zip file
contains the C code and header files required for relocation. It does not contain:

• Compile flags
• Defines
• Makefiles
• Example main files, unless you configure code generation to generate and compile
the example main function. See “Incorporate Generated Code Using an Example
Main Function” on page 25-18.
10 Inspect the contents of foo_pkg.zip in your working folder to verify that it is ready
for relocation to the destination system. Depending on the zip tool that you use, you
can potentially open and inspect the file without unpacking it.

You can now relocate the resulting zip file to the desired development environment
and unpack the file.

Package Generated Code at the Command Line


This example shows how to package generated code into a zip file for relocation using the
packNGo function at the command line.

1 In a local writable folder, for example c:\work, write a function foo that takes two
double inputs.

25-45
25 Deploying Generated Code

function y = foo(A,B)
y = A + B;
end
2 Generate a static library for function foo. (packNGo does not package MEX function
code.)

codegen -report -config:lib foo -args {0,0}

codegen generates code in the c:\work\codegen\lib\foo folder.


3 Load the buildInfo object.

load('c:\work\codegen\lib\foo\buildInfo.mat')
4 Create the zip file.

packNGo(buildInfo, 'fileName', 'foo.zip');


Alternatively, use the notation:

buildInfo.packNGo('fileName', 'foo.zip');

The packNGo function creates a zip file, foo.zip, in the current working folder.
This zip file contains the C code and header files required for relocation. It does not
contain:

• Compile flags
• Defines
• Makefiles
• Example main files, unless you configure code generation to generate and compile
the example main function. See “Incorporate Generated Code Using an Example
Main Function” on page 25-18.

In this example, you specify only the file name. Optionally, you can specify additional
packaging options. See “Specify packNGo Options” on page 25-47.
5 Inspect the contents of foo.zip to verify that it is ready for relocation to the
destination system. Depending on the zip tool that you use, you can potentially
open and inspect the file without unpacking it. If you need to unpack the file and
you packaged the generated code files as a hierarchical structure, you will need to
unpack the primary and secondary zip files. When you unpack the secondary zip
files, relative paths of the files are preserved.

25-46
Package Code for Other Development Environments

You can now relocate the resulting zip file to the desired development environment
and unpack the file.

Specify packNGo Options


You can specify options for the packNGo function.

To Specify
Change the structure of the file packNGo(buildInfo, {'packType'
packaging to hierarchical 'hierarchical'});
Change the structure of the file packNGo(buildInfo, {'packType'
packaging to hierarchical and 'hierarchical'...
rename the primary zip file 'fileName' 'zippedsrcs'});
Include all header files found on packNGo(buildInfo, {'minimalHeaders'
the include path in the zip file false});
(rather than the minimal header
files required to build the code)
Generate warnings for parse packNGo(buildInfo, {'ignoreParseError'
errors and missing files true...
'ignoreFileMissing' true});

For more information, see packNGo in “Build Information Methods” on page 21-139.

Choose a Structure for the Zip File

Before you generate and package the files, decide whether you want to package the files
in a flat or hierarchical folder structure. By default, the packNGo function packages the
files in a single, flat folder structure. This approach is the simplest and might be the
optimal choice.

If Use
You are relocating files to an IDE that does A single, flat folder structure
not use the generated makefile, or the code
is not dependent on the relative location of
required static files

25-47
25 Deploying Generated Code

If Use
The target development environment must A hierarchical structure
maintain the folder structure of the source
environment because it uses the generated
makefile, or the code is dependent on the
relative location of files

If you use a hierarchical structure, the packNGo function creates two levels of zip files.
There is a primary zip file, which in turn contains the following secondary zip files:

• mlrFiles.zip — files in your matlabroot folder tree


• sDirFiles.zip — files in and under your build folder where you initiated code
generation
• otherFiles.zip — required files not in the matlabroot or start folder trees

Paths for the secondary zip files are relative to the root folder of the primary zip file,
maintaining the source development folder structure.

25-48
Structure of Generated Example C/C++ Main Function

Structure of Generated Example C/C++ Main Function

In this section...
“Contents of the File main.c or main.cpp” on page 25-49
“Contents of the File main.h” on page 25-52

When you build an application that uses generated C/C++ code, you must provide a C/C+
+ main function that calls the generated code.

By default, for code generation of C/C++ source code, static libraries, dynamic libraries,
and executables, MATLAB Coder generates an example C/C++ main function. This
function is a template that can help you incorporate generated C/C++ code into your
application. The example main function declares and initializes data, including
dynamically allocated data. It calls entry-point functions but does not use values that the
entry point functions return. To use the example main function, copy the example main
source and header files to a location outside of the build folder, and then modify the files
in the new location to meet the requirements of your application.

MATLAB Coder generates source and header files for the example main function in the
examples subfolder of the build folder. For C code generation, it generates the files
main.c and main.h. For C++ code generation, it generates the files main.cpp and
main.h.

Contents of the File main.c or main.cpp


For the example main source file main.c or main.cpp, MATLAB Coder generates the
following sections:

• “Include Files” on page 25-50


• “Function Declarations” on page 25-50
• “Argument Initialization Functions” on page 25-50
• “Entry-Point Functions” on page 25-51
• “Main Function” on page 25-51

By default, MATLAB Coder also generates comments in the example main source file
that can help you modify the example main function to use in your application.

25-49
25 Deploying Generated Code

Include Files

This section includes the header files required to call code that is not in the example
main source file. If you call external functions when you modify the example main source
file, include any other required header files.

Function Declarations

This section declares the function prototypes for the argument initialization and entry-
point functions that are defined in the example main source file. Modify the function
prototypes to match modifications that you make in the function definitions. Declare new
function prototypes for functions that you define in the example main source file.

Argument Initialization Functions

This section defines an initialization function for each data type that the entry-point
functions use as an argument. The argument initialization function initializes the size
of the argument to a default value and the values of the data to zero. The function then
returns the initialized data. Change these size and data values to meet the requirements
of your application.

For an argument with dimensions of size <dimSizes> and MATLAB C/C++ data type
<baseType>, the example main source file defines an initialization function with the
name argInit_<dimSizes>_<baseType>. For example, for a 5-by-5 array with data of
MATLAB type double, the example main source file defines the argument initialization
function argInit_5x5_real_T.

MATLAB Coder alters the name of the argument initialization functions as follows:

• If any of the dimensions are variable-size, MATLAB Coder designates the size of
these dimensions as d<maxSize>, where <maxSize> is the maximum size of that
dimension. For example, for an array with data of MATLAB type double with a
first dimension of static size 2 and a second dimension that can vary in size up
to 10, the example main source file defines the argument initialization function
argInit_2xd10_real_T.
• If any of the dimensions are unbounded, MATLAB Coder designates the size of these
dimensions as Unbounded.
• If the return type of the initialization function is an emxArray, MATLAB Coder
defines the function as returning a pointer to the emxArray.
• If the length of the initialization function name exceeds the maximum number of
characters set for function names in the configuration settings, MATLAB Coder

25-50
Structure of Generated Example C/C++ Main Function

prepends an identifier string to the front of the function name. MATLAB Coder
then truncates the function name to the maximum allowed number of characters for
identifier length.

Note: By default, the maximum number of characters allowed for generated


identifiers is 31. To specify the value set for the maximum identifier length using
the MATLAB Coder app, select the Maximum identifier length value on the
Code Appearance tab of the code generation settings. To specify the value set for
the maximum identifier using the command-line interface, change the value of the
MaxIdLength configuration object setting.

Entry-Point Functions

This section defines a function for each MATLAB entry-point function. For a MATLAB
function foo.m, the example main source file defines an entry-point function main_foo.
This function creates the variables and calls the data initialization functions that the C/
C++ source function foo.c or foo.cpp requires. It calls this C/C++ source function but
does not return the result. Modify main_foo so that it takes inputs and returns outputs
as required by your application.

Main Function

This section defines a main function that does the following:

• If your output language is C, it declares and names the variables argc and argv
but casts them to void. If your output language is C++, the generated example main
declares, but does not name, the variables argc and argv.
• Calls the initialize function foo_initialize, which is named for the alphabetically
first entry-point function foo declared for code generation. Call the initialize function
only once, even if you have multiple entry-point functions called in the function main.
• Calls each of the entry-point functions once.
• Calls the terminate function foo_terminate, which is named for the alphabetically
first entry-point function foo declared for code generation. Call the terminate
function only once, even if you have multiple entry-point functions called in the
function main.
• Returns zero.

Modify the function main, including the inputs and outputs of main and of the entry-
point functions, to meet the requirements of your application.

25-51
25 Deploying Generated Code

Contents of the File main.h


For the example main header file main.h, MATLAB Coder generates the following:

• “Include Guard” on page 25-52


• “Include Files” on page 25-52
• “Function Declarations” on page 25-52

By default, MATLAB Coder also generates comments in main.h that can help you
modify the example main function to use in your application.

Include Guard

main.h uses an include guard to prevent the contents of the file from being included
multiple times. The include guard contains the include files and function declarations
within an #ifndef construct.

Include Files

main.h includes the header files required to call code that is not defined within it.

Function Declarations

main.h declares the function prototype for the main function that is defined in the
example main source file main.c or main.cpp.

Related Examples
• “Incorporate Generated Code Using an Example Main Function” on page 25-18
• “Use an Example C Main in an Application” on page 25-21

More About
• “How MATLAB Coder Infers C/C++ Data Types” on page 27-9

25-52
Troubleshoot Failures in Deployed Code

Troubleshoot Failures in Deployed Code


If your deployed code fails, consider regenerating the code with run-time error detection
enabled. When you enable run-time error detection, the generated code includes code
that detects and reports errors, such as out-of-bounds array indexing. If the code detects
one of these errors, it reports a message and terminates the program. Running the code
that includes the error checks helps you to see if one of these errors caused the failure.

Run-time error detection can affect the performance of the generated code. If
performance is a consideration for your application, when you finish troubleshooting,
regenerate the code with run-time error detection disabled.

See “Run-Time Error Detection and Reporting in Standalone C/C++ Code” on page 22-29
and “Generate Standalone Code That Detects and Reports Run-Time Errors” on page
22-31.

25-53
26

Accelerating MATLAB Algorithms

• “Workflow for Accelerating MATLAB Algorithms” on page 26-2


• “Best Practices for Using MEX Functions to Accelerate MATLAB Algorithms” on page
26-4
• “Edge Detection on Images” on page 26-7
• “Accelerate MATLAB Algorithms” on page 26-14
• “Modifying MATLAB Code for Acceleration” on page 26-15
• “Control Run-Time Checks” on page 26-16
• “Algorithm Acceleration Using Parallel for-Loops (parfor)” on page 26-19
• “Control Compilation of parfor-Loops” on page 26-25
• “Reduction Assignments in parfor-Loops” on page 26-26
• “Classification of Variables in parfor-Loops” on page 26-27
• “Accelerate MATLAB Algorithms That Use Parallel for-Loops (parfor)” on page
26-36
• “Specify Maximum Number of Threads in parfor-Loops” on page 26-37
• “Troubleshooting parfor-Loops” on page 26-38
• “Accelerating Simulation of Bouncing Balls” on page 26-39
26 Accelerating MATLAB Algorithms

Workflow for Accelerating MATLAB Algorithms

26-2
Workflow for Accelerating MATLAB Algorithms

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
• “Modifying MATLAB Code for Acceleration” on page 26-15

26-3
26 Accelerating MATLAB Algorithms

Best Practices for Using MEX Functions to Accelerate MATLAB


Algorithms
In this section...
“Accelerate Code That Dominates Execution Time” on page 26-4
“Include Loops Inside MEX Function” on page 26-4
“Avoid Generating MEX Functions from Unsupported Functions” on page 26-5
“Avoid Generating MEX Functions if Built-In MATLAB Functions Dominate Run Time”
on page 26-6
“Minimize MEX Function Calls” on page 26-6

When you choose a section of MATLAB code to accelerate, the following practices are
recommended.

Accelerate Code That Dominates Execution Time


Find the section of MATLAB code that dominates run time. Accelerate this section of the
code using a MEX function as follows:

1 Place this section of the code inside a separate MATLAB function.


2 From this MATLAB function, generate a MEX function.
3 From your original MATLAB code, call the MEX function.

To find the execution time of each MATLAB instruction, use MATLAB Profiler.

• To open the Profiler from the command line, type profile viewer.
• To open Profiler from the MATLAB Editor window, under the Editor tab, click Run
and Time.

For more information about using the Profiler to measure run time of MATLAB code, see
“Profile to Improve Performance”.

Include Loops Inside MEX Function


Instead of calling a MEX function inside a loop in the MATLAB code, include the loop
inside the MEX function. Including the loop eliminates the overheads in calling the MEX
function for every run of the loop.

26-4
Best Practices for Using MEX Functions to Accelerate MATLAB Algorithms

For example, the following code finds the greatest element in every row of a 1000–by–
1000 matrix, mat. You can accelerate sections 1,2, and 3 using a MEX function.:

% Section 1 begins
for i = 1:10000

% Section 2 begins
max = mat(i,0); % Initialize max
for j = 1:10000

% Section 3 begins
if (mat(i,j) > max)
max = mat(i,j) % Store the current maximum
end
% Section 3 ends

end
% Section 2 ends

end
% Section 1 ends

Accelerate section 1 using a MEX function. Accelerate section 1 first so that the MEX
function is called only once.. If you cannot accelerate section 1 first, then accelerate
sections 2 or 3, in that order. If section 2 (or 3) is accelerated using a MEX function, the
function is called 10000 (or 10000 × 10000) times.

Avoid Generating MEX Functions from Unsupported Functions


Check that the section of MATLAB code that you accelerate does not contain many
functions and language features that are unsupported by MATLAB Coder. For a list
of supported functions, see “Functions and Objects Supported for C and C++ Code
Generation — Alphabetical List” on page 4-2.

Note: In certain situations, you might have to accelerate sections of code even though
they contain a few unsupported functions. Declare an unsupported function as extrinsic
to invoke the original MATLAB function instead of the code generated for the function.
You can declare a function as extrinsic by using coder.extrinsic or wrapping it in an
feval statement. See “Call MATLAB Functions” on page 14-11.

26-5
26 Accelerating MATLAB Algorithms

Avoid Generating MEX Functions if Built-In MATLAB Functions Dominate


Run Time
Use MEX functions to accelerate MATLAB code only if user-generated code dominates
the run time.

Avoid generating MEX functions if computationally intensive, built-in MATLAB


functions dominate the run time. These functions are pre-compiled and optimized, so the
MATLAB code is not accelerated significantly using a MEX function. Examples of such
functions include svd, eig ,fft, qr, lu.

Tip You can invoke computationally intensive, built-in MATLAB functions from your
MEX function. Declare the MATLAB function as extrinsic using coder.extrinsic or
wrap it in an feval statement. For more information, see “Call MATLAB Functions” on
page 14-11.

Minimize MEX Function Calls


Accelerate as much of the MATLAB code as possible using one MEX function instead of
several MEX functions called at lower levels. This minimizes the overheads in calling the
MEX functions.

For example, consider the function,testfunc,which calls two functions,testfunc_1 and


testfunc_2:

function [y1,y2] = testfunc(x1,x2)


y1 = testfunc_1(x1,x2);
y2 = testfunc_2(x1,x2);
end

Instead of generating MEX functions individually for testfunc_1 and testfunc_2, and
then calling the MEX functions in testfunc, generate a MEX function for testfunc
itself.

26-6
Edge Detection on Images

Edge Detection on Images


This example shows how to generate a standalone C library from MATLAB code that
implements a simple Sobel filter that performs edge detection on images. The example
also shows how to generate and test a MEX function in MATLAB prior to generating C
code to verify that the MATLAB code is suitable for code generation.

Prerequisites

There are no prerequisites for this example.

Create a New Folder and Copy Relevant Files

The following code will create a folder in your current working folder (pwd). The new
folder will only contain the files that are relevant for this example. If you do not want to
affect the current folder (or if you cannot generate files in this folder), you should change
your working folder.

Run Command: Create a New Folder and Copy Relevant Files

coderdemo_setup('coderdemo_edge_detection');

About the 'sobel' Function

The sobel.m function takes an image (represented as a double matrix) and a threshold
value and returns an image with the edges detected (based on the threshold value).

type sobel

% edgeImage = sobel(originalImage, threshold)


% Sobel edge detection. Given a normalized image (with double values)
% return an image where the edges are detected w.r.t. threshold value.
function edgeImage = sobel(originalImage, threshold) %#codegen
assert(all(size(originalImage) <= [1024 1024]));
assert(isa(originalImage, 'double'));
assert(isa(threshold, 'double'));

k = [1 2 1; 0 0 0; -1 -2 -1];
H = conv2(double(originalImage),k, 'same');
V = conv2(double(originalImage),k','same');
E = sqrt(H.*H + V.*V);
edgeImage = uint8((E > threshold) * 255);

26-7
26 Accelerating MATLAB Algorithms

Generate the MEX Function

Generate a MEX function using the 'codegen' command.

codegen sobel

Before generating C code, you should first test the MEX function in MATLAB to ensure
that it is functionally equivalent to the original MATLAB code and that no run-time
errors occur. By default, 'codegen' generates a MEX function named 'sobel_mex' in the
current folder. This allows you to test the MATLAB code and MEX function and compare
the results.

Read in the Original Image

Use the standard 'imread' command.

im = imread('hello.jpg');
image(im);

26-8
Edge Detection on Images

Convert Image to a Grayscale Version

Convert the color image (shown above) to an equivalent grayscale image with normalized
values (0.0 for black, 1.0 for white).

gray = (0.2989 * double(im(:,:,1)) + 0.5870 * double(im(:,:,2)) + 0.1140 * double(im(:,

Run the MEX Function (The Sobel Filter)

Pass the normalized image and a threshold value.

edgeIm = sobel_mex(gray, 0.7);

26-9
26 Accelerating MATLAB Algorithms

Display the Result


im3 = repmat(edgeIm, [1 1 3]);
image(im3);

Generate Standalone C Code


codegen -config coder.config('lib') sobel

Using 'codegen' with the '-config coder.config('lib')' option produces a standalone C


library. By default, the code generated for the library is in the folder codegen/lib/sobel/

Inspect the Generated Function


type codegen/lib/sobel/sobel.c

26-10
Edge Detection on Images

/*
* File: sobel.c
*
* MATLAB Coder version : 3.1
* C/C++ source code generated on : 08-Jan-2016 00:50:43
*/

/* Include Files */
#include "rt_nonfinite.h"
#include "sobel.h"
#include "sobel_emxutil.h"
#include "sqrt.h"
#include "conv2.h"

/* Function Declarations */
static double rt_roundd_snf(double u);

/* Function Definitions */

/*
* Arguments : double u
* Return Type : double
*/
static double rt_roundd_snf(double u)
{
double y;
if (fabs(u) < 4.503599627370496E+15) {
if (u >= 0.5) {
y = floor(u + 0.5);
} else if (u > -0.5) {
y = u * 0.0;
} else {
y = ceil(u - 0.5);
}
} else {
y = u;
}

return y;
}

/*
* Arguments : const emxArray_real_T *originalImage

26-11
26 Accelerating MATLAB Algorithms

* double threshold
* emxArray_uint8_T *edgeImage
* Return Type : void
*/
void sobel(const emxArray_real_T *originalImage, double threshold,
emxArray_uint8_T *edgeImage)
{
emxArray_real_T *H;
emxArray_real_T *V;
int b_H;
int c_H;
emxInit_real_T(&H, 2);
emxInit_real_T(&V, 2);

/* edgeImage = sobel(originalImage, threshold) */


/* Sobel edge detection. Given a normalized image (with double values) */
/* return an image where the edges are detected w.r.t. threshold value. */
conv2(originalImage, H);
b_conv2(originalImage, V);
b_H = H->size[0] * H->size[1];
emxEnsureCapacity((emxArray__common *)H, b_H, (int)sizeof(double));
b_H = H->size[0];
c_H = H->size[1];
c_H *= b_H;
for (b_H = 0; b_H < c_H; b_H++) {
H->data[b_H] = H->data[b_H] * H->data[b_H] + V->data[b_H] * V->data[b_H];
}

emxFree_real_T(&V);
b_sqrt(H);
b_H = edgeImage->size[0] * edgeImage->size[1];
edgeImage->size[0] = H->size[0];
edgeImage->size[1] = H->size[1];
emxEnsureCapacity((emxArray__common *)edgeImage, b_H, (int)sizeof(unsigned
char));
c_H = H->size[0] * H->size[1];
for (b_H = 0; b_H < c_H; b_H++) {
edgeImage->data[b_H] = (unsigned char)rt_roundd_snf((double)(H->data[b_H] >
threshold) * 255.0);
}

emxFree_real_T(&H);
}

26-12
Edge Detection on Images

/*
* File trailer for sobel.c
*
* [EOF]
*/

Cleanup

Remove files and return to original folder

Run Command: Cleanup


cleanup

26-13
26 Accelerating MATLAB Algorithms

Accelerate MATLAB Algorithms


For many applications, you can generate MEX functions to accelerate MATLAB
algorithms. If you have a Fixed-Point Designer license, you can generate MEX functions
to accelerate fixed-point MATLAB algorithms. After generating a MEX function, test
it in MATLAB to verify that its operation is functionally equivalent to the original
MATLAB algorithm. Then compare the speed of execution of the MEX function with that
of the MATLAB algorithm. If the MEX function speed is not sufficiently fast, you might
improve it using one of the following methods:

• Choosing a different C/C++ compiler.

It is important that you use a C/C++ compiler that is designed to generate high
performance code.

Note: The default MATLAB compiler for Windows 64-bit platforms, lcc, is designed
to generate code quickly. It is not designed to generate high performance code.
• “Modifying MATLAB Code for Acceleration” on page 26-15
• “Control Run-Time Checks” on page 26-16

26-14
Modifying MATLAB Code for Acceleration

Modifying MATLAB Code for Acceleration

How to Modify Your MATLAB Code for Acceleration


You might improve the efficiency of the generated code using one of the following
optimizations:

• “Unroll for-Loops” on page 29-37


• “Inline Code” on page 29-10
• “Eliminate Redundant Copies of Function Inputs” on page 29-7

26-15
26 Accelerating MATLAB Algorithms

Control Run-Time Checks


In this section...
“Types of Run-Time Checks” on page 26-16
“When to Disable Run-Time Checks” on page 26-16
“How to Disable Run-Time Checks” on page 26-17

Types of Run-Time Checks


The code generated for your MATLAB functions includes the following run-time checks
and external calls to MATLAB functions.

• Memory integrity checks

These checks detect violations of memory integrity in code generated for MATLAB
functions and stop execution with a diagnostic message.

Caution These checks are enabled by default. Without memory integrity checks,
violations result in unpredictable behavior.
• Responsiveness checks in code generated for MATLAB functions

These checks enable periodic checks for Ctrl+C breaks in code generated for MATLAB
functions. Enabling responsiveness checks also enables graphics refreshing.

Caution These checks are enabled by default. Without these checks, the only way to
end a long-running execution might be to terminate MATLAB.
• Extrinsic calls to MATLAB functions

Extrinsic calls to MATLAB functions, for example to display results, are enabled by
default for debugging purposes. For more information about extrinsic functions, see
“Declaring MATLAB Functions as Extrinsic Functions” on page 14-12.

When to Disable Run-Time Checks


Generally, generating code with run-time checks enabled results in more generated
code and slower MEX function execution than generating code with the checks disabled.

26-16
Control Run-Time Checks

Similarly, extrinsic calls are time consuming and increase memory usage and execution
time. Disabling run-time checks and extrinsic calls usually results in streamlined
generated code and faster MEX function execution. The following table lists issues to
consider when disabling run-time checks and extrinsic calls.

Consider disabling... Only if...


Memory integrity checks You have already verified that array
bounds and dimension checking is
unnecessary.
Responsiveness checks You are sure that you will not need to stop
execution of your application using Ctrl+C.
Extrinsic calls You are using extrinsic calls only for
functions that do not affect application
results.

How to Disable Run-Time Checks


You can disable run-time checks explicitly from the project settings dialog box, the
command line, or a MEX configuration dialog box.

Disabling Run-Time Checks Using the MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Set Build type to MEX.
3 Click More Settings.
4 On the Speed tab, clear Ensure memory integrity, Enable responsiveness to
CTRL+C and graphics refreshing, or Keep Extrinsic calls, as applicable.

Disabling Run-Time Checks From the Command Line

1 In the MATLAB workspace, define the MEX configuration object:

mexcfg = coder.config('mex');
2 At the command line, set the IntegrityChecks, ExtrinsicCalls, or
ResponsivenessChecks properties to false, as applicable:

mexcfg.IntegrityChecks = false;

26-17
26 Accelerating MATLAB Algorithms

mexcfg.ExtrinsicCalls = false;
mexcfg.ResponsivenessChecks = false;

26-18
Algorithm Acceleration Using Parallel for-Loops (parfor)

Algorithm Acceleration Using Parallel for-Loops (parfor)


In this section...
“Parallel for-Loops (parfor) in Generated Code” on page 26-19
“How parfor-Loops Improve Execution Speed” on page 26-20
“When to Use parfor-Loops” on page 26-20
“When Not to Use parfor-Loops” on page 26-20
“parfor-Loop Syntax” on page 26-21
“parfor Restrictions” on page 26-21

Parallel for-Loops (parfor) in Generated Code


To potentially accelerate execution, you can generate MEX functions or C/C++ code from
MATLAB code that contains parallel for-loops (parfor-loops).

A parfor-loop, like the standard MATLAB for-loop, executes a series of statements


(the loop body) over a range of values. Unlike the for-loop, however, the iterations of the
parfor-loop can run in parallel on multiple cores on the target hardware.

Running the iterations in parallel might significantly improve execution speed of the
generated code. For more information, see “How parfor-Loops Improve Execution Speed”
on page 26-20.

Note: The parallel execution occurs only in generated MEX functions or C/C++ code;
not the original MATLAB code. To accelerate your MATLAB code, generate a MEX
function from the parfor-loop. Then, call the MEX function from your code. For more
information, see “Workflow for Accelerating MATLAB Algorithms” on page 26-2.

MATLAB Coder software uses the Open Multiprocessing (OpenMP) application


interface to support shared-memory, multicore code generation. If you want distributed
parallelism, use the Parallel Computing Toolbox™ product. By default, MATLAB Coder
uses up to as many cores as it finds available. If you specify the number of threads to
use, MATLAB Coder uses at most that number of cores for the threads, even if additional
cores are available. For more information, see parfor.

Because the loop body can execute in parallel on multiple threads, it must conform
to certain restrictions. If MATLAB Coder software detects loops that do not conform

26-19
26 Accelerating MATLAB Algorithms

to parfor specifications, it produces an error. For more information, see “parfor


Restrictions” on page 26-21.

How parfor-Loops Improve Execution Speed


A parfor-loop might provide better execution speed than its analogous for-loop because
several threads can compute concurrently on the same loop.

Each execution of the body of a parfor-loop is called an iteration. The threads evaluate
iterations in arbitrary order and independently of each other. Because each iteration is
independent, they do not have to be synchronized. If the number of threads is equal to
the number of loop iterations, each thread performs one iteration of the loop. If there are
more iterations than threads, some threads perform more than one loop iteration.

For example, when a loop of 100 iterations runs on 20 threads, each thread executes five
iterations of the loop simultaneously. If your loop takes a long time to run because of
the large number of iterations or individual iterations being lengthy, you can reduce the
run time significantly using multiple threads. In this example, you might not, however,
get 20 times improvement in speed because of parallelization overheads, such as thread
creation and deletion.

When to Use parfor-Loops


Use parfor when you have:

• Many iterations of a simple calculation. parfor divides the loop iterations into
groups so that each thread executes one group of iterations.
• A loop iteration that takes a long time to execute. parfor executes the iterations
simultaneously on different threads. Although this simultaneous execution does not
reduce the time spent on an individual iteration, it might significantly reduce overall
time spent on the loop.

When Not to Use parfor-Loops


Do not use parfor when:

• An iteration of your loop depends on other iterations. Running the iterations in


parallel can lead to erroneous results.

26-20
Algorithm Acceleration Using Parallel for-Loops (parfor)

To help you avoid using parfor when an iteration of your loop depends on other
iterations, MATLAB Coder specifies a rigid classification of variables. For more
information, see “Classification of Variables in parfor-Loops” on page 26-27. If
MATLAB Coder detects loops that do not conform to the parfor specifications, it does
not generate code and produces an error.

Reductions are an exception to the rule that loop iterations must be independent. A
reduction variable accumulates a value that depends on all the iterations together,
but is independent of the iteration order. For more information, see “Reduction
Variables” on page 26-29.
• There are only a few iterations that perform some simple calculations.

Note: For small number of loop iterations, you might not accelerate execution due
to parallelization overheads. Such overheads include time taken for thread creation,
data synchronization between threads and thread deletion.

parfor-Loop Syntax
• For a parfor-loop, use this syntax:
parfor i = InitVal:EndVal
parfor (i = InitVal:EndVal)
• To specify the maximum number of threads, use this syntax:
parfor (i = InitVal:EndVal,NumThreads)

For more information, see parfor.

parfor Restrictions
• The parfor loop does not support the syntax:
parfor (i=initVal:step:endVal)
parfor i=initVal:step:endVal
• You must use a compiler that supports the Open Multiprocessing (OpenMP)
application interface. See http://www.mathworks.com/support/compilers/
current_release/. If you use a compiler that does not support OpenMP, MATLAB
Coder treats the parfor-loops as for-loops. In the generated MEX function or C/C++
code, the loop iterations run on a single thread.

26-21
26 Accelerating MATLAB Algorithms

• The type of the loop index must be representable by an integer type on the target
hardware. Use a type that does not require a multiword type in the generated code.
• parfor for standalone code generation requires the toolchain approach for building
executables or libraries. Do not change settings that cause the code generation
software to use the template makefile approach. See “Project or Configuration is
Using the Template Makefile” on page 24-22.
• Do not use the following constructs in the body of a parfor loop:

• Nested parfor-loops

You can have a parfor loop inside another parfor-loop. However, the inner
parfor loop will be executed on a single thread as an ordinary for-loop.

Inside a parfor loop, you can call a function that contains another parfor-loop.
• Break and return statements

You cannot use break or return statements inside a parfor-loop.


• Global variables

You cannot write to a global variable inside a parfor-loop.


• Reductions on MATLAB classes

You cannot use reductions on MATLAB classes inside a parfor-loop.


• Reductions on char variables

You cannot use reductions on char variables inside a parfor-loop.

For example, you cannot generate C code for the following MATLAB code:

c = char(0);
parfor i=1:10
c = c + char(1);
end
In the parfor-loop, MATLAB makes c a double. For code generation, c cannot
change type.
• Reductions using external C code

You cannot use coder.ceval in reductions inside a parfor-loop.. For example,


you cannot generate code for the following parfor-loop:

26-22
Algorithm Acceleration Using Parallel for-Loops (parfor)

parfor i=1:4
y=coder.ceval('myCFcn',y,i);
end
Instead, write a local function that calls the C code using coder.ceval and call
this function in the parfor-loop. For example:

parfor i=1:4
y = callMyCFcn(y,i);
end
...
function y = callMyCFcn(y,i)
y = coder.ceval('mCyFcn', y , i);
end
• Extrinsic function calls

You cannot call extrinsic functions using coder.extrinsic inside a parfor-loop.


Calls to functions that contain extrinsic calls result in a run-time error.
• Inlining functions

MATLAB Coder does not inline functions into parfor-loops, including functions
that use coder.inline('always').
• Unrolling loops

You cannot use coder.unroll inside a parfor-loop.

If a loop is unrolled inside a parfor-loop, MATLAB Coder cannot classify the


variable. For example:

for j=coder.unroll(3:6)
y(i,j)=y(i,j)+i+j;
end
This code is unrolled to:

y(i,3)=y(i,3)+i+3;
...
y(i,6)=y(i,6)+i+6;
In the unrolled code, MATLAB Coder cannot classify the variable y because y is
indexed in different ways inside the parfor-loop.

MATLAB Coder does not support variables that it cannot classify. For more
information, see “Classification of Variables in parfor-Loops” on page 26-27.

26-23
26 Accelerating MATLAB Algorithms

• varargin/varargout

You cannot use varargin or varargout inside a parfor-loop.

26-24
Control Compilation of parfor-Loops

Control Compilation of parfor-Loops


By default, MATLAB Coder generates code that can run the parfor-loop on multiple
threads. To treat the parfor-loops as for-loops that run on a single thread, disable
parfor:

• By using the codegen function with -O disable:openmp option at the command


line.
• By setting Enable OpenMP library if possible to No under All Settings tab in the
project settings dialog box.

When to Disable parfor


Disable parfor if you want to:

• Compare the execution times of the serial and parallel versions of the generated code.
• Investigate failures. If the parallel version of the generated code fails, disable parfor
and generate a serial version to facilitate debugging.
• Use C compilers that do not support OpenMP.

26-25
26 Accelerating MATLAB Algorithms

Reduction Assignments in parfor-Loops

What are Reduction Assignments?


Reduction assignments, or reductions, are an exception to the rule that loop iterations
must be independent. A reduction variable accumulates a value that depends on all the
loop iterations together, but is independent of the iteration order. For a list of supported
reduction variables see “Reduction Variables” on page 26-29.

Multiple Reductions in a parfor-Loop


You can perform the same reduction assignment multiple times within a parfor-loop
provided that you use the same data type each time.

For example, in the following parfor-loop, u(i) and v(i) must be the same type.

parfor i = 1:10;
X = X + u(i);
X = X + v(i);
end

Similarly, the following example is valid provided that u(i) and v(i) are the same type.

parfor i=1:10
r = foo(r,u(i));
r = foo(r,v(i));
end

26-26
Classification of Variables in parfor-Loops

Classification of Variables in parfor-Loops


In this section...
“Overview” on page 26-27
“Sliced Variables” on page 26-28
“Broadcast Variables” on page 26-29
“Reduction Variables” on page 26-29
“Temporary Variables” on page 26-34

Overview
MATLAB Coder classifies variables inside a parfor-loop into one of the categories in
the following table. It does not support variables that it cannot classify. If a parfor-
loop contains variables that cannot be uniquely categorized or if a variable violates its
category restrictions, the parfor-loop generates an error.

Classification Description
Loop Serves as a loop index for arrays
Sliced An array whose segments are operated on by different iterations of
the loop
Broadcast A variable defined before the loop whose value is used inside the loop,
but not assigned inside the loop
Reduction Accumulates a value across iterations of the loop, regardless of
iteration order
Temporary A variable created inside the loop, but unlike sliced or reduction
variables, not available outside the loop

Each of these variable classifications appears in this code fragment:


a=0;
c=pi;
z=0;
r=rand(1,10);
parfor i=1:10
a=i; % 'a' is a temporary variable
z=z+i; % 'z' is a reduction variable
b(i)=r(i); % 'b' is a sliced output variable;

26-27
26 Accelerating MATLAB Algorithms

% 'r' a sliced input variable


if i<=c % 'c' is a broadcast variable
d=2*a; % 'd' is a temporary variable
end
end

Sliced Variables
A sliced variable is one whose value can be broken up into segments, or slices, which are
then operated on separately by different threads. Each iteration of the loop works on a
different slice of the array.

In the next example, a slice of A consists of a single element of that array:


parfor i = 1:length(A)
B(i) = f(A(i));
end

Characteristics of a Sliced Variable

A variable in a parfor-loop is sliced if it has the following characteristics:

• Type of First-Level Indexing — The first level of indexing is parentheses, ().


• Fixed Index Listing — Within the first-level parenthesis, the list of indices is the
same for all occurrences of a given variable.
• Form of Indexing — Within the list of indices for the variable, exactly one index
involves the loop variable.
• Shape of Array — In assigning to a sliced variable, the right-hand side of the
assignment is not [] or '' (these operators indicate deletion of elements).

Type of First-Level Indexing. For a sliced variable, the first level of indexing is enclosed
in parentheses, (). For example, A(...). If you reference a variable using dot notation,
A.x, the variable is not sliced.

Variable A on the left is not sliced; variable A on the right is sliced:


A.q(i,12) A(i,12).q

Fixed Index Listing. Within the first-level parentheses of a sliced variable's indexing, the
list of indices is the same for all occurrences of a given variable.

Variable B on the left is not sliced because B is indexed by i and i+1 in different places.
Variable B on the right is sliced.

26-28
Classification of Variables in parfor-Loops

parfor i = 1:10 parfor i = 1:10


B(i) = B(i+1) + 1; B(i+1) = B(i+1) + 1;
end end

Form of Indexing. Within the list of indices for a sliced variable, one index is of the form
i, i+k, i-k, k+i, or k-i.

• i is the loop variable.


• k is a constant or a simple (nonindexed) variable.
• Every other index is a constant, a simple variable, colon, or end.

When you use other variables along with the loop variable to index an array, you cannot
set these variables inside the loop. These variables are constant over the execution of the
entire parfor statement. You cannot combine the loop variable with itself to form an
index expression.

In the following examples, i is the loop variable, j and k are nonindexed variables.
Variable A Is Not Sliced Variable A Is Sliced
A(i+f(k),j,:,3) A(i+k,j,:,3)
A(i,20:30,end) A(i,:,end)
A(i,:,s.field1) A(i,:,k)

Shape of Array. A sliced variable must maintain a constant shape. In the following
examples, the variable A is not sliced:
A(i,:) = [];
A(end + 1) = i;

Broadcast Variables
A broadcast variable is a variable other than the loop variable or a sliced variable that is
not modified inside the loop.

Reduction Variables
A reduction variable accumulates a value that depends on all the iterations together, but
is independent of the iteration order.

This example shows a parfor-loop that uses a scalar reduction assignment. It uses the
reduction variable x to accumulate a sum across 10 iterations of the loop. The execution
order of the iterations on the threads does not matter.

26-29
26 Accelerating MATLAB Algorithms

x = 0;
parfor i = 1:10
x = x + i;
end
x

Where expr is a MATLAB expression, reduction variables appear on both sides of an


assignment statement.

X = X + expr X = expr + X
X = X - expr See “Reduction Assignments, Associativity,
and Commutativity of Reduction Functions”
on page 26-33
X = X .* expr X = expr .* X
X = X * expr X = expr * X
X = X & expr X = expr & X
X = X | expr X = expr | X
X = min(X, expr) X = min(expr, X)
X = max(X, expr) X = max(expr, X)
X=f(X, expr) X = f(expr, X)
Function f must be a user-defined See “Reduction Assignments, Associativity,
function. and Commutativity of Reduction Functions”
on page 26-33

Each of the allowed statements is referred to as a reduction assignment. A reduction


variable can appear only in assignments of this type.

The following example shows a typical usage of a reduction variable X:

X = ...; % Do some initialization of X


parfor i = 1:n
X = X + d(i);
end

This loop is equivalent to the following, where each d(i) is calculated by a different
iteration:

X = X + d(1) + ... + d(n)

26-30
Classification of Variables in parfor-Loops

If the loop were a regular for-loop, the variable X in each iteration would get its value
either before entering the loop or from the previous iteration of the loop. However, this
concept does not apply to parfor-loops.

In a parfor-loop, the value of X is not updated directly inside each thread. Rather,
additions of d(i) are done in each thread, with i ranging over the subset of 1:n being
performed on that thread. The software then accumulates the results into X.

Similarly, the reduction:


r=r<op> x(i)
is equivalent to:
r=r<op>x(1)] <op>x(2)...<op>x(n)
The operation <op> is first applied to x(1)...x(n), then the partial result is applied to
r.

If operation <op> takes two inputs, it should meet one of the following criteria:

• Take two arguments of typeof(x(i)) and return typeof(x(i))


• Take one argument of typeof(r) and one of typeof(x(i)) and return typeof(r)

Rules for Reduction Variables


Use the same reduction function or operation in all reduction assignments

For a reduction variable, you must use the same reduction function or operation in all
reduction assignments for that variable. In the following example, the parfor-loop on
the left is not valid because the reduction assignment uses + in one instance, and * in
another.

Invalid Use of Reduction Variable Valid Use of Reduction Variable


parfor i = 1:n parfor i = 1:n
if A > 5*k if A > 5*k
A = A + 1; A = A * 3;
else else
A = A * 2; A = A * 2;
end end

Restrictions on reduction function parameter and return types

A reduction r=r<op> x(i), should take arguments of typeof(x(i)) and return


typeof(x(i)) or take arguments of typeof(r) and typeof(x(i)) and return
typeof(r).

26-31
26 Accelerating MATLAB Algorithms

In the following example, in the invalid loop, r is a fixed-point type and 2 is not. To fix
this issue, cast 2 to be the same type as r.

Invalid Use of Reduction Variable Valid Use of Reduction Variable


function r = fiops(in) r=fi(in,'WordLength',20,...
r=fi(in,'WordLength',20,... 'FractionLength',14,...
'FractionLength',14,... 'SumMode','SpecifyPrecision',...
'SumMode','SpecifyPrecision',... 'SumWordLength',20,...
'SumWordLength',20,... 'SumFractionLength',14,...
'SumFractionLength',14,... 'ProductMode','SpecifyPrecision',...
'ProductMode', 'SpecifyPrecision',... 'ProductWordLength',20,...
'ProductWordLength',20,... 'ProductFractionLength',14);
'ProductFractionLength',14); T = r.numerictype;
parfor i = 1:10 F = r.fimath;
r = r*2; parfor i = 1:10
end r = r*fi(2,T,F);
end

26-32
Classification of Variables in parfor-Loops

In the following example, the reduction function fcn is invalid because it does not
handle the case when input u is fixed point. (The + and * operations are automatically
polymorphic.) You must write a polymorphic version of fcn to handle the expected input
types.

Invalid Use of Reduction Variable Valid Use of Reduction Variable


function [y0, y1, y2] = pfuserfcn(u) function [y0, y1, y2] = pfuserfcn(u)
y0 = 0; y0 = 0;
y1 = 1; y1 = 1;
[F, N] = fiprops(); [F, N] = fiprops();
y2 = fi(1,N,F); y2 = fi(1,N,F);
parfor (i=1:numel(u),12) parfor (i=1:numel(u),12)
y0 = y0 + u(i); y0 = y0 + u(i);
y1 = y1 * u(i); y1 = y1 * u(i);
y2 = fcn(y2, u(i)); y2 = fcn(y2, u(i));
end end
end end
% fcn handles inputs of type double
function y = fcn(u, v) % and fi
y = u * v; function y = fcn(u, v)
end if isa(u,'double')
y = u * v;
else
[F, N] = fiprops();
y = u * fi(v,N,F);
end
end

function [F, N] = fiprops()


N = numerictype(1,96,30);
F = fimath('ProductMode',...
'SpecifyPrecision',...
'ProductWordLength',96);
end

Reduction Assignments, Associativity, and Commutativity of Reduction Functions

Reduction Assignments. MATLAB Coder does not allow reduction variables to be read
anywhere in the parfor-loop except in reduction statements. In the following example,
the call foo(r) after the reduction statement r=r+i causes the loop to be invalid.

function r = temp %#codegen


r = 0;

26-33
26 Accelerating MATLAB Algorithms

parfor i=1:10
r = r + i;
foo(r);
end
end

Associativity in Reduction Assignments. If you use a user-defined function f in the


definition of a reduction variable, to get deterministic behavior of parfor-loops, the
reduction function f must be associative.

Note: If f is not associative, MATLAB Coder does not generate an error. You must write
code that meets this recommendation.

To be associative, the function f must satisfy the following for all a, b, and c:
f(a,f(b,c)) = f(f(a,b),c)

Commutativity in Reduction Assignments. Some associative functions, including +, .,


min, and max, are also commutative. That is, they satisfy the following for all a and b:

f(a,b) = f(b,a)

The function f of a reduction assignment must be commutative. If f is not commutative,


different executions of the loop might result in different answers.

Unless f is a known noncommutative built-in, the software assumes that it is


commutative.

Temporary Variables
A temporary variable is a variable that is the target of a direct, nonindexed assignment,
but is not a reduction variable. In the following parfor-loop, a and d are temporary
variables:
a = 0;
z = 0;
r = rand(1,10);
parfor i = 1:10
a = i; % Variable a is temporary
z = z + i;
if i <= 5

26-34
Classification of Variables in parfor-Loops

d = 2*a; % Variable d is temporary


end
end

In contrast to the behavior of a for-loop, before each iteration of a parfor-loop,


MATLAB Coder effectively clears temporary variables. Because the iterations must
be independent, the values of temporary variables cannot be passed from one iteration
of the loop to another. Therefore, temporary variables must be set inside the body of a
parfor-loop, so that their values are defined separately for each iteration.

A temporary variable in the context of the parfor statement is different from a variable
with the same name that exists outside the loop.

Uninitialized Temporaries

Because temporary variables are cleared at the beginning of every iteration, MATLAB
Coder can detect certain cases in which an iteration through the loop uses the temporary
variable before it is set in that iteration. In this case, MATLAB Coder issues a static
error rather than a run-time error, because there is little point in allowing execution to
proceed if a run-time error will occur. For example, suppose you write:
b = true;
parfor i = 1:n
if b && some_condition(i)
do_something(i);
b = false;
end
...
end

This loop is acceptable as an ordinary for-loop, but as a parfor-loop, b is a temporary


variable because it occurs directly as the target of an assignment inside the loop.
Therefore, it is cleared at the start of each iteration, so its use in the condition of the
if is uninitialized. (If you change parfor to for, the value of b assumes sequential
execution of the loop, so that do_something(i) is executed for only the lower values of
i until b is set false.)

26-35
26 Accelerating MATLAB Algorithms

Accelerate MATLAB Algorithms That Use Parallel for-Loops (parfor)


This example shows how to generate a MEX function for a MATLAB algorithm that
contains a parfor-loop.

1 Write a MATLAB function that contains a parfor-loop. For example:

function a = test_parfor %#codegen


a=ones(10,256);
r=rand(10,256);
parfor i=1:10
a(i,:)=real(fft(r(i,:)));
end
2 Generate a MEX function for test_parfor. At the MATLAB command line, enter:

codegen test_parfor
codegen generates a MEX function, test_parfor_mex, in the current folder.
3 Run the MEX function. At the MATLAB command line, enter:
test_parfor_mex

Because you did not specify the maximum number of threads to use, the generated
MEX function executes the loop iterations in parallel on the maximum number of
available cores.

26-36
Specify Maximum Number of Threads in parfor-Loops

Specify Maximum Number of Threads in parfor-Loops


This example shows how to specify the maximum number of threads to use for a parfor-
loop. Because you specify the maximum number of threads to use, the generated MEX
function executes the loop iterations in parallel on as many cores as available, up to the
maximum number that you specify. If you specify more threads than there are cores
available, the MEX function uses the available cores.

1 Write a MATLAB function, specify_num_threads, that uses one input to specify


the maximum number of threads to execute a parfor-loop in the generated MEX
function. For example:
function y = specify_num_threads(u) %#codegen
y = ones(1,100);
% u specifies maximum number of threads
parfor (i = 1:100,u)
y(i) = i;
end
end
2 Generate a MEX function for specify_num_threads. Use -args {0} to specify
that input u is a scalar double. Use -report to generate a code generation report. At
the MATLAB command line, enter:
codegen -report specify_num_threads -args {0}
codegen generates a MEX function, specify_num_threads_mex, in the current
folder.
3 Run the MEX function, specifying that it try to run in parallel on four threads. At
the MATLAB command line, enter:
specify_num_threads_mex(4)

The generated MEX function runs on up to four cores. If less than four cores are
available, the MEX function runs on the maximum number of cores available at the
time of the call.

26-37
26 Accelerating MATLAB Algorithms

Troubleshooting parfor-Loops

Global or Persistent Declarations in parfor-Loop


The body of a parfor-loop cannot contain a global or persistent variable
declaration.

Compiler Does Not Support OpenMP


The MATLAB Coder software uses the Open Multiprocessing (OpenMP) application
interface to support shared-memory, multicore code generation. To generate a loop that
runs in parallel on shared-memory, multicore platforms, use a compiler that supports
OpenMP. OpenMP is enabled by default. If your compiler does not support OpenMP,
MATLAB Coder generates a warning.

Install a compiler that supports OpenMP. See http://www.mathworks.com/support/


compilers/current_release/.

26-38
Accelerating Simulation of Bouncing Balls

Accelerating Simulation of Bouncing Balls


This example shows how to accelerate MATLAB algorithm execution using a generated
MEX function. It uses the 'codegen' command to generate a MEX function for a
complicated application that uses multiple MATLAB files. You can use 'codegen' to check
that your MATLAB code is suitable for code generation and, in many cases, to accelerate
your MATLAB algorithm. You can run the MEX function to check for run-time errors.

Prerequisites

There are no prerequisites for this example.

Create a New Folder and Copy Relevant Files

The following code will create a folder in your current working folder (pwd). The new
folder will contain only the files that are relevant for this example. If you do not want
to affect the current folder (or if you cannot generate files in this folder), change your
working folder.

Run Command: Create a New Folder and Copy Relevant Files


coderdemo_setup('coderdemo_bouncing_balls');

About the 'run_balls' Function

The run_balls.m function takes a single input to specify the number of bouncing balls to
simulate. The simulation runs and plots the balls bouncing until there is no energy left
and returns the state (positions) of all the balls.
type run_balls

% balls = run_balls(n)
% Given 'n' number of balls, run a simulation until the balls come to a
% complete halt (or when the system has no more kinetic energy).
function balls = run_balls(n) %#codegen

coder.extrinsic('fprintf');

% Copyright 2010-2013 The MathWorks, Inc.

% Seeding the random number generator will guarantee that we get


% precisely the same simulation every time we call this function.
old_settings = rng(1283,'V4');

26-39
26 Accelerating MATLAB Algorithms

% The 'cdata' variable is a matrix representing the colordata bitmap which


% will be rendered at every time step.
cdata = zeros(400,600,'uint8');

% Setup figure windows


im = setup_figure_window(cdata);

% Get the initial configuration for 'n' balls.


balls = initialize_balls(cdata, n);

energy = 2; % Something greater than 1


iteration = 1;
while energy > 1
% Clear the bitmap
cdata(:,:) = 0;
% Apply one iteration of movement
[cdata,balls,energy] = step_function(cdata,balls);
% Render the current state
cdata = draw_balls(cdata, balls);
iteration = iteration + 1;
if mod(iteration,10) == 0
fprintf(1, 'Iteration %d\n', iteration);
end
refresh_image(im, cdata);
end
fprintf(1, 'Completed iterations: %d\n', iteration);

% Restore RNG settings.


rng(old_settings);

Generate the MEX Function


First, generate a MEX function using the command codegen followed by the name of the
MATLAB file to compile. Pass an example input (-args 0) to indicate that the generated
MEX function will be called with an input of type double.
codegen run_balls -args 0

The 'run_balls' function calls other MATLAB functions, but you need to specify only the
entry-point function when calling 'codegen'.

By default, 'codegen' generates a MEX function named 'run_balls_mex' in the current


folder. This allows you to test the MATLAB code and MEX function and compare the
results.

26-40
Accelerating Simulation of Bouncing Balls

Compare Results

Run and time the original 'run_balls' function followed by the generated MEX function.
tic, run_balls(50); t1 = toc;
tic, run_balls_mex(50); t2 = toc;

Iteration 10
Iteration 20
Iteration 30
Iteration 40
Iteration 50
Iteration 60
Iteration 70
Iteration 80
Iteration 90
Iteration 100
Iteration 110
Iteration 120
Iteration 130
Iteration 140
Iteration 150
Iteration 160
Iteration 170
Iteration 180
Iteration 190
Iteration 200
Iteration 210
Iteration 220
Iteration 230
Iteration 240
Iteration 250
Iteration 260
Iteration 270
Iteration 280
Completed iterations: 281
Iteration 10
Iteration 20
Iteration 30
Iteration 40
Iteration 50
Iteration 60
Iteration 70
Iteration 80
Iteration 90

26-41
26 Accelerating MATLAB Algorithms

Iteration 100
Iteration 110
Iteration 120
Iteration 130
Iteration 140
Iteration 150
Iteration 160
Iteration 170
Iteration 180
Iteration 190
Iteration 200
Iteration 210
Iteration 220
Iteration 230
Iteration 240
Iteration 250
Iteration 260
Iteration 270
Iteration 280
Completed iterations: 281

26-42
Accelerating Simulation of Bouncing Balls

Estimated speed up is:


fprintf(1, 'Speed up: x ~%2.1f\n', t1/t2);

Speed up: x ~6.5

Clean Up

Remove files and return to original folder

Run Command: Cleanup


cleanup

26-43
27

Calling C/C++ Functions from


Generated Code

• “External Function Calls from Generated Code” on page 27-2


• “Call External Functions by Using coder.ceval” on page 27-6
• “Return Multiple Values from C Functions” on page 27-8
• “How MATLAB Coder Infers C/C++ Data Types” on page 27-9
27 Calling C/C++ Functions from Generated Code

External Function Calls from Generated Code


In this section...
“Calling External Functions from Generated Code” on page 27-2
“Why Call External Functions from Generated Code?” on page 27-2
“How To Call External Functions” on page 27-2
“Pass Arguments by Reference to External Functions” on page 27-3
“Manipulate C Data” on page 27-4

Calling External Functions from Generated Code


You can call external functions from generated code. The external functions must have a
C programming interface. The code generation software provides functions for:

• Calling external functions from generated code.


• Passing arguments by reference to external code.
• Manipulating C/C++ data.

By using these functions, you gain unrestricted access to external code. Misuse of
these functions or errors in your code can destabilize MATLAB when generating MEX
functions.

Why Call External Functions from Generated Code?


Call external functions from generated code when you want to:

• Use legacy code.


• Use your own optimized functions instead of generated code.
• Interface your libraries and hardware with MATLAB functions.

How To Call External Functions


To call external functions, use one of the following methods:

• The coder.ceval function in your MATLAB code. coder.ceval passes function


input and output arguments to C/C++ functions by value or by reference.

27-2
External Function Calls from Generated Code

• The coder.ExternalDependency class to define methods that call the functions. These
methods use the coder.ceval function. In your MATLAB code, use these methods to
call external functions.

Define the called functions in external C/C++ source files, object files, or libraries. You
must then include C/C++ source files, libraries, object files, and header files in the build
configuration. See “Specify External File Locations” on page 25-12.

Pass Arguments by Reference to External Functions


By default, coder.ceval passes arguments by value to the C/C++ function whenever
C/C++ supports passing arguments by value. You can pass MATLAB variables as
arguments by reference to external C/C++ functions with the following constructs:

• coder.ref — pass value by reference.


• coder.rref — pass read-only value by reference.
• coder.wref — pass write-only value by reference.

These constructs offer the following benefits:

• Passing values by reference optimizes memory use.

When you pass arguments by value, MATLAB Coder passes a copy of the value of
each argument to the C/C++ function to preserve the original values. When you pass
arguments by reference, MATLAB Coder does not copy values. If you need to pass
large matrices to the C/C++ function, the memory savings can be significant.

Passing write-only values by reference allows you to return multiple outputs.

Use coder.wref to return multiple outputs from your C/C++ function, including
arrays and matrices. Otherwise, the C/C++ function can return only a single scalar
value through its return statement.

Do not store pointers that you pass to C/C++ functions because MATLAB Coder
optimizes the code based on the assumption that you do not store the addresses of
these variables. Storing the addresses might invalidate our optimizations leading to
incorrect behavior. For example, if a MATLAB function passes a pointer to an array
using coder.ref, coder.rref, or coder.wref, then the C/C++ function can modify
the data in the array—but you should not store the pointer for future use.

When you pass arguments by reference using coder.rref, coder.wref, and


coder.ref, the corresponding C/C++ function signature must declare these variables

27-3
27 Calling C/C++ Functions from Generated Code

as pointers of the same data type. Otherwise, the C/C++ compiler generates a type
mismatch error.

For example, suppose your MATLAB function calls an external C function ctest:

function y = fcn()
u = pi;

y = 0;
y = coder.ceval('ctest',u);

Now suppose the C function signature is:

double ctest(double *a)

When you compile the code, you get a type mismatch error because coder.ceval calls
ctest with an argument of type double when ctest expects a pointer to a double-
precision, floating-point value.

Match the types of arguments in coder.ceval with their counterparts in the C function.
For instance, you can fix the error in the previous example by passing the argument by
reference:

y = coder.ceval('ctest', coder.rref(u));

You can pass a reference to an element of a matrix. For example, to pass the second
element of the matrix v, you can use the following code:

y = coder.ceval('ctest', coder.ref(v(1,2)));

Manipulate C Data
The construct coder.opaque allows you to manipulate C/C++ data that a MATLAB
function does not recognize. You can store the opaque data in a variable or structure field
and pass it to, or return it from, a C/C++ function using coder.ceval.

Declaring Opaque Data

The following example uses coder.opaque to declare a variable f as a FILE * type.


% This example returns its own source code by using
% fopen/fread/fclose.
function buffer = filetest
%#codegen

27-4
External Function Calls from Generated Code

% Declare 'f' as an opaque type 'FILE *'


f = coder.opaque('FILE *', 'NULL');
% Open file in binary mode
f = coder.ceval('fopen', cstring('filetest.m'), cstring('rb'));

% Read from file until end of file is reached and put


% contents into buffer
n = int32(1);
i = int32(1);
buffer = char(zeros(1,8192));
while n > 0
% By default, MATLAB converts constant values
% to doubles in generated code
% so explicit type conversion to in32 is inserted.
n = coder.ceval('fread', coder.ref(buffer(i)), int32(1), ...
int32(numel(buffer)), f);
i = i + n;
end
coder.ceval('fclose',f);

buffer = strip_cr(buffer);

% Put a C termination character '\0' at the end of MATLAB string


function y = cstring(x)
y = [x char(0)];

% Remove character 13 (CR) but keep character 10 (LF)


function buffer = strip_cr(buffer)
j = 1;
for i = 1:numel(buffer)
if buffer(i) ~= char(13)
buffer(j) = buffer(i);
j = j + 1;
end
end
buffer(i) = 0;

27-5
27 Calling C/C++ Functions from Generated Code

Call External Functions by Using coder.ceval


In this section...
“Workflow for Calling External Functions” on page 27-6
“Best Practices for Calling External Code from Generated Code” on page 27-7

Workflow for Calling External Functions


To call external C/C++ functions from generated code:

1 Write your C/C++ functions in external source files or libraries.


2 Create header files, if required.

The header file defines the data types used by the C/C++ functions that MATLAB
Coder generates in code, as described in “Mapping MATLAB Types to C/C++ Types”
on page 27-9.

Tip One way to add these type definitions is to include the header file tmwtypes.h,
which defines general data types supported by MATLAB. This header file is in
matlabroot/extern/include. Check the definitions in tmwtypes.h to determine
if they are compatible with your target. If not, define these types in your own header
files.
3 In your MATLAB function, add calls to coder.ceval to invoke your external C/C++
functions.

You need one coder.ceval statement for each call to a C/C++ function. In your
coder.ceval statements, use coder.ref, coder.rref, and coder.wref
constructs as required (see “Pass Arguments by Reference to External Functions” on
page 27-3).
4 Include the custom C/C++ functions in the build. See “Specify External File
Locations” on page 25-12.
5 Check for compilation warnings about data type mismatches.

Perform this check so that you catch type mismatches between C/C++ and MATLAB
(see “How MATLAB Coder Infers C/C++ Data Types” on page 27-9).
6 Generate code and fix errors.

27-6
Call External Functions by Using coder.ceval

7 Run your application.

Best Practices for Calling External Code from Generated Code


The following are recommended practices when calling C/C++ code from generated code.

• Start small. — Create a test function and learn how coder.ceval and its related
constructs work.
• Use separate files. — Create a file for each C/C++ function that you call. Make sure
that you call the C/C++ functions with suitable types.
• In a header file, declare a function prototype for each function that you call, and
include this header file in the generated code. For more information, see “Specify
External File Locations” on page 25-12.

27-7
27 Calling C/C++ Functions from Generated Code

Return Multiple Values from C Functions


The C language restricts functions from returning multiple outputs; instead, they return
only a single, scalar value. The constructs coder.ref and coder.wref allow MATLAB
functions to exchange multiple outputs with the external C functions that they call.

For example, suppose you write a MATLAB function foo that takes two inputs x and y
and returns three outputs a, b, and c. In MATLAB, you call this function as follows:

[a, b, c] = foo (x, y)

If you rewrite foo as a C function, you cannot return a, b, and c through the return
statement. You can create a C function with multiple pointer type input arguments, and
pass the output parameters by reference. For example:
foo(double x, double y, double *a, double *b, double *c)
Then you can call the C function with multiple outputs from a MATLAB function using
coder.wref constructs:

coder.ceval ('foo', x, y, ...


coder.wref(a), coder.wref(b), coder.wref(c));

Similarly, suppose that one of the outputs a is also an input argument. In this case,
create a C function with multiple pointer type input arguments, and pass the output
parameters by reference. For example:
foo(double *a, double *b, double *c)
Then call the C function from a MATLAB function using coder.wref and coder.rref
constructs:
coder.ceval ('foo', coder.ref(a), coder.wref(b), coder.wref(c));

27-8
How MATLAB Coder Infers C/C++ Data Types

How MATLAB Coder Infers C/C++ Data Types


In this section...
“Mapping MATLAB Types to C/C++ Types” on page 27-9
“Mapping 64-Bit Integer Types to C/C++” on page 27-10
“Mapping Fixed-Point Types to C/C++” on page 27-11
“Mapping Arrays to C/C++” on page 27-11
“Mapping Complex Values to C/C++” on page 27-12
“Mapping Structures to C/C++ Structures” on page 27-13
“Mapping Strings to C/C++” on page 27-13
“Mapping Multiword Types to C/C++” on page 27-14

Mapping MATLAB Types to C/C++ Types


The C/C++ type associated with a MATLAB variable or expression is based on the
following properties:

• Class
• Size
• Complexity

By default, the MATLAB Coder software tries to use built-in C/C++ types in the
generated code. If the target hardware supports the built-in C type, the software
generates a built-in C type for these MATLAB types.
int8 uint8 double
int16 uint16 single
int32 uint32 char
int64 uint64
The built-in C/C++ type that the code generation software uses depends on the target
hardware. You have the option to use MathWorks C/C++ data types instead of built-in
C/C++ types. For information about setting this option, see “Specify Data Types Used in
Generated Code” on page 21-38.

The following translation table shows how the MATLAB Coder software maps MATLAB
types to MathWorks C/C++ data types.

27-9
27 Calling C/C++ Functions from Generated Code

MATLAB Type MATLAB C/C++ Data Type Reference Type for MATLAB C/
C++ Data Type
int8 int8_T int8_T *
int16 int16_T int16_T *
int32 int32_T int32_T *
int64 See “Mapping 64-Bit Integer Types to C/C++” on page
27-10.
uint8 uint8_T uint8_T *
uint16 uint16_T uint16_T *
uint32 uint32_T uint32_T *
uint64 See “Mapping 64-Bit Integer Types to C/C++” on page
27-10.
double real_T real_T *
single real32_T real32_T *
char char_T char *
logical boolean_T boolean_T *
fi numerictype also influences the C/C++ type. Integer
type varies according to the MATLAB fixed-point type,
as described in “Mapping Fixed-Point Types to C/C++” on
page 27-11.
struct The MATLAB Coder software translates structures to C/C
++ types field-by-field. See “Mapping Structures to C/C++
Structures” on page 27-13 .
complex See “Mapping Complex Values to C/C++” on page
27-12.
Multiword types See “Mapping Multiword Types to C/C++” on page
27-14.

Mapping 64-Bit Integer Types to C/C++


The C/C++ data type associated with a 64-bit integer MATLAB type depends on the sizes
of the integer types on the target hardware. If a type wide enough for a 64-bit type does
not exist, then a 64-bit type maps to a multiword type.

27-10
How MATLAB Coder Infers C/C++ Data Types

By default, MATLAB Coder software tries to map int64 and uint64 types to built-in C
types. For a multiword type, the software uses a built-in C type for the array in the struct
that represents the multiword type. You have the option to use MATLAB C/C++ data
types instead of built-in types. The following table shows how 64 bit integer types map to
MATLAB C/C++ data types.

MATLAB Type MATLAB C/C++ Type Multiword MATLAB C/C++


Type
int64 int64_T int64m_T
uint64 uint64_T uint64m_T
complex int64 cint64_T cint64m_T
complex uint64 cuint64_T cuint64m_T

See “Mapping Multiword Types to C/C++” on page 27-14.

Mapping Fixed-Point Types to C/C++


The numerictype properties of a fi object determine the C/C++ data type. By default,
the code generation software tries to use built-in C/C++ types. However, you can
choose to use MATLAB C/C++ data types instead. The following table shows how the
Signedness, WordLength, and FractionLength properties determine the MATLAB
C/C++ data type. The MATLAB C/C++ data type is the next larger target word size that
can store the fixed-point value, based on its word length. The sign of the integer type
matches the sign of the fixed-point type.

Signedness Word Length Fraction Length MATLAB C/C++ Reference Type


Data Type for MATLAB C/
C++ Data Type
1 16 15 int16_T int16_T *
1 13 10 int16_T int16_T *
0 19 15 uint32_T uint32_T *
1 8 7 int8_T int8_T *

Mapping Arrays to C/C++


By default, the code generation software tries to use built-in C/C++ types for arrays in
the generated code. However, you can choose to use MATLAB C/C++ data types instead.

27-11
27 Calling C/C++ Functions from Generated Code

The following translation table shows how MATLAB Coder software maps arrays to
MATLAB C/C++ data types. In the first column, the arrays are specified by the MATLAB
function zeros:

zeros(number of rows, number of columns, data type)


MATLAB array data is laid out in column major order.

Array MATLAB C/C++ Data Type Reference Type for MATLAB


C/C++ Data Type
zeros(10, 5, 'int8') int8_T int8_T *
zeros(5, 10, 'int8') int8_T int8_T *
zeros(3, 7) real_T real_T *
zeros(10, 1, 'single') real32_T real32_T *

Mapping Complex Values to C/C++


The following translation table shows how the MATLAB Coder software infers complex
values in generated code.

Complex MATLAB C/C++ Data Type Reference Type for MATLAB C/


C++ Data Type
complex int8 cint8_T cint8_T *
complex int16 cint16_T cint16_T *
complex int32 cint32_T cint32_T *
complex int64 See “Mapping 64-Bit Integer Types to C/C++” on page
27-10.
complex uint8 cuint8_T cuint8_T *
complex uint16 cuint16_T cuint16_T *
complex uint32 cuint32_T cuint32_T *
complex uint64 See “Mapping 64-Bit Integer Types to C/C++” on page
27-10.
complex double creal_T creal_T *
complex single creal32_T creal32_T *

27-12
How MATLAB Coder Infers C/C++ Data Types

The MATLAB Coder software defines each complex value as a structure with a real
component re and an imaginary component im, as in this example from tmwtypes.h:
typedef struct {
real32_T re;/* Real component*/
real32_T im;/* Imaginary component*/
} creal32_T;
MATLAB Coder uses the names re and im in generated code to represent the
components of complex numbers. For example, suppose you define a variable x of
type creal32_T. The generated code references the real component as x.re and the
imaginary component as x.im.

If your C/C++ library requires a different representation, you can define your own
versions of MATLAB Coder complex types. However, you must use the names re for the
real components and im for the imaginary components in your definitions.

The MATLAB Coder software represents a matrix of complex numbers as an array of


structures.

Mapping Structures to C/C++ Structures


The MATLAB Coder software translates structures to C/C++ types field-by-field. The
order of the field items is preserved as the order in MATLAB. To control the name of the
generated C/C++ structure type, or provide a definition, use the coder.cstructname
function.

Note: If you are not using dynamic memory allocation, arrays in structures translate into
single-dimension arrays, not pointers.

Mapping Strings to C/C++


The MATLAB Coder software translates MATLAB strings to C/C++ character matrices.
You cannot use character matrices as substitutes for C/C++ strings because they are
not null terminated. You can terminate a MATLAB string with a null character by
appending a zero to the end of the string: ['sample string' 0]. A single character
translates to a C/C++ char type, not a C/C++ string.

Caution Failing to null-terminate your MATLAB strings might cause C/C++ code to crash
without compiler errors or warnings.

27-13
27 Calling C/C++ Functions from Generated Code

Mapping Multiword Types to C/C++


The MATLAB Coder software translates multiword types to structure types that contain
an array of integers. The array dimensions depend on the size of the widest integer type
on the target hardware. For example, for a 128-bit fixed-point type, if the widest integer
type on the target hardware is 32-bits, the software generates a structure with an array
of four 32-bit integers.
typedef struct
{
unsigned int chunks[4];
} uint128m_T;
If the widest integer type on the target hardware is long with a size of 64-bits, MATLAB
Coder generates a structure with an array of two 64-bit long integers.
typedef struct
{
unsigned long chunks[2];
} uint128m_T;

27-14
28

External Code Integration

• “External Code Integration for Code Generation” on page 28-2


• “Encapsulating the Interface to External Code” on page 28-3
• “Best Practices for Using coder.ExternalDependency” on page 28-4
• “Encapsulate Interface to an External C Library” on page 28-6
• “Update Build Information from MATLAB code” on page 28-9
• “Call External Functions Encapsulated by coder.ExternalDependency” on page
28-10
28 External Code Integration

External Code Integration for Code Generation


You can integrate external code with MATLAB code intended for code generation. The
external code can be external libraries, object files, or C/C++ source code.

The basic workflow is:

1 Create the external code.


2 Call the external code from MATLAB code.
3 Specify the external file locations.
4 Generate code from the MATLAB code.

Call the external code and specify the file locations in one of the following ways:

• Use coder.ExternalDependency to encapsulate the interface to the external code.


The updateBuildInfo method specifies file locations and other build information.
Write methods that define the programming interface to the external functions. In
your MATLAB code, use these methods to call the external functions.
• Use coder.ceval to call external functions from your MATLAB code. When you
generate code, define the locations of external files.
• Use coder.ceval to call external functions from your MATLAB code. Use
coder.updateBuildInfo to specify external file locations and update build
information.

See Also
coder.ceval | coder.ExternalDependency | coder.updateBuildInfo

More About
• “Encapsulating the Interface to External Code” on page 28-3
• “Specify External File Locations” on page 25-12
• “External Function Calls from Generated Code” on page 27-2

28-2
Encapsulating the Interface to External Code

Encapsulating the Interface to External Code


Use the coder.ExternalDependency class to encapsulate the interface between
external code and MATLAB code intended for code generation. With the encapsulation,
you can separate the details of the interface from your MATLAB code. The methods of
coder.ExternalDependency:

• specify the location of external files


• update build information
• define the programming interface for external functions

In your MATLAB code, you can call the external code without providing build
information.

The workflow is:

1 Write a class definition file for a class that derives from


coder.ExternalDependency.
2 Store the class definition file in a folder on the MATLAB path.
3 In your MATLAB code, use a method of the class to call an external function.
4 Generate code from your MATLAB code.

See Also
coder.ExternalDependency

Related Examples
• “Encapsulate Interface to an External C Library” on page 28-6

More About
• “Best Practices for Using coder.ExternalDependency” on page 28-4

28-3
28 External Code Integration

Best Practices for Using coder.ExternalDependency

In this section...
“Terminate Code Generation for Unsupported External Dependency” on page 28-4
“Parameterize Methods for MATLAB and Generated Code” on page 28-4
“Parameterize updateBuildInfo for Multiple Platforms” on page 28-5

Terminate Code Generation for Unsupported External Dependency


The isSupportedContext method returns true if the external code interface is
supported in the build context. If the external code interface is not supported, do not
return false. Instead, use error to terminate code generation with an error message. For
example:

function tf = isSupportedContext(ctx)
if ctx.isMatlabHostTarget()
tf = true;
else
error('MyLibrary is not available for this target');
end
end

Parameterize Methods for MATLAB and Generated Code


Parameterize methods that call external functions so that the methods run in MATLAB.
For example:

...
if coder.target('MATLAB')
% running in MATLAB, use built-in addition
c = a + b;
else
% running in generated code, call library function
coder.ceval('adder_initialize');
end
...

28-4
Best Practices for Using coder.ExternalDependency

Parameterize updateBuildInfo for Multiple Platforms


Parameterize the updateBuildInfo method to support multiple platforms. For
example, use coder.BuildConfig.getStdLibInfo to get the platform-specific library
file extensions.
...
[~, linkLibExt, execLibExt, ~] = ctx.getStdLibInfo()
% Link files
linkFiles = strcat('adder', linkLibExt);
buildInfo.addLinkObjects(linkFiles, linkPath, linkPriority, ...
linkPrecompiled, linkLinkOnly, group);
...

See Also
coder.BuildConfig | coder.ExternalDependency | error

Related Examples
• “Encapsulate Interface to an External C Library” on page 28-6

28-5
28 External Code Integration

Encapsulate Interface to an External C Library


This example shows how to encapsulate the interface to an external C dynamic linked
library using coder.ExternalDependency.

Write a function adder that returns the sum of its inputs.


function c = adder(a,b)
%#codegen
c = a + b;
end

Generate a library that contains adder.


codegen('adder','-args', {-2,5}, '-config:dll', '-report');

Write the class definition file AdderAPI.m to encapsulate the library interface.
%================================================================
% This class abstracts the API to an external Adder library.
% It implements static methods for updating the build information
% at compile time and build time.
%================================================================

classdef AdderAPI < coder.ExternalDependency


%#codegen

methods (Static)

function bName = getDescriptiveName(~)


bName = 'AdderAPI';
end

function tf = isSupportedContext(ctx)
if ctx.isMatlabHostTarget()
tf = true;
else
error('adder library not available for this target');
end
end

function updateBuildInfo(buildInfo, ctx)


[~, linkLibExt, execLibExt, ~] = ctx.getStdLibInfo();

% Header files

28-6
Encapsulate Interface to an External C Library

hdrFilePath = fullfile(pwd, 'codegen', 'dll', 'adder');


buildInfo.addIncludePaths(hdrFilePath);

% Link files
linkFiles = strcat('adder', linkLibExt);
linkPath = hdrFilePath;
linkPriority = '';
linkPrecompiled = true;
linkLinkOnly = true;
group = '';
buildInfo.addLinkObjects(linkFiles, linkPath, ...
linkPriority, linkPrecompiled, linkLinkOnly, group);

% Non-build files
nbFiles = 'adder';
nbFiles = strcat(nbFiles, execLibExt);
buildInfo.addNonBuildFiles(nbFiles,'','');
end

%API for library function 'adder'


function c = adder(a, b)
if coder.target('MATLAB')
% running in MATLAB, use built-in addition
c = a + b;
else
% running in generated code, call library function
coder.cinclude('adder.h');

% Because MATLAB Coder generated adder, use the


% housekeeping functions before and after calling
% adder with coder.ceval.
% Call initialize function before calling adder for the
% first time.

coder.ceval('adder_initialize');
c = 0;
c = coder.ceval('adder', a, b);

% Call the terminate function after


% calling adder for the last time.

coder.ceval('adder_terminate');
end

28-7
28 External Code Integration

end
end
end

Write a function adder_main that calls the external library function adder.

function y = adder_main(x1, x2)


%#codegen
y = AdderAPI.adder(x1, x2);
end

Generate a MEX function for adder_main. The MEX Function exercises the
coder.ExternalDependency methods.

codegen('adder_main', '-args', {7,9}, '-report')

Copy the library to the current folder using the file extension for your platform.

For Windows, use:


copyfile(fullfile(pwd, 'codegen', 'dll', 'adder', 'adder.dll'));

For Linux, use:


copyfile(fullfile(pwd, 'codegen', 'dll', 'adder', 'adder.so'));

Run the MEX function and verify the result.


adder_main_mex(2,3)

See Also
coder.BuildConfig | coder.ExternalDependency | error

More About
• “Encapsulating the Interface to External Code” on page 28-3
• “Build Information Object” on page 21-139
• “Build Information Methods” on page 21-139

28-8
Update Build Information from MATLAB code

Update Build Information from MATLAB code


You can choose to control aspects of the build process that occur after code generation but
before compilation. For example, you can specify compiler or linker options.

To customize the build from your MATLAB code:

1 In your MATLAB code, call coder.updateBuildInfo to update the build


information object. You specify a build information object method and the input
arguments for the method.
2 Generate code from your MATLAB code.

See Also
coder.updateBuildInfo

28-9
28 External Code Integration

Call External Functions Encapsulated by coder.ExternalDependency


When a method of a class derived from coder.ExternalDependency defines the
interface to an external function, you call the external function by calling the method.

Suppose you define the following method for a class named AdderAPI:

function c = adder(a, b)
coder.cinclude('adder.h');
c = 0;
c = coder.ceval('adder', a, b);
end
This method defines the interface to a function adder which has two inputs, a and b. In
your MATLAB code, call adder this way:

y = AdderAPI.adder(x1, x2);

See Also
coder.ExternalDependency

Related Examples
• “Encapsulate Interface to an External C Library” on page 28-6

More About
• “Encapsulating the Interface to External Code” on page 28-3

28-10
29

Generate Efficient and Reusable Code

• “Optimization Strategies” on page 29-3


• “Modularize MATLAB Code” on page 29-6
• “Eliminate Redundant Copies of Function Inputs” on page 29-7
• “Inline Code” on page 29-10
• “Control Inlining” on page 29-12
• “Fold Function Calls into Constants” on page 29-15
• “Control Stack Space Usage” on page 29-17
• “Stack Allocation and Performance” on page 29-18
• “Dynamic Memory Allocation and Performance” on page 29-19
• “Minimize Dynamic Memory Allocation” on page 29-20
• “Provide Maximum Size for Variable-Size Arrays” on page 29-21
• “Disable Dynamic Memory Allocation During Code Generation” on page 29-27
• “Set Dynamic Memory Allocation Threshold” on page 29-28
• “Excluding Unused Paths from Generated Code” on page 29-30
• “Prevent Code Generation for Unused Execution Paths” on page 29-31
• “Generate Code with Parallel for-Loops (parfor)” on page 29-33
• “Minimize Redundant Operations in Loops” on page 29-35
• “Unroll for-Loops” on page 29-37
• “Support for Integer Overflow and Non-Finites” on page 29-40
• “Integrate External/Custom Code” on page 29-42
• “MATLAB Coder Optimizations in Generated Code” on page 29-48
• “memcpy Optimization” on page 29-52
• “memset Optimization” on page 29-54
• “Generate Reusable Code” on page 29-56
• “Reuse Large Arrays and Structures” on page 29-57
29 Generate Efficient and Reusable Code

• “Variable Reuse in Generated Code” on page 29-58


• “LAPACK Calls in Generated Code” on page 29-59
• “Speed Up Linear Algebra in Generated Standalone Code by Using LAPACK Calls” on
page 29-60

29-2
Optimization Strategies

Optimization Strategies
MATLAB Coder introduces certain optimizations when generating C/C++ code or
MEX functions from your MATLAB code. For more information, see “MATLAB Coder
Optimizations in Generated Code” on page 29-48.

To optimize your generated code further, you can:

• Adapt your MATLAB code.


• Control code generation using the configuration object from the command-line or the
project settings dialog box.

To optimize the execution speed of generated code, for these conditions, perform the
following actions as necessary:

Condition Action
You have for-loops whose iterations are “Generate Code with Parallel for-Loops (parfor)”
independent of each other. on page 29-33
You have variable-size arrays in your MATLAB “Minimize Dynamic Memory Allocation” on page
code. 29-20
You have multiple variable-size arrays in your “Set Dynamic Memory Allocation Threshold” on
MATLAB code. You want dynamic memory page 29-28
allocation for larger arrays and static allocation
for smaller ones.
You want your generated function to be called by “Eliminate Redundant Copies of Function
reference. Inputs” on page 29-7
You are calling small functions in your MATLAB “Inline Code” on page 29-10
code.
You have limited target memory for your “Control Inlining” on page 29-12
generated code. You want to inline small
functions and generate separate code for larger
ones.
You do not want to generate code for expressions “Fold Function Calls into Constants” on page
that contain constants only. 29-15
You have loop operations in your MATLAB code “Minimize Redundant Operations in Loops” on
that do not depend on the loop index. page 29-35

29-3
29 Generate Efficient and Reusable Code

Condition Action
You have integer operations in your MATLAB “Disable Support for Integer Overflow” on page
code. You know beforehand that integer 29-40
overflow does not occur during execution of your
generated code.
You know beforehand that Infs and NaNs do not “Disable Support for Non-Finite Numbers” on
occur during execution of your generated code. page 29-41
You have for-loops with few iterations. “Unroll for-Loops” on page 29-37
You already have legacy C/C++ code optimized “Integrate External/Custom Code” on page
for your target environment. 29-42
You want to speed up the code generated for “Speed Up Linear Algebra in Generated
linear algebra functions. Standalone Code by Using LAPACK Calls” on
page 29-60

To optimize the memory usage of generated code, for these conditions, perform the
following actions as necessary:

Condition Action
You have if/else/elseif statements “Prevent Code Generation for Unused
or switch/case/otherwise statements Execution Paths” on page 29-31
in your MATLAB code. You do not require
some branches of the statements in your
generated code.
You want your generated function to be “Eliminate Redundant Copies of Function
called by reference. Inputs” on page 29-7
You have limited stack space for your “Control Stack Space Usage” on page
generated code. 29-17
You are calling small functions in your “Inline Code” on page 29-10
MATLAB code.
You have limited target memory for your “Control Inlining” on page 29-12
generated code. You want to inline small
functions and generate separate code for
larger ones.
You do not want to generate code for “Fold Function Calls into Constants” on
expressions that contain constants only. page 29-15

29-4
Optimization Strategies

Condition Action
You have loop operations in your MATLAB “Minimize Redundant Operations in Loops”
code that do not depend on the loop index. on page 29-35
You have integer operations in your “Disable Support for Integer Overflow” on
MATLAB code. You know beforehand that page 29-40
integer overflow does not occur during
execution of your generated code.
You know beforehand that Inf-s and NaN- “Disable Support for Non-Finite Numbers”
s does not occur during execution of your on page 29-41
generated code.
Your MATLAB code has variables that are “Reuse Large Arrays and Structures” on
large arrays or structures. The variable page 29-57
reuse optimization preserves your variable
names. You want to see if the extra
memory required to preserve the variable
names of the large arrays or structures
affects performance.

29-5
29 Generate Efficient and Reusable Code

Modularize MATLAB Code


For large MATLAB code, streamline code generation by modularizing the code:

1 Break up your MATLAB code into smaller, self-contained sections.


2 Save each section in a MATLAB function.
3 Generate C/C++ code for each function.
4 Call the generated C/C++ functions in sequence from a wrapper MATLAB function
using coder.ceval.
5 Generate C/C++ code for the wrapper function.

Besides streamlining code generation for the original MATLAB code, this approach also
supplies you with C/C++ code for the individual sections. You can reuse the code for the
individual sections later by integrating them with other generated C/C++ code using
coder.ceval.

29-6
Eliminate Redundant Copies of Function Inputs

Eliminate Redundant Copies of Function Inputs


You can reduce the number of copies in your generated code by writing functions that use
the same variable as both an input and an output. For example:

function A = foo( A, B ) %#codegen


A = A * B;
end

This coding practice uses a reference parameter optimization. When a variable acts
as both input and output, the generated code passes the variable by reference instead
of redundantly copying the input to a temporary variable. In the preceding example,
input A is passed by reference in the generated code because it also acts as an output for
function foo:

...
/* Function Definitions */
void foo(double *A, double B)
{
*A *= B;
}
...

The reference parameter optimization reduces memory usage and execution time,
especially when the variable passed by reference is a large data structure. To achieve
these benefits at the call site, call the function with the same variable as both input and
output.

By contrast, suppose that you rewrite function foo without the optimization:

function y = foo2( A, B ) %#codegen


y = A * B;
end

The generated code passes the inputs by value and returns the value of the output:

...
/* Function Definitions */
double foo2(double A, double B)
{
return A * B;
}
...

29-7
29 Generate Efficient and Reusable Code

In some cases, the output of the function cannot be a modified version of its inputs. If
you do not use the inputs later in the function, you can modify your code to operate on
the inputs instead of on a copy of the inputs. One method is to create additional return
values for the function. For example, consider the code:
function y1=foo(u1) %#codegen
x1=u1+1;
y1=bar(x1);
end

function y2=bar(u2)
% Since foo does not use x1 later in the function,
% it would be optimal to do this operation in place
x2=u2.*2;
% The change in dimensions in the following code
% means that it cannot be done in place
y2=[x2,x2];
end

You can modify this code to eliminate redundant copies.


function y1=foo(u1) %#codegen
u1=u1+1;
[y1, u1]=bar(u1);
end

function [y2, u2]=bar(u2)


u2=u2.*2;
% The change in dimensions in the following code
% still means that it cannot be done in place
y2=[u2,u2];
end

The reference parameter optimization does not apply to constant inputs. If the same
variable is an input and an output, and the input is constant, the code generation
software treats the output as a separate variable. For example, consider the function
foo:
function A = foo( A, B ) %#codegen
A = A * B;
end

Generate code in which A has a constant value 2.


codegen -config:lib foo -args {coder.Constant(2) 3} -report

29-8
Eliminate Redundant Copies of Function Inputs

The generated code defines the constant A and returns the value of the output.

...
#define A (2.0)
...
double foo(double B)
{
return A * B;
}
...

Related Examples
• “Pass Structure Arguments by Reference or by Value” on page 8-13

29-9
29 Generate Efficient and Reusable Code

Inline Code
Inlining is a technique that replaces a function call with the contents (body) of that
function. Inlining eliminates the overhead of a function call, but can produce larger C/C
++ code. Inlining can create opportunities for further optimization of the generated C/C
++ code. The code generation software uses internal heuristics to determine whether to
inline functions in the generated code. You can use the coder.inline directive to fine-
tune these heuristics for individual functions. For more information, see coder.inline.

In this section...
“Prevent Function Inlining” on page 29-10
“Use Inlining in Control Flow Statements” on page 29-10

Prevent Function Inlining


In this example, function foo is not inlined in the generated code:
function y = foo(x)
coder.inline('never');
y = x;
end

Use Inlining in Control Flow Statements


You can use coder.inline in control flow code. If the software detects contradictory
coder.inline directives, the generated code uses the default inlining heuristic and
issues a warning.

Suppose you want to generate code for a division function that will be embedded in
a system with limited memory. To optimize memory use in the generated code, the
following function, inline_division, manually controls inlining based on whether it
performs scalar division or vector division:
function y = inline_division(dividend, divisor)

% For scalar division, inlining produces smaller code


% than the function call itself.
if isscalar(dividend) && isscalar(divisor)
coder.inline('always');
else

29-10
Inline Code

% Vector division produces a for-loop.


% Prohibit inlining to reduce code size.
coder.inline('never');
end

if any(divisor == 0)
error('Can not divide by 0');
end

y = dividend / divisor;

Related Examples
• “Control Inlining” on page 29-12

29-11
29 Generate Efficient and Reusable Code

Control Inlining
Restrict inlining when:

• The size of generated code exceeds desired limits due to excessive inlining of
functions. Suppose that you include the statement, coder.inline('always'),
inside a certain function. You then call that function at many different sites in your
code. The generated code can be large due to the function being inlined every time it is
called.

The call sites must be different. For instance, inlining does not lead to large code if
the function to be inlined is called several times inside a loop.
• You have limited RAM or stack space.

In this section...
“Control Size of Functions Inlined” on page 29-12
“Control Size of Functions After Inlining” on page 29-13
“Control Stack Size Limit on Inlined Functions” on page 29-13

Control Size of Functions Inlined


You can use the MATLAB Coder app or the command-line interface to control the
maximum size of functions that can be inlined. The function size is measured in terms of
an abstract number of instructions, not actual MATLAB instructions or instructions in
the target processor. Experiment with this parameter to obtain the inlining behavior that
you want.

• Using the app, in the project settings dialog box, on the All Settings tab, set the
value of the field, Inline threshold, to the maximum size that you want.
• At the command line, create a codegen configuration object. Set the value of the
property, InlineThreshold, to the maximum size that you want.

cfg = coder.config('lib');
cfg.InlineThreshold = 100;

Generate code using this configuration object.

29-12
Control Inlining

Control Size of Functions After Inlining


You can use the MATLAB Coder app or the command-line interface to control the
maximum size of functions after inlining. The function size is measured in terms of an
abstract number of instructions, not actual MATLAB instructions or instructions in the
target processor. Experiment with this parameter to obtain the inlining behavior that
you want.

• Using the app, in the project settings dialog box, on the All Settings tab, set the
value of the field, Inline threshold max, to the maximum size that you want.
• At the command line, create a codegen configuration object. Set the value of the
property, InlineThresholdMax, to the maximum size that you want.
cfg = coder.config('lib');
cfg.InlineThresholdMax = 100;

Generate code using this configuration object.

Control Stack Size Limit on Inlined Functions


Specifying a limit on the stack space constrains the amount of inlining allowed. For
out-of-line functions, stack space for variables local to the function is released when
the function returns. However, for inlined functions, stack space remains occupied
by the local variables even after the function is executed. The value of the property,
InlineStackLimit, is measured in bytes. Based on information from the target
hardware settings, the software estimates the number of stack variables that a certain
value of InlineStackLimit can accomodate. This estimate excludes possible C compiler
optimizations such as putting variables in registers.

You can use the MATLAB Coder app or the command-line interface to control the stack
size limit on inlined functions.

• Using the app, in the project settings dialog box, on the All Settings tab, set the
value of the field, Inline stack limit, to the maximum size that you want.
• At the command line, create a codegen configuration object. Set the value of the
property, InlineThresholdMax, to the maximum size that you want.
cfg = coder.config('lib');
cfg.InlineStackLimit = 2000;

Generate code using this configuration object.

29-13
29 Generate Efficient and Reusable Code

Related Examples
• “Inline Code” on page 29-10

29-14
Fold Function Calls into Constants

Fold Function Calls into Constants


This example shows how to specify constants in generated code using coder.const.
The code generation software folds an expression or a function call in a coder.const
statement into a constant in generated code. Because the generated code does not have
to evaluate the expression or call the function every time, this optimization reduces the
execution time of the generated code.

Write a function AddShift that takes an input Shift and adds it to the elements of
a vector. The vector consists of the square of the first 10 natural numbers. AddShift
generates this vector.

function y = AddShift(Shift) %#codegen


y = (1:10).^2+Shift;

Generate code for AddShift using the codegen command. Open the Code Generation
Report.

codegen -config:lib -launchreport AddShift -args 0

The code generation software generates code for creating the vector. It adds Shift
to each element of the vector during vector creation. The definition of AddShift in
generated code looks as follows:

void AddShift(double Shift, double y[10])


{
int k;
for (k = 0; k < 10; k++) {
y[k] = (double)((1 + k) * (1 + k)) + Shift;
}
}

Replace the statement

y = (1:10).^2+Shift;

with

y = coder.const((1:10).^2)+Shift;

Generate code for AddShift using the codegen command. Open the Code Generation
Report.

29-15
29 Generate Efficient and Reusable Code

codegen -config:lib -launchreport AddShift -args 0

The code generation software creates the vector containing the squares of the first 10
natural numbers. In the generated code, it adds Shift to each element of this vector.
The definition of AddShift in generated code looks as follows:

void AddShift(double Shift, double y[10])


{
int i0;
static const signed char iv0[10] = { 1, 4, 9, 16, 25, 36,
49, 64, 81, 100 };

for (i0 = 0; i0 < 10; i0++) {


y[i0] = (double)iv0[i0] + Shift;
}
}

See Also
coder.const

29-16
Control Stack Space Usage

Control Stack Space Usage


This example shows how to set the maximum stack space that the generated code uses.
Set the maximum stack usage when:

• You have limited stack space, for instance, in embedded targets.


• Your C compiler reports a run-time stack overflow.

The value of the property, StackUsageMax, is measured in bytes. Based on information


from the target hardware settings, the software estimates the number of stack variables
that a certain value of StackUsageMax can accomodate. This estimate excludes possible
C compiler optimizations such as putting variables in registers.

Control Stack Space Usage Using the MATLAB Coder App

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Set Build type to Source Code, Static Library, Dynamic Library, or
Executable (depending on your requirements).
3 Click More Settings.
4 On the Memory tab, set Stack usage max to the value that you want.

Control Stack Space Usage at the Command Line

1 Create a configuration object for code generation.

Use coder.config with arguments 'lib','dll', or 'exe' (depending on your


requirements). For example:
cfg = coder.config('lib');
2 Set the property, StackUsageMax, to the value that you want.

cfg.StackUsageMax=400000;

More About
• “Stack Allocation and Performance” on page 29-18

29-17
29 Generate Efficient and Reusable Code

Stack Allocation and Performance


By default, local variables are allocated on the stack. Large variables that do not fit on
the stack are statically allocated in memory.

Stack allocation typically uses memory more efficiently than static allocation. However,
stack space is sometimes limited, typically in embedded processors. MATLAB Coder
allows you to manually set a limit on the stack space usage to make your generated
code suitable for your target hardware. You can choose this limit based on the target
hardware configurations. For more information, see “Control Stack Space Usage” on page
29-17.

29-18
Dynamic Memory Allocation and Performance

Dynamic Memory Allocation and Performance


To achieve faster execution of generated code, minimize dynamic (or run-time) memory
allocation of arrays.

MATLAB Coder does not provide a size for unbounded arrays in generated code. Instead,
such arrays are referenced indirectly through pointers. For such arrays, memory cannot
be allocated during compilation of generated code. Based on storage requirements
for the arrays, memory is allocated and freed at run time as required. This run-time
allocation and freeing of memory leads to slower execution of the generated code. For
more information on dynamic memory allocation, see “Bounded Versus Unbounded
Variable-Size Data” on page 7-4.

When Dynamic Memory Allocation Occurs


Dynamic memory allocation occurs when the code generation software cannot find upper
bounds for variable-size arrays. The software cannot find upper bounds when you specify
the size of an array using a variable that is not a compile-time constant. An example of
such a variable is an input variable (or a variable computed from an input variable).

Instances in the MATLAB code that can lead to dynamic memory allocation are:

• Array initialization: You specify array size using a variable whose value is known only
at run time.
• After initialization of an array:

• You declare the array as variable-size using coder.varsize without explicit


upper bounds. After this declaration, you expand the array by concatenation inside
a loop. The number of loop runs is known only at run time.
• You use a reshape function on the array. At least one of the size arguments to the
reshape function is known only at run time.

If you know the maximum size of the array, you can avoid dynamic memory allocation.
You can then provide an upper bound for the array and prevent dynamic memory
allocation in generated code. For more information, see “Minimize Dynamic Memory
Allocation” on page 29-20.

29-19
29 Generate Efficient and Reusable Code

Minimize Dynamic Memory Allocation


When possible, minimize dynamic memory allocation because it leads to slower execution
of generated code. Dynamic memory allocation occurs when the code generation software
cannot find upper bounds for variable-size arrays.

If you know the maximum size of a variable-size array, you can avoid dynamic memory
allocation. Follow these steps:

1 “Provide Maximum Size for Variable-Size Arrays” on page 29-21.


2 Depending on your requirements, do one of the following:

• “Disable Dynamic Memory Allocation During Code Generation” on page


29-27.
• “Set Dynamic Memory Allocation Threshold” on page 29-28

Caution If a variable-size array in the MATLAB code does not have a maximum size,
disabling dynamic memory allocation leads to a code generation error. Before disabling
dynamic memory allocation, you must provide a maximum size for variable-size arrays in
your MATLAB code.

More About
• “Dynamic Memory Allocation and Performance” on page 29-19

29-20
Provide Maximum Size for Variable-Size Arrays

Provide Maximum Size for Variable-Size Arrays


To constrain array size for variable-size arrays, do one of the following:

• Constrain Array Size Using assert Statements

If the variable specifying array size is not a compile-time constant, use an assert
statement with relational operators to constrain the variable. Doing so helps the code
generation software to determine a maximum size for the array.

The following examples constrain array size using assert statements:

• When Array Size Is Specified by Input Variables

Define a function array_init which initializes an array y with input variable N:


function y = array_init (N)
assert(N <= 25); % Generates exception if N > 25
y = zeros(1,N);

The assert statement constrains input N to a maximum size of 25. In the absence
of the assert statement, y is assigned a pointer to an array in the generated code,
thus allowing dynamic memory allocation.
• When Array Size Is Obtained from Computation Using Input Variables

Define a function, array_init_from_prod, which takes two input variables, M


and N, and uses their product to specify the maximum size of an array, y.
function y = array_init_from_prod (M,N)
size=M*N;
assert(size <= 25); % Generates exception if size > 25
y=zeros(1,size);

The assert statement constrains the product of M and N to a maximum of 25.

Alternatively, if you restrict M and N individually, it leads to dynamic memory


allocation:
function y = array_init_from_prod (M,N)
assert(M <= 5);
assert(N <= 5);
size=M*N;
y=zeros(1,size);

29-21
29 Generate Efficient and Reusable Code

This code causes dynamic memory allocation because M and N can both have
unbounded negative values. Therefore, their product can be unbounded and
positive even though, individually, their positive values are bounded.

Tip Place the assert statement on a variable immediately before it is used to


specify array size.

Tip You can use assert statements to restrict array sizes in most cases. When
expanding an array inside a loop, this strategy does not work if the number of loop
runs is known only at run time.
• Restrict Concatenations in a Loop Using coder.varsize with Upper Bounds

You can expand arrays beyond their initial size by concatenation. When you
concatenate additional elements inside a loop, there are two syntax rules for
expanding arrays.

1 Array size during initialization is not a compile-time constant

If the size of an array during initialization is not a compile-time constant, you can
expand it by concatenating additional elements:

function out=ExpandArray(in) % Expand an array by five elements


out = zeros(1,in);
for i=1:5
out = [out 0];
end
2 Array size during initialization is a compile-time constant

Before concatenating elements, you have to declare the array as variable-size


using coder.varsize:

function out=ExpandArray() % Expand an array by five elements


out = zeros(1,5);
coder.varsize('out');
for i=1:5
out = [out 0];
end

29-22
Provide Maximum Size for Variable-Size Arrays

Either case leads to dynamic memory allocation. To prevent dynamic memory


allocation in such cases, use coder.varsize with explicit upper bounds. This
example shows how to use coder.varsize with explicit upper bounds:

Restrict Concatenations Using coder.varsize with Upper Bounds

1 Define a function, RunningAverage, that calculates the running average of an N-


element subset of an array:

function avg=RunningAverage(N)

% Array whose elements are to be averaged


NumArray=[1 6 8 2 5 3];

% Initialize average:
% These will also be the first two elements of the function output
avg=[0 0];

% Place a bound on the argument


coder.varsize('avg',[1 8]);

% Loop to calculate running average


for i=1:N
s=0;
s=s+sum(NumArray(1:i));
avg=[avg s/i];
% Increase the size of avg as required by concatenation
end

The output, avg, is an array that you can expand as required to accommodate
the running averages. As a new running average is calculated, it is added to the
array avg through concatenation, thereby expanding the array.

Because the maximum number of running averages is equal to the number of


elements in NumArray, you can supply an explicit upper bound for avg in the
coder.varsize statement. In this example, the upper bound is 8 (the two initial
elements plus the six elements of NumArray).
2 Generate code for RunningAverage with input argument of type double:

codegen -config:lib -report RunningAverage -args 2

29-23
29 Generate Efficient and Reusable Code

In the generated code, avg is assigned an array of size 8 (static memory


allocation). The function definition for RunningAverage appears as follows
(using built-in C types):

void RunningAverage (double N, double avg_data[8], int avg_size[2])


3 By contrast, if you remove the explicit upper bound, the generated code
dynamically allocates avg.

Replace the statement

coder.varsize('avg',[1 8]);

with:

coder.varsize('avg');
4 Generate code for RunningAverage with input argument of type double:

codegen -config:lib -report RunningAverage -args 2

In the generated code, avg is assigned a pointer to an array, thereby allowing


dynamic memory allocation. The function definition for RunningAverage
appears as follows (using built-in C types):

void Test(double N, emxArray_real_T *avg)

Note: Dynamic memory allocation also occurs if you precede


coder.varsize('avg') with the following assert statement:

assert(N < 6);


The assert statement does not restrict the number of concatenations within the
loop.
• Constrain Array Size When Rearranging a Matrix

The statement out = reshape(in,m,n,...) takes an array, in, as an argument


and returns array, out, having the same elements as in, but reshaped as an m-by-n-
by-... matrix. If one of the size variables m,n,.... is not a compile-time constant,
then dynamic memory allocation of out takes place.

29-24
Provide Maximum Size for Variable-Size Arrays

To avoid dynamic memory allocation, use an assert statement before the reshape
statement to restrict the size variables m,n,... to numel(in). This example shows
how to use an assert statement before a reshape statement:

Rearrange a Matrix into Given Number of Rows

1 Define a function, ReshapeMatrix, which takes an input variable, N, and


reshapes a matrix, mat, to have N rows:

function [out1,out2] = ReshapeMatrix(N)

mat = [1 2 3 4 5; 4 5 6 7 8]
% Since mat has 10 elements, N must be a factor of 10
% to pass as argument to reshape

out1 = reshape(mat,N,[]);
% N is not restricted

assert(N < numel(mat));


% N is restricted to number of elements in mat
out2 = reshape(mat,N,[]);
2 Generate code for ReshapeArray using the codegen command (the input
argument does not have to be a factor of 10):

codegen -config:lib -report ReshapeArray -args 3

While out1 is dynamically allocated, out2 is assigned an array with size 100
(=10 X 10) in the generated code.

Tip If your system has limited memory, do not use the assert statement in this
way. For an n-element matrix, the assert statement creates an n-by-n matrix,
which might be large.

Related Examples
• “Minimize Dynamic Memory Allocation” on page 29-20
• “Disable Dynamic Memory Allocation During Code Generation” on page 29-27
• “Set Dynamic Memory Allocation Threshold” on page 29-28

29-25
29 Generate Efficient and Reusable Code

More About
• “Dynamic Memory Allocation and Performance” on page 29-19

29-26
Disable Dynamic Memory Allocation During Code Generation

Disable Dynamic Memory Allocation During Code Generation


To disable dynamic memory allocation using the MATLAB Coder app:

1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Click More Settings.
3 On the Memory tab, under Variable Sizing Support, set Dynamic memory
allocation to Never.

To disable dynamic memory allocation at the command line:

1 In the MATLAB workspace, define the configuration object:


cfg=coder.config('lib');
2 Set the DynamicMemoryAllocation property of the configuration object to Off:

cfg.DynamicMemoryAllocation = 'Off';

If a variable-size array in the MATLAB code does not have a maximum upper bound,
disabling dynamic memory allocation leads to a code generation error. Therefore, you can
identify variable-size arrays in your MATLAB code that do not have a maximum upper
bound. These arrays are the arrays that are dynamically allocated in the generated code.

Related Examples
• “Minimize Dynamic Memory Allocation” on page 29-20
• “Provide Maximum Size for Variable-Size Arrays” on page 29-21
• “Set Dynamic Memory Allocation Threshold” on page 29-28

More About
• “Dynamic Memory Allocation and Performance” on page 29-19

29-27
29 Generate Efficient and Reusable Code

Set Dynamic Memory Allocation Threshold


This example shows how to specify a dynamic memory allocation threshold for variable-
size arrays. Dynamic memory allocation optimizes storage requirements for variable-
size arrays, but causes slower execution of generated code. Instead of disabling dynamic
memory allocation for all variable-size arrays, you can disable dynamic memory
allocation for arrays less than a certain size.

Specify this threshold when you want to:

• Disable dynamic memory allocation for smaller arrays. For smaller arrays, static
memory allocation can speed up generated code. Static memory allocation can lead to
unused storage space. However, you can decide that the unused storage space is not a
significant consideration for smaller arrays.
• Enable dynamic memory allocation for larger arrays. For larger arrays, when you use
dynamic memory allocation, you can significantly reduce storage requirements.

Set Dynamic Memory Allocation Threshold Using the MATLAB Coder App
1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
2 Click More Settings.
3 On the Memory tab, select the Enable variable-sizing check box.
4 Set Dynamic memory allocation to For arrays with max size at or
above threshold.
5 Set Dynamic memory allocation threshold to the value that you want.

29-28
Set Dynamic Memory Allocation Threshold

The Dynamic memory allocation threshold value is measured in bytes. Based


on information from the target hardware settings, the software estimates the size
of the array that a certain value of DynamicMemoryAllocationThreshold can
accomodate. This estimate excludes possible C compiler optimizations such as
putting variables in registers.

Set Dynamic Memory Allocation Threshold at the Command Line


1 Create a configuration object for code generation. Use coder.config with
arguments 'lib','dll', or 'exe' (depending on your requirements). For example:

cfg = coder.config('lib');
2 Set DynamicMemoryAllocation to 'Threshold'.

cfg.DynamicMemoryAllocation='Threshold';
3 Set the property, DynamicMemoryAllocationThreshold, to the value that you
want.
cfg.DynamicMemoryAllocationThreshold = 40000;

The value stored in DynamicMemoryAllocationThreshold is measured in bytes.


Based on information from the target hardware settings, the software estimates the
size of the array that a certain value of DynamicMemoryAllocationThreshold
can accomodate. This estimate excludes possible C compiler optimizations such as
putting variables in registers.

Related Examples
• “Minimize Dynamic Memory Allocation” on page 29-20
• “Provide Maximum Size for Variable-Size Arrays” on page 29-21
• “Disable Dynamic Memory Allocation During Code Generation” on page 29-27

More About
• “Dynamic Memory Allocation and Performance” on page 29-19

29-29
29 Generate Efficient and Reusable Code

Excluding Unused Paths from Generated Code


In certain situations, you do not need some branches of an: if, elseif, else
statement, or a switch, case, otherwise statement in your generated code. For
instance:

• You have a MATLAB function that performs multiple tasks determined by a control-
flow variable. You might not need some of the tasks in the code generated from this
function.
• You have an if/elseif/if statement in a MATLAB function performing different
tasks based on the nature (type/value) of the input. In some cases, you know the
nature of the input beforehand. If so, you do not need some branches of the if
statement.

You can prevent code generation for the unused branches of an if/elseif/else
statement or a switch/case/otherwise statement. Declare the control-flow variable
as a constant. The code generation software generates code only for the branch that the
control-flow variable chooses.

Related Examples
• “Prevent Code Generation for Unused Execution Paths” on page 29-31

29-30
Prevent Code Generation for Unused Execution Paths

Prevent Code Generation for Unused Execution Paths


In this section...
“Prevent Code Generation When Local Variable Controls Flow” on page 29-31
“Prevent Code Generation When Input Variable Controls Flow” on page 29-32

If a variable controls the flow of an: if, elseif, else statement, or a switch,
case, otherwise statement, declare it as constant so that code generation takes place
for one branch of the statement only.

Depending on the nature of the control-flow variable, you can declare it as constant in
two ways:

• If the variable is local to the MATLAB function, assign it to a constant value in the
MATLAB code. For an example, see “Prevent Code Generation When Local Variable
Controls Flow” on page 29-31.
• If the variable is an input to the MATLAB function, you can declare it as constant
using coder.Constant. For an example, see “Prevent Code Generation When Input
Variable Controls Flow” on page 29-32.

Prevent Code Generation When Local Variable Controls Flow


1 Define a function SquareOrCube which takes an input variable, in, and squares or
cubes its elements based on whether the choice variable, ch, is set to s or c:

function out = SquareOrCube(ch,in) %#codegen


if ch=='s'
out = in.^2;
elseif ch=='c'
out = in.^3;
else
out = 0;
end
2 Generate code for SquareOrCube using the codegen command:

codegen -config:lib SquareOrCube -args {'s',zeros(2,2)}

The generated C code squares or cubes the elements of a 2-by-2 matrix based on the
input for ch.

29-31
29 Generate Efficient and Reusable Code

3 Add the following line to the definition of SquareOrCube:

ch = 's';

The generated C code squares the elements of a 2-by-2 matrix. The choice variable,
ch, and the other branches of the if/elseif/if statement do not appear in the
generated code.

Prevent Code Generation When Input Variable Controls Flow


1 Define a function MathFunc, which performs different mathematical operations on
an input, in, depending on the value of the input, flag:

function out = MathFunc(flag,in) %#codegen


%# codegen
switch flag
case 1
out=sin(in);
case 2
out=cos(in);
otherwise
out=sqrt(in);
end
2 Generate code for MathFunc using the codegen command:

codegen -config:lib MathFunc -args {1,zeros(2,2)}

The generated C code performs different math operations on the elements of a 2-by-2
matrix based on the input for flag.
3 Generate code for MathFunc, declaring the argument, flag, as a constant using
coder.Constant:
codegen -config:lib MathFunc -args {coder.Constant(1),zeros(2,2)}

The generated C code finds the sine of the elements of a 2-by-2 matrix. The variable,
flag, and the switch/case/otherwise statement do not appear in the generated
code.

More About
• “Excluding Unused Paths from Generated Code” on page 29-30

29-32
Generate Code with Parallel for-Loops (parfor)

Generate Code with Parallel for-Loops (parfor)


This example shows how to generate C code for a MATLAB algorithm that contains a
parfor-loop.

1 Write a MATLAB function that contains a parfor-loop. For example:

function a = test_parfor %#codegen


a=ones(10,256);
r=rand(10,256);
parfor i=1:10
a(i,:)=real(fft(r(i,:)));
end
2 Generate C code for test_parfor. At the MATLAB command line, enter:

codegen -config:lib test_parfor

Because you did not specify the maximum number of threads to use, the generated C
code executes the loop iterations in parallel on the available number of cores.
3 To specify a maximum number of threads, rewrite the function test_parfor as
follows:

function a = test_parfor(u) %#codegen


a=ones(10,256);
r=rand(10,256);
parfor (i=1:10,u)
a(i,:)=real(fft(r(i,:)));
end
4 Generate C code for test_parfor. Use -args 0 to specify that the input, u, is a
scalar double. At the MATLAB command line, enter:

codegen -config:lib test_parfor -args 0

In the generated code, the iterations of the parfor-loop run on at most the number
of cores specified by the input, u. If less than u cores are available, the iterations run
on the cores available at the time of the call.

More About
• “Algorithm Acceleration Using Parallel for-Loops (parfor)” on page 26-19
• “Classification of Variables in parfor-Loops” on page 26-27

29-33
29 Generate Efficient and Reusable Code

• “Reduction Assignments in parfor-Loops” on page 26-26

29-34
Minimize Redundant Operations in Loops

Minimize Redundant Operations in Loops


This example shows how to minimize redundant operations in loops. When a loop
operation does not depend on the loop index, performing it inside a loop is redundant.
This redundancy often goes unnoticed when you are performing multiple operations in a
single MATLAB statement inside a loop. For example, in the following code, the inverse
of the matrix B is being calculated 100 times inside the loop although it does not depend
on the loop index:

for i=1:100
C=C + inv(B)*A^i*B;
end

Performing such redundant loop operations can lead to unnecessary processing. To avoid
unnecessary processing, move operations outside loops as long as they do not depend on
the loop index.

1 Define a function, SeriesFunc(A,B,n), that calculates the sum of n terms in the


following power series expansion:

C = 1 + B-1 AB + B-1 A 2 B + ...

function C=SeriesFunc(A,B,n)

% Initialize C with a matrix having same dimensions as A


C=zeros(size(A));

% Perform the series sum


for i=1:n
C=C+inv(B)*A^i*B;
end
2 Generate code for SeriesFunc with 4-by-4 matrices passed as input arguments for A
and B:

X = coder.typeof(zeros(4));
codegen -config:lib -launchreport SeriesFunc -args {X,X,10}

In the generated code, the inversion of B is performed n times inside the loop. It is
more economical to perform the inversion operation once outside the loop because it
does not depend on the loop index.
3 Modify SeriesFunc as follows:

29-35
29 Generate Efficient and Reusable Code

function C=SeriesFunc(A,B,n)

% Initialize C with a matrix having same dimensions as A


C=zeros(size(A));

% Perform the inversion outside the loop


inv_B=inv(B);

% Perform the series sum


for i=1:n
C=C+inv_B*A^i*B;
end

This procedure performs the inversion of B only once, leading to faster execution of
the generated code.

29-36
Unroll for-Loops

Unroll for-Loops
Unrolling for-loops eliminates the loop logic by creating a separate copy of the loop body
in the generated code for each iteration. Within each iteration, the loop index variable
becomes a constant.

You can also force loop unrolling for individual functions by wrapping the loop header in
a coder.unroll function. For more information, see coder.unroll.

Limit Copying the for-loop Body in Generated Code


To limit the number of times that you copy the body of a for-loop in generated code:

1 Write a MATLAB function getrand(n) that uses a for-loop to generate a vector


of length n and assign random numbers to specific elements. Add a test function
test_unroll. This function calls getrand(n) with n equal to values both less than
and greater than the threshold for copying the for-loop in generated code.

function [y1, y2] = test_unroll() %#codegen


% The directive %#codegen indicates that the function
% is intended for code generation
% Calling getrand 8 times triggers unroll
y1 = getrand(8);
% Calling getrand 50 times does not trigger unroll
y2 = getrand(50);

function y = getrand(n)
% Turn off inlining to make
% generated code easier to read
coder.inline('never');

% Set flag variable dounroll to repeat loop body


% only for fewer than 10 iterations
dounroll = n < 10;
% Declare size, class, and complexity
% of variable y by assignment
y = zeros(n, 1);
% Loop body begins
for i = coder.unroll(1:2:n, dounroll)
if (i > 2) && (i < n-2)
y(i) = rand();
end;

29-37
29 Generate Efficient and Reusable Code

end;
% Loop body ends
2 In the default output folder, codegen/lib/test_unroll, generate C static library
code for test_unroll:

codegen -config:lib test_unroll

In test_unroll.c, the generated C code for getrand(8) repeats the body of the
for-loop (unrolls the loop) because the number of iterations is less than 10:

static void getrand(double y[8])


{
/* Turn off inlining to make */
/* generated code easier to read */
/* Set flag variable dounroll to repeat loop body */
/* only for fewer than 10 iterations */
/* Declare size, class, and complexity */
/* of variable y by assignment */
memset(&y[0], 0, sizeof(double) << 3);

/* Loop body begins */


y[2] = b_rand();
y[4] = b_rand();

/* Loop body ends */


}

The generated C code for getrand(50) does not unroll the for-loop because the
number of iterations is greater than 10:

static void b_getrand(double y[50])


{
int i;
int b_i;

/* Turn off inlining to make */


/* generated code easier to read */
/* Set flag variable dounroll to repeat loop body */
/* only for fewer than 10 iterations */
/* Declare size, class, and complexity */
/* of variable y by assignment */
memset(&y[0], 0, 50U * sizeof(double));

/* Loop body begins */

29-38
Unroll for-Loops

for (i = 0; i < 25; i++) {


b_i = (i << 1) + 1;
if ((b_i > 2) && (b_i < 48)) {
y[b_i - 1] = b_rand();
}
}

29-39
29 Generate Efficient and Reusable Code

Support for Integer Overflow and Non-Finites


The code generation software generates supporting code for the following situations:

• The result of an integer operation falls outside the range that a data type can
represent. This situation is known as integer overflow.
• An operation generates non-finite values (inf and NaN). The supporting code is
contained in the files rt_nonfinite.c, rtGetInf.c, and rtGetNaN.c (with
corresponding header files).

If you know that these situations do not occur, you can suppress generation of the
supporting code. You therefore reduce the size of the generated code and increase its
speed. However, if one of these situations occurs, it is possible that the generated code
will not match the behavior of the original MATLAB code.

Disable Support for Integer Overflow


You can use the MATLAB Coder app or the command-line interface to disable support for
integer overflow. When you disable this support, the overflow behavior of your generated
code depends on your target C compiler. Most C compilers wrap on overflow.

• Using the app:

1 To open the Generate dialog box, on the Generate Code page, click the
Generate arrow .
2 Click More Settings.
3 To disable support for integer overflow, on the Speed tab, clear Saturate on
integer overflow.
• At the command line:

1 Create a configuration object for code generation. Use coder.config with


arguments 'lib', 'dll', or 'exe' (depending on your requirements). For
example:
cfg = coder.config('lib');
2 To disable support for integer overflow, set the SaturateOnIntegerOverflow
property to false.
cfg.SaturateOnIntegerOverflow = false;

29-40
Support for Integer Overflow and Non-Finites

Disable Support for Non-Finite Numbers


You can use the MATLAB Coder app or the command-line interface to disable support for
non-finite numbers(inf and NaN).

• Using the app:

1 To open the Generate dialog box, on the Generate Code page, click the
Generate arrow .
2 Set Build type to Source Code, Static Library, Dynamic Library, or
Executable (depending on your requirements).
3 Click More Settings.
4 On the Speed tab, clear the Support non-finite numbers check box.
• At the command line:

1 Create a configuration object for code generation. Use coder.config with


arguments 'lib', 'dll', or 'exe' (depending on your requirements). For
example:
cfg = coder.config('lib');
2 To disable support for integer overflow, set the SupportNonFinite property to
false.

cfg.SupportNonFinite = false;

29-41
29 Generate Efficient and Reusable Code

Integrate External/Custom Code


This example shows how to integrate external or custom code to enhance performance
of generated code. Although MATLAB Coder generates optimized code for most
applications, you might have custom code optimized for your specific requirements. For
example:

• You have custom libraries optimized for your target environment.


• You have custom libraries for functions not supported by MATLAB Coder.
• You have custom libraries that meet standards set by your company.

In such cases, you can integrate your custom code with the code generated by MATLAB
Coder.

This example illustrates how to integrate the function cublasSgemm from the NVIDIA®
CUDA® Basic Linear Algebra Subroutines (CUBLAS) library in generated code. This
function performs matrix multiplication on a Graphics Processing Unit (GPU).

1 Define a class ExternalLib_API that derives from the class


coder.ExternalDependency. ExternalLib_API defines an interface to the
CUBLAS library through the following methods:

• getDescriptiveName: Returns a descriptive name for ExternalLib_API to be


used for error messages.
• isSupportedContext: Determines if the build context supports the CUBLAS
library.
• updateBuildInfo: Adds header file paths and link files to the build
information.
• GPU_MatrixMultiply: Defines the interface to the CUBLAS library function
cublasSgemm.

ExternalLib_API.m
classdef ExternalLib_API < coder.ExternalDependency
%#codegen

methods (Static)

function bName = getDescriptiveName(~)


bName = 'ExternalLib_API';

29-42
Integrate External/Custom Code

end

function tf = isSupportedContext(ctx)
if ctx.isMatlabHostTarget()
tf = true;
else
error('CUBLAS library not available for this target');
end
end

function updateBuildInfo(buildInfo, ctx)


[~, linkLibExt, ~, ~] = ctx.getStdLibInfo();

% Include header file path


% Include header files later using coder.cinclude
hdrFilePath = 'C:\My_Includes';
buildInfo.addIncludePaths(hdrFilePath);

% Include link files


linkFiles = strcat('libcublas', linkLibExt);
linkPath = 'C:\My_Libs';
linkPriority = '';
linkPrecompiled = true;
linkLinkOnly = true;
group = '';
buildInfo.addLinkObjects(linkFiles, linkPath, ...
linkPriority, linkPrecompiled, linkLinkOnly, group);

linkFiles = strcat('libcudart', linkLibExt);


buildInfo.addLinkObjects(linkFiles, linkPath, ...
linkPriority, linkPrecompiled, linkLinkOnly, group);

end

%API for library function 'cuda_MatrixMultiply'


function C = GPU_MatrixMultiply(A, B)
assert(isa(A,'single'), 'A must be single.');
assert(isa(B,'single'), 'B must be single.');

if(coder.target('MATLAB'))
C=A*B;
else

% Include header files

29-43
29 Generate Efficient and Reusable Code

% for external functions and typedefs


% Header path included earlier using updateBuildInfo
coder.cinclude('"cuda_runtime.h"');
coder.cinclude('"cublas_v2.h"');

% Compute dimensions of input matrices


m = int32(size(A, 1));
k = int32(size(A, 2));
n = int32(size(B, 2));

% Declare pointers to matrices on destination GPU


d_A = coder.opaque('float*');
d_B = coder.opaque('float*');
d_C = coder.opaque('float*');

% Compute memory to be allocated for matrices


% Single = 4 bytes
size_A = m*k*4;
size_B = k*n*4;
size_C = m*n*4;

% Define error variables


error = coder.opaque('cudaError_t');
cudaSuccessV = coder.opaque('cudaError_t', ...
'cudaSuccess');

% Assign memory on destination GPU


error = coder.ceval('cudaMalloc', ...
coder.wref(d_A), size_A);
assert(error == cudaSuccessV, ...
'cudaMalloc(A) failed');
error = coder.ceval('cudaMalloc', ...
coder.wref(d_B), size_B);
assert(error == cudaSuccessV, ...
'cudaMalloc(B) failed');
error = coder.ceval('cudaMalloc', ...
coder.wref(d_C), size_C);
assert(error == cudaSuccessV, ...
'cudaMalloc(C) failed');

% Define direction of copying


hostToDevice = coder.opaque('cudaMemcpyKind', ...
'cudaMemcpyHostToDevice');

29-44
Integrate External/Custom Code

% Copy matrices to destination GPU


error = coder.ceval('cudaMemcpy', ...
d_A, coder.rref(A), size_A, hostToDevice);
assert(error == cudaSuccessV, 'cudaMemcpy(A) failed');

error = coder.ceval('cudaMemcpy', ...


d_B, coder.rref(B), size_B, hostToDevice);
assert(error == cudaSuccessV, 'cudaMemcpy(B) failed');

% Define type and size for result


C = zeros(m, n, 'single');

error = coder.ceval('cudaMemcpy', ...


d_C, coder.rref(C), size_C, hostToDevice);
assert(error == cudaSuccessV, 'cudaMemcpy(C) failed');

% Define handle variables for external library


handle = coder.opaque('cublasHandle_t');
blasSuccess = coder.opaque('cublasStatus_t', ...
'CUBLAS_STATUS_SUCCESS');

% Initialize external library


ret = coder.opaque('cublasStatus_t');
ret = coder.ceval('cublasCreate', coder.wref(handle));
assert(ret == blasSuccess, 'cublasCreate failed');

TRANSA = coder.opaque('cublasOperation_t', ...


'CUBLAS_OP_N');
alpha = single(1);
beta = single(0);

% Multiply matrices on GPU


ret = coder.ceval('cublasSgemm', handle, ...
TRANSA,TRANSA,m,n,k, ...
coder.rref(alpha),d_A,m, ...
d_B,k, ...
coder.rref(beta),d_C,k);

assert(ret == blasSuccess, 'cublasSgemm failed');

% Copy result back to local host


deviceToHost = coder.opaque('cudaMemcpyKind', ...
'cudaMemcpyDeviceToHost');

29-45
29 Generate Efficient and Reusable Code

error = coder.ceval('cudaMemcpy', coder.wref(C), ...


d_C, size_C, deviceToHost);
assert(error == cudaSuccessV, 'cudaMemcpy(C) failed');

end
end
end
end
2 To perform the matrix multiplication using the interface defined in method
GPU_MatrixMultiply and the build information in ExternalLib_API, include the
following line in your MATLAB code:

C= ExternalLib_API.GPU_MatrixMultiply(A,B);

For instance, you can define a MATLAB function Matrix_Multiply that solely
performs this matrix multiplication.

function C = Matrix_Multiply(A, B) %#codegen


C= ExternalLib_API.GPU_MatrixMultiply(A,B);
3 Define a MEX configuration object using coder.config. For using the CUBLAS
libraries, set the target language for code generation to C++.

cfg=coder.config('mex');
cfg.TargetLang='C++';
4 Generate code for Matrix_Multiply using cfg as the configuration object and two
2 X 2 matrices of type single as arguments. Since cublasSgemm supports matrix
multiplication for data type float, the corresponding MATLAB matrices must have
type single.

codegen -config cfg Matrix_Multiply ...


-args {ones(2,'single'),ones(2,'single')}
5 Test the generated MEX function Matrix_Multiply_mex using two 2 X 2 identity
matrices of type single.

Matrix_Multiply_mex(eye(2,'single'),eye(2,'single'))

The output is also a 2 X 2 identity matrix.

See Also
coder.BuildConfig | assert | coder.ceval | coder.ExternalDependency |
coder.opaque | coder.rref | coder.wref

29-46
Integrate External/Custom Code

Related Examples
• “Encapsulate Interface to an External C Library” on page 28-6

More About
• “Encapsulating the Interface to External Code” on page 28-3

29-47
29 Generate Efficient and Reusable Code

MATLAB Coder Optimizations in Generated Code


In this section...
“Constant Folding” on page 29-48
“Loop Fusion” on page 29-49
“Successive Matrix Operations Combined” on page 29-49
“Unreachable Code Elimination” on page 29-50
“memcpy Calls” on page 29-51
“memset Calls” on page 29-51

In order to improve the execution speed and memory usage of generated code, MATLAB
Coder introduces the following optimizations:

Constant Folding
When possible, the code generation software evaluates expressions in your MATLAB
code that involve compile-time constants only. In the generated code, it replaces these
expressions with the result of the evaluations. This behavior is known as constant
folding. Because of constant folding, the generated code does not have to evaluate the
constants during execution.

The following example shows MATLAB code that is constant-folded during code
generation. The function MultiplyConstant multiplies every element in a matrix by a
scalar constant. The function evaluates this constant using the product of three compile-
time constants, a, b, and c.
function out=MultiplyConstant(in) %#codegen
a=pi^4;
b=1/factorial(4);
c=exp(-1);
out=in.*(a*b*c);
end

The code generation software evaluates the expressions involving compile-time


constants, a,b, and c. It replaces these expressions with the result of the evaluation in
generated code.

Constant folding can occur when the expressions involve scalars only. To explicitly
enforce constant folding of expressions in other cases, use the coder.const function.
For more information, see “Fold Function Calls into Constants” on page 29-15.

29-48
MATLAB Coder Optimizations in Generated Code

Control Constant Folding

You can control the maximum number of instructions that can be constant-folded from
the command line or the project settings dialog box.

• At the command line, create a configuration object for code generation. Set the
property ConstantFoldingTimeout to the value that you want.

cfg=coder.config('lib');
cfg.ConstantFoldingTimeout = 200;
• Using the app, in the project settings dialog box, on the All Settings tab, set the field
Constant folding timeout to the value that you want.

Loop Fusion
When possible, the code generation software fuses successive loops with the same
number of runs into a single loop in the generated code. This optimization reduces loop
overhead.

The following code contains successive loops, which are fused during code generation.
The function SumAndProduct evaluates the sum and product of the elements in an array
Arr. The function uses two separate loops to evaluate the sum y_f_sum and product
y_f_prod.

function [y_f_sum,y_f_prod] = SumAndProduct(Arr) %#codegen


y_f_sum = 0;
y_f_prod = 1;
for i = 1:length(Arr)
y_f_sum = y_f_sum+Arr(i);
end
for i = 1:length(Arr)
y_f_prod = y_f_prod*Arr(i);
end

The code generated from this MATLAB code evaluates the sum and product in a single
loop.

Successive Matrix Operations Combined


When possible, the code generation software converts successive matrix operations in
your MATLAB code into a single loop operation in generated code. This optimization

29-49
29 Generate Efficient and Reusable Code

reduces excess loop overhead involved in performing the matrix operations in separate
loops.

The following example contains code where successive matrix operations take place. The
function ManipulateMatrix multiplies every element of a matrix Mat with a factor.
To every element in the result, the function then adds a shift:

function Res=ManipulateMatrix(Mat,factor,shift)
Res=Mat*factor;
Res=Res+shift;
end

The generated code combines the multiplication and addition into a single loop operation.

Unreachable Code Elimination


When possible, the code generation software suppresses code generation from
unreachable procedures in your MATLAB code. For instance, if a branch of an if,
elseif, else statement is unreachable, then code is not generated for that branch.

The following example contains unreachable code, which is eliminated during code
generation. The function SaturateValue returns a value based on the range of its input
x.

function y_b = SaturateValue(x) %#codegen


if x>0
y_b = x;
elseif x>10 %This is redundant
y_b = 10;
else
y_b = -x;
end

The second branch of the if, elseif, else statement is unreachable. If the variable
x is greater than 10, it is also greater than 0. Therefore, the first branch is executed in
preference to the second branch.

MATLAB Coder does not generate code for the unreachable second branch.

29-50
MATLAB Coder Optimizations in Generated Code

memcpy Calls
To optimize generated code that copies consecutive array elements, the code generation
software tries to replace the code with a memcpy call. A memcpy call can be more efficient
than code, such as a for-loop or multiple, consecutive element assignments.

See “memcpy Optimization” on page 29-52.

memset Calls
To optimize generated code that assigns a literal constant to consecutive array elements,
the code generation software tries to replace the code with a memset call. A memset call
can be more efficient than code, such as a for-loop or multiple, consecutive element
assignments.

See “memset Optimization” on page 29-54.

29-51
29 Generate Efficient and Reusable Code

memcpy Optimization
To optimize generated code that copies consecutive array elements, the code generation
software tries to replace the code with a memcpy call. A memcpy call can be more efficient
than code, such as a for-loop or multiple, consecutive element assignments.

Code Generated with the memcpy Code Generated without the memcpy
Optimization Optimization
memcpy(&C[0], &A[0], 10000U * sizeof(double)); for (i0 = 0; i0 < 10000; i0++) {
C[i0] = A[i0];
memcpy(&Z[0], &X[0],1000U * sizeof(double)); Z[0] = X[0];
Z[1] = X[1];
Z[2] = X[2];
...
Z[999] = X[999];

The code generation software invokes the memcpy optimization if the following conditions
are true:

• The memcpy optimization is enabled.


• The number of bytes to copy is greater than or equal to the memcpy threshold. The
number of bytes to copy is the number of array elements multiplied by the number of
bytes required for the C/C++ data type.

To enable or disable the memcpy optimization:

• At the command line, set the code configuration object property EnableMemcpy to
true or false, respectively. The default value is true.
• In the MATLAB Coder app, set Use memcpy for vector assignment to Yes or No
respectively. The default value is Yes.

The default memcpy threshold is 64 bytes. To change the threshold:

• At the command line, set the code configuration object property MemcpyThreshold.
• In the MATLAB Coder app, set Memcpy threshold (bytes).

The memset optimization also uses the memcpy threshold.

More About
• “memset Optimization” on page 29-54
• “MATLAB Coder Optimizations in Generated Code” on page 29-48

29-52
memcpy Optimization

• “Optimization Strategies” on page 29-3

29-53
29 Generate Efficient and Reusable Code

memset Optimization
To optimize generated code that assigns a literal constant to consecutive array elements,
the code generation software tries to replace the code with a memset call. A memset call
can be more efficient than code, such as a for-loop or multiple, consecutive element
assignments.

Code Generated with the memset Code Generated without the memset
Optimization Optimization
memset(&Y[0], 125, 100U * sizeof(signed char)); for (i = 0; i < 100; i++) {
Y[i] = 125;
memset(&Y[0], 0, 10000U * sizeof(double)); for (i0 = 0; i0 < 10000; i0++) {
Y[i0] = 0.0;
memset(&Z[0], 0, 1000U * sizeof(double)); Z[0] = 0.0;
Z[1] = 0.0;
Z[2] = 0.0;
...
Z[999] = 0.0;

memset Optimization for an Integer Constant


To assign an integer constant to consecutive array elements, the code generation
software invokes the memset optimization when the following conditions are true:

• The constant is a literal constant. For example, X[i] = 5.


• For a nonzero constant:

• The type of the constant is not multiword.


• The length in bits of the type of the constant is the same as the length in bits of
the C char type that the hardware supports.
• The number of bytes to assign is greater than or equal to the memset optimization
threshold. The number of bytes to assign is the number of array elements multiplied
by the number of bytes required for the C/C++ data type.

The memset optimization threshold is the same as the memcpy optimization threshold.
The default threshold is 64 bytes. To change the threshold:

• At the command line, set the code configuration object property MemcpyThreshold.
• In the MATLAB Coder app, set Memcpy threshold (bytes).

29-54
memset Optimization

memset Optimization for Float or Double Zero


To assign a float or double 0 to consecutive array elements, the code generation software
invokes the memset optimization when the following conditions are true:

• The constant is a literal constant. For example, X[i] = 0.0.


• The memset optimization is enabled for assignment of float or double 0 to consecutive
array elements.
• The number of bytes to assign is greater than or equal to the memset optimization
threshold. The number of bytes to assign is the number of array elements multiplied
by the number of bytes required for the C/C++ data type.

To enable or disable the memset optimization for assignment of float or double 0 to


consecutive array elements:

• At the command line, set the code configuration object property


InitFltsAndDblsToZero to true or false, respectively. The default value is true.
• In the MATLAB Coder app, set Use memset to initialize floats and doubles to
0.0 to Yes or No respectively. The default value is Yes.

The memset optimization threshold is the same as the memcpy optimization threshold.
The default threshold is 64 bytes. To change the threshold:

• At the command line, set the code configuration object property MemcpyThreshold.
• In the MATLAB Coder app, set Memcpy threshold (bytes).

More About
• “memcpy Optimization” on page 29-52
• “MATLAB Coder Optimizations in Generated Code” on page 29-48
• “Optimization Strategies” on page 29-3

29-55
29 Generate Efficient and Reusable Code

Generate Reusable Code


With MATLAB, you can generate reusable code in the following ways:

• Write reusable functions using standard MATLAB function file names which you can
call from different locations, for example, in a Simulink model or MATLAB function
library.
• Compile external functions on the MATLAB path and integrate them into generated
C code for embedded targets.

See “Resolution of Function Calls for Code Generation” on page 14-2.

Common applications include:

• Overriding generated library function with a custom implementation.


• Implementing a reusable library on top of standard library functions that can be used
with Simulink.
• Swapping between different implementations of the same function.

29-56
Reuse Large Arrays and Structures

Reuse Large Arrays and Structures


To reduce memory usage, when possible, variables share names and memory in the
generated code. By default, for readability, this variable reuse optimization preserves
your name for a variable. It does not reuse your variable name for another variable
or reuse another variable name for your variable. If your code has large arrays or
structures, the extra memory required to preserve your variable names can affect
performance. In this case, to reduce memory usage, specify that the variable reuse
optimization does not have to preserve variable names. The optimization can, therefore,
reuse any variables that meet the requirements for variable reuse.

• Using the MATLAB Coder app, in the project settings dialog box, on the All Settings
tab, set Preserve variable names to None.
• Using the command-line interface:

1 Create a code configuration object for 'mex', 'lib', 'dll', or 'exe'. For
example:
cfg = coder.config('lib'); % or mex, dll, exe
2 Set the PreserveVariableNames property to None.

cfg.PreserveVariableNames = 'None';

More About
• “Variable Reuse in Generated Code” on page 29-58
• “Optimization Strategies” on page 29-3

29-57
29 Generate Efficient and Reusable Code

Variable Reuse in Generated Code


To reduce memory usage, MATLAB Coder can reuse the name and memory of one
variable for another variable when:

• Both variables have the same memory requirements.


• Memory access for one variable does not interfere with memory access for the other.

By default, this variable reuse optimization preserves your variable names in the
generated code. It does not reuse your variable name for another variable or reuse
another variable name for your variable. For example, for code such as:
if (s>0)
myvar1 = 0;
...
else
myvar2 = 0;
...
end
the generated code might look like:
if (s > 0.0) {
myvar1 = 0.0;
...
} else {
myvar2 = 0.0;
...
}

You can configure the variable reuse optimization so that it does not preserve your
variable names. For an example, see “Reuse Large Arrays and Structures” on page 29-57.
When the optimization does not preserve your variable names, the generated code might
look like:
if (s > 0.0) {
myvar2 = 0.0;
...
} else {
myvar2 = 0.0;
...
}

In this case, the optimization uses myvar2 for myvar1.

29-58
LAPACK Calls in Generated Code

LAPACK Calls in Generated Code


To improve the execution speed of code generated for certain linear algebra functions,
MATLAB Coder can generate calls to LAPACK functions instead of generating the code
for the linear algebra functions. LAPACK is a software library for numerical linear
algebra. MATLAB Coder uses the LAPACKE C interface to LAPACK.

For MEX generation, if the input arrays for the linear algebra functions meet certain
criteria, the code generation software generates LAPACK calls. For standalone code
(library or executable program), by default, the code generation software does not
generate LAPACK calls. If you specify that you want to generate LAPACK calls, and
the input arrays for the linear algebra functions meet the criteria, the code generation
software generates LAPACK calls. See “Speed Up Linear Algebra in Generated
Standalone Code by Using LAPACK Calls” on page 29-60.

For MEX functions, the code generation software uses the LAPACK library that is
included with MATLAB. MATLAB uses LAPACK in some linear algebra functions such
as eig and svd. For standalone code, the code generation software uses the LAPACK
library that you specify. See “Specify LAPACK Library” on page 29-60.

More About
• “Optimization Strategies” on page 29-3

External Websites
• www.netlib.org/lapack

29-59
29 Generate Efficient and Reusable Code

Speed Up Linear Algebra in Generated Standalone Code by Using


LAPACK Calls
To improve the execution speed of code generated for certain linear algebra functions in
standalone (library or executable program) code, specify that you want MATLAB Coder
to generate LAPACK calls. LAPACK is a software library for numerical linear algebra.
MATLAB Coder uses the LAPACKE C interface to LAPACK. If you specify that you want
to generate LAPACK calls, and the input arrays for the linear algebra functions meet
certain criteria, the code generation software generates the LAPACK calls. Otherwise,
the code generation software generates code for the linear algebra functions.

For LAPACK calls in standalone code, MATLAB Coder uses the


LAPACK library that you specify. Specify a LAPACK library that is
optimized for your execution environment. See www.netlib.org/lapack/
faq.html#_what_and_where_are_the_lapack_vendors_implementations.

Specify LAPACK Library


To generate LAPACK calls in standalone code, you must have access to a LAPACK
callback class. A LAPACK callback class specifies the LAPACK library and LAPACKE
header file for the LAPACK calls. To indicate that you want to generate LAPACK calls
and that you want to use a specific LAPACK library, specify the name of the LAPACK
callback class.

• At the command line, set the code configuration object property


CustomLAPACKCallback to the name of the callback class.
• In the MATLAB Coder app, set Custom LAPACK library callback to the name of
the callback class.

Write LAPACK Callback Class


To specify the locations of a particular LAPACK library and LAPACKE header file, write
a LAPACK callback class. Share the callback class with others who want to use this
LAPACK library for LAPACK calls in standalone code.

The callback class must derive from the abstract class coder.LAPACKCallback. Use the
following example callback class as a template.

classdef useMyLAPACK < coder.LAPACKCallback

29-60
Speed Up Linear Algebra in Generated Standalone Code by Using LAPACK Calls

methods (Static)
function hn = getHeaderFilename()
hn = 'mylapacke_custom.h';
end
function updateBuildInfo(buildInfo, buildctx)
buildInfo.addIncludePaths(fullfile(pwd,'include'));
libName = 'mylapack';
libPath = fullfile(pwd,'lib');
[~,linkLibExt] = buildctx.getStdLibInfo();
buildInfo.addLinkObjects([libName linkLibExt], libPath, ...
'', true, true);
buildInfo.addDefines('HAVE_LAPACK_CONFIG_H');
buildInfo.addDefines('LAPACK_COMPLEX_STRUCTURE');
end
end
end

You must provide the getHeaderFilename and updateBuildInfo methods. The


getHeaderFilename method returns the LAPACKE header file name. In the example
callback class, replace mylapacke_custom.h with the name of your LAPACKE header
file. The updateBuildInfo method provides the information required for the build
process to link to the LAPACK library. Use code like the code in the template to specify
the location of header files and the full path name of the LAPACK library. In the
example callback class, replace mylapack with the name of your LAPACK library.

If your compiler supports only complex data types that are represented as structures,
include these lines in the updateBuildInfo method.
buildInfo.addDefines('HAVE_LAPACK_CONFIG_H');
buildInfo.addDefines('LAPACK_COMPLEX_STRUCTURE');

Generate LAPACK Calls by Specifying a LAPACK Callback Class


This example shows how to generate code that calls LAPACK functions in a specific
LAPACK library. For this example, assume that the LAPACK callback class
useMyLAPACK specifies the LAPACK library that you want to use.

1 Write a MATLAB function that calls a linear algebra function. For example, write a
function mysvd that calls the MATLAB function svd.
function s = mysvd(A)
%#codegen
s = svd(A);

29-61
29 Generate Efficient and Reusable Code

end
2 Define a code configuration object for a static library, dynamically linked library, or
executable program. For example, define a configuration object for a dynamically
linked library on a Windows platform.
cfg = coder.config('dll');
3 Specify the LAPACK callback class useMyLAPACK.
cfg.CustomLAPACKCallback = 'useMyLAPACK';

The callback class must be on the MATLAB path.


4 Generate code. Specify that the input A is a 500-by-500 array of doubles.
codegen test -args {zeros(500)} -config cfg -report

If A is large enough, the code generation software generates a LAPACK call for svd. Here
is an example of a call to the LAPACK library function for svd.
info_t = LAPACKE_dgesvd(LAPACK_COL_MAJOR, 'N', 'N', (lapack_int)500,
(lapack_int)500, &A[0], (lapack_int)500, &S[0], NULL, (lapack_int)1, NULL,
(lapack_int)1, &superb[0]);

Locate LAPACK Library in Execution Environment


The LAPACK library must be available in your execution environment. If your LAPACK
library is shared, use environment variables or linker options to specify the location of
the LAPACK library.

• On a Windows platform, modify the PATH environment variable.


• On a Linux platform, modify the LD_LIBRARY_PATH environment variable or use
the rpath linker option.
• On a Mac OS X, modify the DYLD_LIBRARY_PATH environment variable or use the
rpath linker option.

To specify the rpath linker option, you can use the build information addLinkFlags
method in the updateBuildInfo method of your coder.LAPACKCallback class. For
example, for a GCC compiler:
buildInfo.addLinkFlags(sprintf('-Wl,-rpath,"%s"',libPath));

See Also
coder.LAPACKCallback

29-62
Speed Up Linear Algebra in Generated Standalone Code by Using LAPACK Calls

More About
• “LAPACK Calls in Generated Code” on page 29-59
• “Optimization Strategies” on page 29-3

External Websites
• www.netlib.org/lapack
• www.netlib.org/lapack/
faq.html#_what_and_where_are_the_lapack_vendors_implementations

29-63
30

Generating Reentrant C Code from


MATLAB Code

• “Generate Reentrant C Code from MATLAB Code” on page 30-2


• “Reentrant Code” on page 30-10
• “Specify Generation of Reentrant Code” on page 30-12
• “Generated Code API” on page 30-14
• “Call Reentrant Code in a Single-Thread Environment” on page 30-15
• “Call Reentrant Code in a Multithreaded Environment” on page 30-16
• “Call Reentrant Code with No Persistent or Global Data (UNIX Only)” on page
30-17
• “Call Reentrant Code — Multithreaded with Persistent Data (Windows Only)” on
page 30-22
• “Call Reentrant Code — Multithreaded with Persistent Data (UNIX Only)” on page
30-27
30 Generating Reentrant C Code from MATLAB Code

Generate Reentrant C Code from MATLAB Code


In this section...
“About This Tutorial” on page 30-2
“Copying Files Locally” on page 30-3
“About the Example” on page 30-4
“Providing a C main Function” on page 30-5
“Configuring Build Parameters” on page 30-6
“Generating the C Code” on page 30-7
“Viewing the Generated C Code” on page 30-7
“Running the Code” on page 30-8
“Key Points to Remember” on page 30-8
“Learn More” on page 30-9

About This Tutorial


Learning Objectives

This tutorial shows you how to:

• Generate reentrant code from MATLAB code that does not use persistent or global
data.
• Automatically generate C code from your MATLAB code.
• Define function input properties at the command line.
• Specify code generation properties.
• Generate a code generation report that you can use to view and debug your MATLAB
code.

Note: This example runs on Windows only.

Prerequisites

To complete this example, install the following products:

30-2
Generate Reentrant C Code from MATLAB Code

• MATLAB
• MATLAB Coder
• C compiler (for most platforms, a default C compiler is supplied with MATLAB).
MATLAB Coder locates and uses a supported installed compiler. For the current list
of supported compilers, see http://www.mathworks.com/support/compilers/
current_release/ on the MathWorks website.

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

Required Files

Type Name Description


Function code matrix_exp.m MATLAB function that
computes matrix exponential
of the input matrix using
Taylor series and returns the
computed output.
C main function main.c Calls the reentrant code.

Copying Files Locally


Copy the tutorial files to a local working folder.

1 Create a local working folder, for example, c:\coder\work.


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

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


3 Copy the reentrant_win folder to your local working folder.

Your work folder now contains the files for the tutorial.
4 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.

30-3
30 Generating Reentrant C Code from MATLAB Code

About the Example


This example requires libraries that are specific to the Microsoft Windows operating
system and, therefore, runs only on Windows platforms. It is a simple, multithreaded
example that does not use persistent or global data. Two threads call the MATLAB
function matrix_exp with different sets of input data.

Contents of matrix_exp.m
function Y = matrix_exp(X) %#codegen
%
% The function matrix_exp computes matrix exponential of
% the input matrix using Taylor series and returns the
% computed output.
E = zeros(size(X));
F = eye(size(X));
k = 1;
while norm(E+F-E,1) > 0
E = E + F;
F = X*F/k;
k = k+1;
end
Y = E;

When you generate reusable, reentrant code, MATLAB Coder supports dynamic
allocation of:

• Function variables that are too large for the stack


• Persistent variables
• Global variables

MATLAB Coder generates a header file, primary_function_name_types.h, that


you must include when using the generated code. This header file contains the following
structures:

• primary_function_nameStackData

Contains the user allocated memory. Pass a pointer to this structure as the first
parameter to functions that use it:

• Directly (the function uses a field in the structure)


• Indirectly (the function passes the structure to a called function)

If the algorithm uses persistent or global data, the


primary_function_nameStackData structure also contains a pointer to the

30-4
Generate Reentrant C Code from MATLAB Code

primary_function_namePersistentData structure. If you include this pointer,


you have to pass only one parameter to each calling function.
• primary_function_namePersistentData

If your algorithm uses persistent or global variables, MATLAB Coder provides a


separate structure for them. The memory allocation structure contains a pointer to
this persistent data structure.Because you have a separate structure for persistent
and global variables, you can allocate memory for these variables once and share
them with all threads. However, if the threads do not communicate, you can allocate
memory for these variables per thread or per application.

Providing a C main Function


To call the reentrant code, provide a main function that:

• Includes the generated header file matrix_exp.h. This file includes the generated
header file, matrix_exp_types.h.
• For each thread, allocates memory for stack data.
• Calls the matrix_exp_initialize housekeeping function. For more information,
see “Calling Initialize and Terminate Functions” on page 25-7.
• Calls matrix_exp.
• Calls matrix_exp_terminate.
• Frees up the for stack data memory.

Contents of main.c
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "matrix_exp.h"
#include "matrix_exp_initialize.h"
#include "matrix_exp_terminate.h"
#include "rtwtypes.h"
#define NUMELEMENTS (160*160)

typedef struct {
real_T in[NUMELEMENTS];
real_T out[NUMELEMENTS];
matrix_expStackData* spillData;
} IODATA;

/* The thread_function calls the matrix_exp function written in MATLAB */


DWORD WINAPI thread_function(PVOID dummyPtr) {
IODATA *myIOData = (IODATA*)dummyPtr;
matrix_exp_initialize();
matrix_exp(myIOData->spillData, myIOData->in, myIOData->out);

30-5
30 Generating Reentrant C Code from MATLAB Code

matrix_exp_terminate();
return 0;
}

void main() {
HANDLE thread1, thread2;
IODATA data1;
IODATA data2;
int32_T i;

/*Initializing data for passing to the 2 threads*/


matrix_expStackData* sd1 = (matrix_expStackData*)calloc(1,sizeof(matrix_expStackData));
matrix_expStackData* sd2 = (matrix_expStackData*)calloc(1,sizeof(matrix_expStackData));

data1.spillData = sd1;
data2.spillData = sd2;

for (i=0;i<NUMELEMENTS;i++) {
data1.in[i] = 1;
data1.out[i] = 0;
data2.in[i] = 1.1;
data2.out[i] = 0;
}

/*Initializing the 2 threads and passing data to the thread functions*/


printf("Starting thread 1...\n");
thread1 = CreateThread(NULL , 0, thread_function, (PVOID) &data1, 0, NULL);
if (thread1 == NULL){
perror( "Thread 1 creation failed.");
exit(EXIT_FAILURE);
}

printf("Starting thread 2...\n");


thread2 = CreateThread(NULL, 0, thread_function, (PVOID) &data2, 0, NULL);
if (thread2 == NULL){
perror( "Thread 2 creation failed.");
exit(EXIT_FAILURE);
}

/*Wait for both the threads to finish execution*/


if (WaitForSingleObject(thread1, INFINITE) != WAIT_OBJECT_0){
perror( "Thread 1 join failed.");
exit(EXIT_FAILURE);
}

if (WaitForSingleObject(thread2, INFINITE) != WAIT_OBJECT_0){


perror( "Thread 2 join failed.");
exit(EXIT_FAILURE);
}

free(sd1);
free(sd2);

printf("Finished Execution!\n");
exit(EXIT_SUCCESS);
}

Configuring Build Parameters


You can enable generation of reentrant code using a code generation configuration object.

30-6
Generate Reentrant C Code from MATLAB Code

1 Create a configuration object.


cfg = coder.config('exe');
2 Enable reentrant code generation.
cfg.MultiInstanceCode = true;

Generating the C Code


Call the codegen function to generate C code, with the following options:

• -config to pass in the code generation configuration object cfg.


• main.c to include this file in the compilation.
• -report to create a code generation report.
• -args to specify the class, size, and complexity of input arguments using example
data.
codegen -config cfg main.c -report matrix_exp.m -args ones(160,160)

codegen generates a C executable, matrix_exp.exe, in the current folder and C code


in the /codegen/exe/matrix_exp subfolder. Because you selected report generation,
codegen provides a link to the report.

Viewing the Generated C Code


codegen generates a header file matrix_exp_types.h, which defines the
matrix_expStackData global structure. This structure contains local variables that are
too large to fit on the stack.

To view this header file:

1 Click the View report link to open the code generation report.
2 In the report, click the C code tab.
3 On this tab, click the link to matrix_exp_types.h.

/*
* matrix_exp_types.h
*
* Code generation for function 'matrix_exp'
*
*/

30-7
30 Generating Reentrant C Code from MATLAB Code

#ifndef __MATRIX_EXP_TYPES_H__
#define __MATRIX_EXP_TYPES_H__

/* Include files */
#include "rtwtypes.h"

/* Type Definitions */
#ifndef typedef_matrix_expStackData
#define typedef_matrix_expStackData

typedef struct {
struct {
double F[25600];
double Y[25600];
double X[25600];
} f0;
} matrix_expStackData;

#endif /*typedef_matrix_expStackData*/
#endif

/* End of code generation (matrix_exp_types.h) */

Running the Code


Verify that the example is running on Windows platforms and call the code.

% This example can only be run on Windows platforms


if ~ispc
error('This example requires Windows-specific libraries and can only be run on Windows.');
end
system('matrix_exp.exe')

The executable runs and reports completion.

Key Points to Remember


• Create a main function that:

• Includes the generated header file, primary_function_name_types.h. This file


defines the primary_function_nameStackData global structure. This structure
contains local variables that are too large to fit on the stack.
• For each thread, allocates memory for stack data.
• Calls primary_function_name_initialize.
• Calls primary_function_name.

30-8
Generate Reentrant C Code from MATLAB Code

• Calls primary_function_name_terminate.
• Frees the stack data memory.
• Use the -config option to pass the code generation configuration object to the
codegen function.
• Use the -args option to specify input parameters at the command line.
• Use the -report option to create a code generation report.

Learn More
To See
Learn more about the generated code API “Generated Code API” on page 30-14
Call reentrant code without persistent or global “Call Reentrant Code with No Persistent or
data on UNIX Global Data (UNIX Only)” on page 30-17
Call reentrant code with persistent data on “Call Reentrant Code — Multithreaded with
Windows Persistent Data (Windows Only)” on page
30-22
Call reentrant code with persistent data on “Call Reentrant Code — Multithreaded with
UNIX Persistent Data (UNIX Only)” on page 30-27

30-9
30 Generating Reentrant C Code from MATLAB Code

Reentrant Code
Reentrant code is a reusable programming routine that multiple programs can use
simultaneously. Operating systems and other system software that use multithreading
to handle concurrent events use reentrant code. In a concurrent environment, multiple
threads or processes can attempt to read and write static data simultaneously. Therefore,
sharing code that uses persistent or static data is difficult. Reentrant code does not
contain static data. Calling programs maintain their state variables and pass them into
the function. Therefore, any number of threads or processes can share one copy of a
reentrant routine.

Generate reentrant code when you want to:

• Deploy your code in multithreaded environments.


• Use an algorithm with persistent data belonging to different processes or threads.
• Compile code that uses function variables that are too large to fit on the stack.

If you do not specify reentrant code, MATLAB Coder generates code that uses statically
allocated memory for:

• Function variables that are too large to fit on the stack


• Global variables
• Persistent variables

If the generated code uses static memory allocation for these variables, you cannot deploy
the generated code in environments that require reentrant code. If you cannot adjust
the static memory allocation size, the generated code can result in static memory size
overflow.

When you generate reentrant code, MATLAB Coder creates input data structures for:

• Function variables that are too large to fit on the stack


• Persistent variables
• Global variables

You can then dynamically allocate memory for these input structures. The use
of dynamic memory allocation means that you can deploy the code in reentrant
environments.

30-10
Reentrant Code

Related Examples
• “Specify Generation of Reentrant Code” on page 30-12
• “Generate Reentrant C Code from MATLAB Code” on page 30-2
• “Call Reentrant Code with No Persistent or Global Data (UNIX Only)” on page
30-17
• “Call Reentrant Code — Multithreaded with Persistent Data (Windows Only)” on
page 30-22
• “Call Reentrant Code — Multithreaded with Persistent Data (UNIX Only)” on page
30-27

30-11
30 Generating Reentrant C Code from MATLAB Code

Specify Generation of Reentrant Code


In this section...
“Specify Generation of Reentrant Code Using the MATLAB Coder App” on page
30-12
“Specify Generation of Reentrant Code Using the Command-Line Interface” on page
30-12

Specify Generation of Reentrant Code Using the MATLAB Coder App


1
On the Generate Code page, click the Generate arrow .
2 Set Build type to one of the following:

• Source Code
• Static Library (.lib)
• Dynamic Library (.dll)
• Executable (.exe)
3 Click More Settings.
4 On the Memory tab, select the Generate re-entrant code check box.

Specify Generation of Reentrant Code Using the Command-Line Interface


1 Create a code configuration object for 'lib', 'dll', or 'exe'. For example:

cfg = coder.config('lib'); % or dll or exe


2 Set the MultiInstanceCode property to true. For example:

cfg.MultiInstanceCode = true;

Related Examples
• “Generate Reentrant C Code from MATLAB Code” on page 30-2
• “Call Reentrant Code with No Persistent or Global Data (UNIX Only)” on page
30-17
• “Call Reentrant Code — Multithreaded with Persistent Data (Windows Only)” on
page 30-22

30-12
Specify Generation of Reentrant Code

• “Call Reentrant Code — Multithreaded with Persistent Data (UNIX Only)” on page
30-27

More About
• “Reentrant Code” on page 30-10

30-13
30 Generating Reentrant C Code from MATLAB Code

Generated Code API


When you generate reusable code, MATLAB Coder supports dynamic allocation of:

• Function variables that are too large for the stack


• Persistent variables
• Global variables

It generates a header file, primary_function_name_types.h, that you must include


when using the generated code. This header file contains the following structures:

• primary_function_nameStackData

This structure contains the user-allocated memory. You must pass a pointer to this
structure as the first parameter to all functions that use it:

• Directly, because the function uses a field in the structure.


• Indirectly, because the function passes the structure to a called function.

If the algorithm uses persistent or global data, the


primary_function_nameStackData structure also contains a pointer to the
primary_function_namePersistentData structure. If you include this pointer,
you only have to pass one parameter to each calling function.
• primary_function_namePersistentData

If your algorithm uses persistent or global variables, MATLAB Coder provides a


separate structure for them. The memory allocation structure contains a pointer
to this structure. Because you have a separate structure for persistent and global
variables, you can allocate memory for these variables once and share them with all
threads. However, if there is no communication between threads, you can choose to
allocate memory for these variables per thread or per application.

For more information on using these global structures, see “Multithreaded Examples” on
page 30-16.

30-14
Call Reentrant Code in a Single-Thread Environment

Call Reentrant Code in a Single-Thread Environment


To call reentrant code in a single-thread environment, create a main function that:

• Includes the header file primary_function_name.h.


• Allocates memory for the global memory allocation structure
primary_function_nameStackData.
• If the algorithm uses persistent or global data, allocates memory for the global
structure primary_function_namePersistentData.
• Calls these functions:

• primary_function_name_initialize.
• primary_function_name.
• primary_function_name_terminate.

When you convert a MATLAB function to a C/C++ library function or a C/C++


executable, MATLAB Coder generates two housekeeping functions. Call these
housekeeping functions in the code that calls the generated C/C++ function. For more
information, see “Calling Initialize and Terminate Functions” on page 25-7.
• Frees the memory used for global structures.

30-15
30 Generating Reentrant C Code from MATLAB Code

Call Reentrant Code in a Multithreaded Environment


To call reentrant code, create a main function that:

• Includes the header file primary_function_name.h.


• For each thread, allocates memory for the global memory allocation structure
primary_function_nameStackData.
• If the algorithm uses persistent or global data, allocates memory for the global
structure primary_function_namePersistentData. If the threads communicate,
allocate this memory once for the application. Otherwise, you can choose to allocate
memory per thread or per application.
• Contains a thread function that calls these functions:

• primary_function_name_initialize.
• primary_function_name.
• primary_function_name_terminate.

When you convert a MATLAB function to a C/C++ library function or a C/C++


executable, MATLAB Coder generates two housekeeping functions. Call these
functions in the code that calls the generated C/C++ function. For more information,
see “Calling Initialize and Terminate Functions” on page 25-7.
• Initializes each thread and passes in a pointer to the memory allocation structure as
the first parameter to the thread function.
• Frees up the memory used for global structures.

Multithreaded Examples
Type of Reentrant Code Platform Reference
Multithreaded without Windows “Generate Reentrant C Code from MATLAB Code” on
persistent or global data page 30-2
UNIX “Call Reentrant Code with No Persistent or Global Data
(UNIX Only)” on page 30-17
Multithreaded with Windows “Call Reentrant Code — Multithreaded with Persistent
persistent or global data Data (Windows Only)” on page 30-22
UNIX “Call Reentrant Code — Multithreaded with Persistent
Data (UNIX Only)” on page 30-27

30-16
Call Reentrant Code with No Persistent or Global Data (UNIX Only)

Call Reentrant Code with No Persistent or Global Data (UNIX Only)


In this section...
“Provide a Main Function” on page 30-17
“Generate Reentrant C Code” on page 30-19
“Examine the Generated Code” on page 30-20
“Run the Code” on page 30-21

This example requires POSIX thread (pthread) libraries and, therefore, runs only on
UNIX platforms. It is a simple multithreaded example that uses no persistent or global
data. Two threads call the MATLAB function matrix_exp with different sets of input
data.

Provide a Main Function


To call the reentrant code, provide a main function that:

• Includes the header file matrix_exp.h.


• For each thread, allocates memory for stack data.
• Calls the matrix_exp_initialize housekeeping function. For more information,
see “Calling Initialize and Terminate Functions” on page 25-7.
• Calls matrix_exp.
• Calls matrix_exp_terminate.
• Frees the memory used for stack data.

For this example, main.c contains:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "matrix_exp.h"
#include "matrix_exp_initialize.h"
#include "matrix_exp_terminate.h"
#include "rtwtypes.h"
#define NUMELEMENTS (160*160)

typedef struct {
real_T in[NUMELEMENTS];
real_T out[NUMELEMENTS];
matrix_expStackData* spillData;
} IODATA;

30-17
30 Generating Reentrant C Code from MATLAB Code

/* The thread_function calls the matrix_exp function written in MATLAB */


void *thread_function(void *dummyPtr) {
IODATA *myIOData = (IODATA*)dummyPtr;
matrix_exp_initialize();
matrix_exp(myIOData->spillData, myIOData->in, myIOData->out);
matrix_exp_terminate();
}

int main() {
pthread_t thread1, thread2;
int iret1, iret2;
IODATA data1;
IODATA data2;
int32_T i;

/*Initializing data for passing to the 2 threads*/


matrix_expStackData* sd1=(matrix_expStackData*)calloc(1,sizeof(matrix_expStackData));
matrix_expStackData* sd2=(matrix_expStackData*)calloc(1,sizeof(matrix_expStackData));

data1.spillData = sd1;
data2.spillData = sd2;

for (i=0;i<NUMELEMENTS;i++) {
data1.in[i] = 1;
data1.out[i] = 0;
data2.in[i] = 1.1;
data2.out[i] = 0;
}

/*Initializing the 2 threads and passing required data to the thread functions*/
printf("Starting thread 1...\n");
iret1 = pthread_create(&thread1, NULL, thread_function, (void*) &data1);
if (iret1 != 0){
perror( "Thread 1 creation failed.");
exit(EXIT_FAILURE);
}

printf("Starting thread 2...\n");


iret2 = pthread_create(&thread2, NULL, thread_function, (void*) &data2);
if (iret2 != 0){
perror( "Thread 2 creation failed.");
exit(EXIT_FAILURE);
}

/*Wait for both the threads to finish execution*/


iret1 = pthread_join(thread1, NULL);
if (iret1 != 0){
perror( "Thread 1 join failed.");
exit(EXIT_FAILURE);
}

iret2 = pthread_join(thread2, NULL);


if (iret2 != 0){
perror( "Thread 2 join failed.");

30-18
Call Reentrant Code with No Persistent or Global Data (UNIX Only)

exit(EXIT_FAILURE);
}

free(sd1);
free(sd2);

printf("Finished Execution!\n");
exit(EXIT_SUCCESS);

Generate Reentrant C Code


To generate code, run the following script at the MATLAB command prompt.

% This example can only be run on Unix platforms


if ~isunix
error('This example requires pthread libraries and can only be run on Unix.');
end

% Setting the options for the Config object

% Create a code gen configuration object


cfg = coder.config('exe');

% Enable reentrant code generation


cfg.MultiInstanceCode = true;

% Set the post code generation command to be the 'setbuildargs' function


cfg.PostCodeGenCommand = 'setbuildargs(buildInfo)';

% Compiling
codegen -config cfg main.c matrix_exp.m -report -args ones(160,160)

This script:

• Generates an error message if the example is not running on a UNIX platform.


• Creates a code configuration object for generation of an executable.
• Enables the MultiInstanceCode option to generate reusable, reentrant code.
• Uses the PostCodeGenCommand option to set the post code generation command to
be the setbuildargs function. This function sets the -lpthread flag to specify that
the build include the pthread library.
function setbuildargs(buildInfo)
% The example being compiled requires pthread support.
% The -lpthread flag requests that the pthread library
% be included in the build
linkFlags = {'-lpthread'};

30-19
30 Generating Reentrant C Code from MATLAB Code

addLinkFlags(buildInfo, linkFlags);

For more information, see “Customize the Post-Code-Generation Build Process” on


page 21-138.
• Invokes codegen with the following options:

• -config to pass in the code generation configuration object cfg.


• main.c to include this file in the compilation.
• -report to create a code generation report.
• -args to specify an example input with class, size, and complexity.

Examine the Generated Code


codegen generates a header file matrix_exp_types.h, which defines the
matrix_expStackData global structure. This structure contains local variables that are
too large to fit on the stack.

/*
* matrix_exp_types.h
*
* Code generation for function 'matrix_exp'
*
*/

#ifndef __MATRIX_EXP_TYPES_H__
#define __MATRIX_EXP_TYPES_H__

/* Include files */
#include "rtwtypes.h"

/* Type Definitions */
#ifndef typedef_matrix_expStackData
#define typedef_matrix_expStackData

typedef struct {
struct {
double F[25600];
double Y[25600];
double X[25600];
} f0;
} matrix_expStackData;

#endif /*typedef_matrix_expStackData*/
#endif

/* End of code generation (matrix_exp_types.h) */

30-20
Call Reentrant Code with No Persistent or Global Data (UNIX Only)

Run the Code


Call the code using the command:
system('./matrix_exp')
The executable runs and reports completion.

30-21
30 Generating Reentrant C Code from MATLAB Code

Call Reentrant Code — Multithreaded with Persistent Data


(Windows Only)

In this section...
“MATLAB Code for This Example” on page 30-22
“Provide a Main Function” on page 30-23
“Generate Reentrant C Code” on page 30-25
“Examine the Generated Code” on page 30-25
“Run the Code” on page 30-26

This example requires libraries that are specific to the Microsoft Windows operating
system and, therefore, runs only on Windows platforms. It is a multithreaded example
that uses persistent data. Two threads call the MATLAB function matrix_exp with
different sets of input data.

MATLAB Code for This Example

function [Y,numTimes] = matrix_exp(X) %#codegen


%
% The function matrix_exp computes matrix exponential
% of the input matrix using Taylor series and returns
% the computed output. It also returns the number of
% times this function has been called.
%
persistent count;
if isempty(count)
count = 0;
end
count = count+1;

E = zeros(size(X));
F = eye(size(X));
k = 1;
while norm(E+F-E,1) > 0
E = E + F;
F = X*F/k;
k = k+1;
end
Y = E ;

numTimes = count;

30-22
Call Reentrant Code — Multithreaded with Persistent Data (Windows Only)

Provide a Main Function


To call reentrant code that uses persistent data, provide a main function that:

• Includes the header file matrix_exp.h.


• For each thread, allocates memory for stack data.
• Allocates memory for persistent data, once per application if threads share data, and
once per thread otherwise.
• Calls the matrix_exp_initialize housekeeping function. For more information,
see “Calling Initialize and Terminate Functions” on page 25-7.
• Calls matrix_exp.
• Calls matrix_exp_terminate.
• Frees the memory used for stack and persistent data.

For this example, main.c contains:


#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "matrix_exp.h"
#include "matrix_exp_initialize.h"
#include "matrix_exp_terminate.h"
#include "rtwtypes.h"
#define NUMELEMENTS (160*160)

typedef struct {
real_T in[NUMELEMENTS];
real_T out[NUMELEMENTS];
real_T numTimes;
matrix_expStackData* spillData;
} IODATA;

/*The thread_function calls the matrix_exp function written in MATLAB*/


DWORD WINAPI thread_function(PVOID dummyPtr) {
IODATA *myIOData = (IODATA*)dummyPtr;
matrix_exp_initialize(myIOData->spillData);
matrix_exp(myIOData->spillData, myIOData->in, myIOData->out, &myIOData->numTimes);
printf("Number of times function matrix_exp is called is %g\n",myIOData->numTimes);
matrix_exp_terminate();
return 0;
}

void main() {
HANDLE thread1, thread2;
IODATA data1;
IODATA data2;
int32_T i;

30-23
30 Generating Reentrant C Code from MATLAB Code

/*Initializing data for passing to the 2 threads*/


matrix_expPersistentData* pd1 = (matrix_expPersistentData*)calloc(1,sizeof(matrix_expPersistentData));
matrix_expPersistentData* pd2 = (matrix_expPersistentData*)calloc(1,sizeof(matrix_expPersistentData));
matrix_expStackData* sd1 = (matrix_expStackData*)calloc(1,sizeof(matrix_expStackData));
matrix_expStackData* sd2 = (matrix_expStackData*)calloc(1,sizeof(matrix_expStackData));

sd1->pd = pd1;
sd2->pd = pd2;
data1.spillData = sd1;
data2.spillData = sd2;

for (i=0;i<NUMELEMENTS;i++) {
data1.in[i] = 1;
data1.out[i] = 0;
data2.in[i] = 1.1;
data2.out[i] = 0;
}

data1.numTimes = 0;
data2.numTimes = 0;

/*Initializing the 2 threads and passing required data to the thread functions*/
printf("Starting thread 1...\n");
thread1 = CreateThread(NULL, 0, thread_function, (PVOID) &data1, 0, NULL);
if (thread1 == NULL){
perror( "Thread 1 creation failed.");
exit(EXIT_FAILURE);
}

printf("Starting thread 2...\n");


thread2 = CreateThread(NULL, 0, thread_function, (PVOID) &data2, 0, NULL);
if (thread2 == NULL){
perror( "Thread 2 creation failed.");
exit(EXIT_FAILURE);
}

/*Wait for both the threads to finish execution*/


if (WaitForSingleObject(thread1, INFINITE) != WAIT_OBJECT_0){
perror( "Thread 1 join failed.");
exit(EXIT_FAILURE);
}

if (WaitForSingleObject(thread2, INFINITE) != WAIT_OBJECT_0){


perror( "Thread 2 join failed.");
exit(EXIT_FAILURE);
}

free(sd1);
free(sd2);
free(pd1);
free(pd2);

printf("Finished Execution!\n");
exit(EXIT_SUCCESS);

30-24
Call Reentrant Code — Multithreaded with Persistent Data (Windows Only)

Generate Reentrant C Code


Run the following script at the MATLAB command prompt to generate code.

% This example can only be run on Windows platforms


if ~ispc
error...
('This example requires Windows-specific libraries and can only be run on Windows.');
end

% Setting the options for the Config object


% Create a code gen configuration object
cfg = coder.config('exe');

% Enable reentrant code generation


cfg.MultiInstanceCode = true;

% Compiling
codegen -config cfg main.c -report matrix_exp.m -args ones(160,160)

This script:

• Generates an error message if the example is not running on a Windows platform.


• Creates a code generation configuration object for generation of an executable.
• Enables the MultiInstanceCode option to generate reusable, reentrant code.
• Invokes codegen with the following options:

• -config to pass in the code generation configuration object cfg.


• main.c to include this file in the compilation.
• -report to create a code generation report.
• -args to specify an example input with class, size, and complexity.

Examine the Generated Code


codegen generates a header file matrix_exp_types.h, that defines:

• The matrix_expStackData global structure that contains local variables that are
too large to fit on the stack and a pointer to the matrix_expPersistentData global
structure.
• The matrix_expPersistentData global structure that contains persistent data.

30-25
30 Generating Reentrant C Code from MATLAB Code

/*
* matrix_exp_types.h
*
* Code generation for function 'matrix_exp'
*
*/

#ifndef __MATRIX_EXP_TYPES_H__
#define __MATRIX_EXP_TYPES_H__

/* Include files */
#include "rtwtypes.h"

/* Type Definitions */
#ifndef typedef_matrix_expPersistentData
#define typedef_matrix_expPersistentData

typedef struct {
double count;
} matrix_expPersistentData;

#endif /*typedef_matrix_expPersistentData*/

#ifndef typedef_matrix_expStackData
#define typedef_matrix_expStackData

typedef struct {
struct {
double F[25600];
double Y[25600];
double X[25600];
} f0;

matrix_expPersistentData *pd;
} matrix_expStackData;

#endif /*typedef_matrix_expStackData*/
#endif

/* End of code generation (matrix_exp_types.h) */

Run the Code


Call the code using the command:
system('matrix_exp.exe')
The executable runs and reports completion.

30-26
Call Reentrant Code — Multithreaded with Persistent Data (UNIX Only)

Call Reentrant Code — Multithreaded with Persistent Data (UNIX


Only)

In this section...
“MATLAB Code for This Example” on page 30-27
“Provide a Main Function” on page 30-28
“Generate Reentrant C Code” on page 30-30
“Examine the Generated Code” on page 30-31
“Run the Code” on page 30-32

This example requires POSIX thread (pthread) libraries and, therefore, runs only on
UNIX platforms. It is a multithreaded example that uses persistent data. Two threads
call the MATLAB function matrix_exp with different sets of input data.

MATLAB Code for This Example

function [Y,numTimes] = matrix_exp(X) %#codegen


%
% The function matrix_exp computes matrix exponential
% of the input matrix using Taylor series and returns
% the computed output. It also returns the number of
% times this function has been called.
%

persistent count;
if isempty(count)
count = 0;
end
count = count+1;

E = zeros(size(X));
F = eye(size(X));
k = 1;
while norm(E+F-E,1) > 0
E = E + F;
F = X*F/k;
k = k+1;
end
Y = E ;

numTimes = count;

30-27
30 Generating Reentrant C Code from MATLAB Code

Provide a Main Function


To call reentrant code that uses persistent data, provide a main function that:

• Includes the header file matrix_exp.h.


• For each thread, allocates memory for stack data.
• Allocates memory for persistent data, once per application if threads share data, and
once per thread otherwise.
• Calls the matrix_exp_initialize housekeeping function. For more information,
see “Calling Initialize and Terminate Functions” on page 25-7.
• Calls matrix_exp.
• Calls matrix_exp_terminate.
• Frees the memory used for stack and persistent data.

For this example, main.c contains:


#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "matrix_exp.h"
#include "matrix_exp_initialize.h"
#include "matrix_exp_terminate.h"
#include "rtwtypes.h"
#define NUMELEMENTS (160*160)

typedef struct {
real_T in[NUMELEMENTS];
real_T out[NUMELEMENTS];
real_T numTimes;
matrix_expStackData* spillData;
} IODATA;

/*The thread_function calls the matrix_exp function written in MATLAB*/


void *thread_function(void *dummyPtr) {
IODATA *myIOData = (IODATA*)dummyPtr;
matrix_exp_initialize(myIOData->spillData);
matrix_exp(myIOData->spillData, myIOData->in, myIOData->out, &myIOData>numTimes);
printf("Number of times function matrix_exp is called is %g\n",myIOData->numTimes);
matrix_exp_terminate();
}

int main() {
pthread_t thread1, thread2;
int iret1, iret2;
IODATA data1;
IODATA data2;
int32_T i;

30-28
Call Reentrant Code — Multithreaded with Persistent Data (UNIX Only)

/*Initializing data for passing to the 2 threads*/


matrix_expPersistentData* pd1 =
(matrix_expPersistentData*)calloc(1,sizeof(matrix_expPersistentData));
matrix_expPersistentData* pd2 =
(matrix_expPersistentData*)calloc(1,sizeof(matrix_expPersistentData));
matrix_expStackData* sd1 = (matrix_expStackData*)calloc(1,sizeof(matrix_expStackData));
matrix_expStackData* sd2 = (matrix_expStackData*)calloc(1,sizeof(matrix_expStackData));

sd1->pd = pd1;
sd2->pd = pd2;
data1.spillData = sd1;
data2.spillData = sd2;

for (i=0;i<NUMELEMENTS;i++) {
data1.in[i] = 1;
data1.out[i] = 0;
data2.in[i] = 1.1;
data2.out[i] = 0;
}

data1.numTimes = 0;
data2.numTimes = 0;

/*Initializing the 2 threads and passing required data to the thread functions*/
printf("Starting thread 1...\n");
iret1 = pthread_create(&thread1, NULL, thread_function, (void*) &data1);
if (iret1 != 0){
perror("Thread 1 creation failed.");
exit(EXIT_FAILURE);
}

printf("Starting thread 2...\n");


iret2 = pthread_create(&thread2, NULL, thread_function, (void*) &data2);
if (iret2 != 0){
perror( "Thread 2 creation failed.");
exit(EXIT_FAILURE);
}

/*Wait for both the threads to finish execution*/


iret1 = pthread_join(thread1, NULL);
if (iret1 != 0){
perror( "Thread 1 join failed.");
exit(EXIT_FAILURE);
}

iret2 = pthread_join(thread2, NULL);


if (iret2 != 0){
perror( "Thread 2 join failed.");
exit(EXIT_FAILURE);
}

free(sd1);
free(sd2);
free(pd1);
free(pd2);

30-29
30 Generating Reentrant C Code from MATLAB Code

printf("Finished Execution!\n");
return(0);

Generate Reentrant C Code


To generate code, run the following script at the MATLAB command prompt.
% This example can only be run on Unix platforms
if ~isunix
error('This example requires pthread libraries and can only be run on Unix.');
end

% Setting the options for the Config object

% Specify an ERT target


cfg = coder.config('exe');

% Enable reentrant code generation


cfg.MultiInstanceCode = true;

% Set the post code generation command to be the 'setbuildargs' function


cfg.PostCodeGenCommand = 'setbuildargs(buildInfo)';

% Compiling
codegen -config cfg main.c -report matrix_exp.m -args ones(160,160)

This script:

• Generates an error message if the example is not running on a UNIX platform.


• Creates a code generation configuration object for generation of an executable.
• Enables the MultiInstanceCode option to generate reusable, reentrant code.
• Uses the PostCodeGenCommand option to set the post-code-generation command to
be the setbuildargs function. This function sets the -lpthread flag to specify that
the build include the pthread library.
function setbuildargs(buildInfo)
% The example being compiled requires pthread support.
% The -lpthread flag requests that the pthread library
% be included in the build
linkFlags = {'-lpthread'};
addLinkFlags(buildInfo, linkFlags);

For more information, see “Customize the Post-Code-Generation Build Process” on


page 21-138.
• Invokes codegen with the following options:

30-30
Call Reentrant Code — Multithreaded with Persistent Data (UNIX Only)

• -config to pass in the code generation configuration object cfg.


• main.c to include this file in the compilation.
• -report to create a code generation report.
• -args to specify an example input with class, size, and complexity.

Examine the Generated Code


codegen generates a header file matrix_exp_types.h, which defines:

• The matrix_expStackData global structure that contains local variables that are
too large to fit on the stack and a pointer to the matrix_expPersistentData global
structure.
• The matrix_expPersistentData global structure that contains persistent data.

/*
* matrix_exp_types.h
*
* Code generation for function 'matrix_exp'
*
*/

#ifndef __MATRIX_EXP_TYPES_H__
#define __MATRIX_EXP_TYPES_H__

/* Include files */
#include "rtwtypes.h"

/* Type Definitions */
#ifndef typedef_matrix_expPersistentData
#define typedef_matrix_expPersistentData

typedef struct {
double count;
} matrix_expPersistentData;

#endif /*typedef_matrix_expPersistentData*/

#ifndef typedef_matrix_expStackData
#define typedef_matrix_expStackData

typedef struct {
struct {
double F[25600];
double Y[25600];
double X[25600];
} f0;

30-31
30 Generating Reentrant C Code from MATLAB Code

matrix_expPersistentData *pd;
} matrix_expStackData;

#endif /*typedef_matrix_expStackData*/
#endif

/* End of code generation (matrix_exp_types.h) */

Run the Code


Call the code using the command:
system('./matrix_exp')

30-32
MATLAB® Coder™
Reference

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™ Reference


© 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

Apps — Alphabetical List


1

Function Reference
2

Class Reference
3

Tools — Alphabetical List


4

vii
1

Apps — Alphabetical List


1 Apps — Alphabetical List

MATLAB Coder
Generate C code or MEX function from MATLAB code

Description
The MATLAB Coder app generates C or C++ code from MATLAB® code. You can
generate:

• C or C++ source code, static libraries, dynamically linked libraries, and executables
that you can integrate into existing C or C++ applications outside of MATLAB.
• MEX functions for accelerated versions of your MATLAB functions.

The workflow-based user interface steps you through the code generation process. Using
the app, you can:

• Create a project or open an existing project. The project specifies the input files, entry-
point function input types, and build configuration.
• Review code generation readiness issues, including unsupported functions.
• Check your MATLAB function for run-time issues.
• Fix issues in your MATLAB code using the integrated editor.
• Convert floating-point MATLAB code to fixed-point C code (requires a Fixed-Point
Designer™ license).
• Convert double-precision MATLAB code to single-precision C code (requires a Fixed-
Point Designer license).
• Trace from MATLAB code to generated C or C++ source code through comments.
• See static code metrics (requires an Embedded Coder® license).
• Verify the numerical behavior of generated code using software-in-the-loop and
processor-in-the-loop execution (requires an Embedded Coder license).
• Export project settings in the form of a MATLAB script.
• Access generated files.
• Package generated files as a single zip file for deployment outside of MATLAB.

When the app creates a project, if the Embedded Coder product is installed, the app
enables Embedded Coder features. When Embedded Coder features are enabled, code
generation requires an Embedded Coder license. To disable Embedded Coder features,

1-2
MATLAB Coder

in the project build settings, on the All Settings tab, under Advanced, set Use
Embedded Coder features to No.

Open the MATLAB Coder App


• MATLAB Toolstrip: On the Apps tab, under Code Generation, click the app icon.
• MATLAB command prompt: Enter coder.

Examples
• “C Code Generation Using the MATLAB Coder App”

Programmatic Use
coder

See Also
Apps
Fixed-Point Converter

Functions
codegen

1-3
2

Function Reference
2 Function Reference

codegen
Generate C/C++ code from MATLAB code

Syntax
codegen options files fcn_1 args... fcn_n args
codegen project_name

Description
codegen options files fcn_1 args... fcn_n args translates the MATLAB
functions fcn_1 through fcn_n to a C/C++ static or dynamic library, executable, or MEX
function. Optionally, you can specify custom files to include in the build. codegen
applies the options to functions fcn_1 through fcn_n. It applies args to the preceding
function only (fcn_n). If you specify C++, MATLAB Coder™ wraps the C code into .cpp
files so that you can use a C++ compiler and interface with external C++ applications. It
does not generate C++ classes.

codegen project_name generates output for the MATLAB Coder project


project_name. codegen generates a MEX function, C/C++ static or dynamic library, or
C/C++ executable depending on the project settings that you defined for project_name.

By default, codegen generates files in the folder codegen/target/fcn_name.

target can be:

• mex for MEX functions


• exe for embeddable C/C++ executables
• lib for embeddable C/C++ static libraries
• dll for C/C++ dynamic libraries

fcn_name is the name of the first MATLAB function (alphabetically) at the command
line.

codegen copies the MEX function and executable file to the current working folder or to
the output folder that the -d option specifies.

2-2
codegen

Each time codegen generates the same type of output for the same code or project, it
removes the files from the previous build. If you want to preserve files from a previous
build, before starting another build, copy them to a different location

Input Arguments
args

args applies only to the preceding function, fcn_n.

-args example_inputs Define the size, class, and complexity of all


MATLAB function inputs. Use the values in
example_inputs to define these properties.
example_inputs must be a cell array that
specifies the same number and order of inputs as
the MATLAB function. codegen interprets an
empty cell array with the -args option to mean
that the function takes no inputs. If the function
does have inputs, a compile-time error occurs.

Specify the example inputs immediately after


the function to which they apply.

Use the coder.typeof function to create


example inputs.

fcn_1

fcn_1... fcn_n are the MATLAB entry-point functions from which to generate a MEX
function, C/C++ library, or C/C++ executable code. In most cases, you have only one
function. Make sure that fcn_1... fcn_n are suitable for code generation.

If these MATLAB functions are in files on a path that contains non 7-bit ASCII
characters, such as Japanese characters, it is possible that codegen does not find them.

If you are using the LCC compiler, do not name an entry-point function main.

files

Space-separated list of custom files to include in generated code. You can include the
following types of files:

2-3
2 Function Reference

• C file (.c)
• C++ file (.cpp)
• Header file (.h)
• Object file (.o or .obj)
• Library (.a, .so, or .lib)
• Template makefile (.tmf)

If these files are on a path that contains non 7-bit ASCII characters, such as Japanese
characters, it is possible that codegen does not find them.

options

Choice of compiler options. codegen gives precedence to individual command-line


options over options specified using a configuration object. If command-line options
conflict, the rightmost option prevails.

-c Generate C/C++ code, but do not invoke the


make command.
-config:dll Generate a dynamic C/C++ library using the
default configuration parameters.
-config:exe Generate a static C/C++ executable using the
default configuration parameters.
-config:lib Generate a static C/C++ library using the
default configuration parameters.
-config:mex Generate a MEX function using the default
configuration parameters.
-config:single Generate single-precision MATLAB code using
the default configuration parameters.

Requires a Fixed-Point Designer license.


-config config_object Specify the configuration object that contains the
code generation parameters. config_object is
based on one of the following classes:

• coder.CodeConfig — Parameters for


standalone C/C++ library or executable
generation if no Embedded Coder license is
available.

2-4
codegen

% Configuration object for a dynamic linked library


cfg = coder.config('dll')
% Configuration object for an executable
cfg = coder.config('exe')
% Configuration object for a static standalone library
cfg = coder.config('lib')

• coder.EmbeddedCodeConfig— Parameters
for a standalone C/C++ library or executable
generation if an Embedded Coder license is
available.
% Configuration object for a dynamic linked library
ec_cfg = coder.config('dll')
% Configuration object for an executable
ec_cfg = coder.config('exe')
% Configuration object for a static standalone library
ec_cfg = coder.config('lib')

• coder.MexCodeConfig — Parameters for


MEX code generation.

mex_cfg = coder.config
% or
mex_cfg = coder.config('mex')

2-5
2 Function Reference

-d out_folder Store generated files in the absolute or relative


path specified by out_folder. out_folder
must not contain:

• Spaces, as spaces can lead to code generation


failures in certain operating system
configurations.
• Non 7-bit ASCII characters, such as Japanese
characters,

If the folder specified by out_folder does not


exist, codegen creates it.

If you do not specify the folder location, codegen


generates files in the default folder:
codegen/target/fcn_name.

target can be:

• mex for MEX functions


• exe for embeddable C/C++ executables
• lib for embeddable C/C++ libraries
• dll for C/C++ dynamic libraries

fcn_name is the name of the first MATLAB


function (alphabetically) at the command line.

The function does not support the following


characters in folder names: asterisk (*),
question-mark (?), dollar ($), and pound (#).

Note: Each time codegen generates the same


type of output for the same code, it removes
the files from the previous build. If you want
to preserve files from a previous build, before
starting another build, copy them to a different
location.

2-6
codegen

-doubles2single Generates single-precision MATLAB code using


double2single_cfg_name the settings that the coder.singleConfig
object double2single_cfg_name specifies.
codegen generates files in the folder
codegen/fcn_name/single.

fcn_name is the name of the entry-point


function.

When used with the -config option, also


generates single-precision C/C++ code. codegen
generates the single-precision files in the folder
codegen/target/folder_name

. target can be:

• mex for MEX functions


• exe for embeddable C/C++ executables
• lib for embeddable C/C++ libraries
• dll for C/C++ dynamic libraries

folder_name is the concatenation of fcn_name


and singlesuffix.

singlesuffix is the suffix that


the coder.singleConfig property
OutputFileNameSuffix specifies. The single-
precision files in this folder also have this suffix.

You must have a Fixed-Point Designer license to


use this option.

2-7
2 Function Reference

-float2fixed float2fixed_cfg_name When used with the -config option, generates


fixed-point C/C++ code using the settings that
the floating-point to fixed-point conversion
configuration object float2fixed_cfg_name
specifies.

codegen generates files in the folder


codegen/target/fcn_name_fixpt. target
can be:

• mex for MEX functions


• exe for embeddable C/C++ executables
• lib for embeddable C/C++ libraries
• dll for C/C++ dynamic libraries

fcn_name is the name of the entry-point


function.

When used without the -config option,


generates fixed-point MATLAB code using
the settings that the floating-point to
fixed-point conversion configuration object
named float2fixed_cfg_name specifies.
codegen generates files in the folder
codegen/fcn_name/fixpt.

You must set the TestBenchName property of


float2fixed_cfg_name. For example:

fixptcfg.TestBenchName = 'myadd_test';
specifies that myadd_test is the test file for the
floating-point to fixed-point configuration object
fixptcfg.

You must have a Fixed-Point Designer license to


use this option.

2-8
codegen

-g Specify whether to use the debug option for


the C compiler. If you enable debug mode, the
C compiler disables some optimizations. The
compilation is faster, but the execution is slower.

2-9
2 Function Reference

-globals global_values Specify names and initial values for global


variables in MATLAB files.

global_values is a cell array of global


variable names and initial values. The format of
global_values is:

{g1, init1, g2, init2, ..., gn, initn}

gn is the name of a global variable specified as a


string. initn is the initial value. For example:

-globals {'g', 5}

Alternatively, use this format:


-globals {global_var, {type, initial_value}}

type is a type object. To create the type object,


use coder.typeof. For global cell array
variables, you must use this format.

Before generating code with codegen, initialize


global variables. If you do not provide initial
values for global variables using the -globals
option, codegen checks for the variable in the
MATLAB global workspace. If you do not supply
an initial value, codegen generates an error.

MATLAB Coder and MATLAB each have their


own copies of global data. For consistency,
synchronize their global data whenever the two
interact. If you do not synchronize the data,
their global variables can differ.

To specify a constant value for a global variable,


use coder.Constant. For example:

-globals {'g', coder.Constant(v)}


specifies that g is a global variable with constant
value v.

2-10
codegen

-I include_path Add include_path to the beginning of the code


generation path. When codegen searches for
MATLAB functions and custom C/C++ files, it
searches the code generation path first. It does
not search for classes on the code generation
path. Classes must be on the MATLAB search
path.

Spaces in include_path can lead to code


generation failures in certain operating system
configurations. If the path contains characters
that are not 7-bit ASCII , such as Japanese
characters, it is possible that codegen does not
find files on this path.
-launchreport Generate and open a code generation report.
If you do not specify this option, codegen
generates a report only if error or warning
messages occur or if you specify the -report
option.

2-11
2 Function Reference

-o output_file_name Generate the MEX function, C/C++ library,


or C/C++ executable file with the base name
output_file_name plus an extension:

• .a or .lib for C/C++ static libraries


• .exe or no extension for C/C++ executables
• .dll for C/C++ dynamic libraries on
Microsoft® Windows® systems
• .so for C/C++ dynamic libraries on Linux®
and Macintosh systems
• Platform-dependent extension for generated
MEX functions

output_file_name can be a file name or


include an existing path. output_file_name
must not contain spaces, as spaces can lead to
code generation failures in certain operating
system configurations.

For MEX functions, output_file_name must


be a valid MATLAB function name.

If you do not specify an output file name for


libraries and executables, the base name is
fcn_1. fcn_1 is the name of the first MATLAB
function specified at the command line. For MEX
functions, the base name is fcn_1_mex. You can
run the original MATLAB function and the MEX
function and compare the results.

2-12
codegen

-O optimization_option Optimize generated code, based on the value of


optimization_option:

• enable:inline — Enable function inlining


• disable:inline — Disable function
inlining
• enable:openmp — Use OpenMP library if
available. Using the OpenMP library, the
MEX functions or C/C++ code that codegen
generates for parfor-loops can run on
multiple threads.
• disable:openmp — Disable OpenMP
library. With OpenMP disabled, codegen
treats parfor-loops as for-loops and
generates a MEX function or C/C++ code that
runs on a single thread.

Specify-O at the command line once for each


optimization.

If not specified, codegen uses inlining and


OpenMP for optimization.
-report Generate a code generation report. If you do not
specify this option, codegen generates a report
only if error or warning messages occur or if you
specify the -launchreport option.

If you have an Embedded Coder license, this


option also enables the Code Replacements and
Static Code Metrics reports.
-singleC Generate single-precision C/C++ code.

You must have a Fixed-Point Designer license to


use this option.
-v Enable verbose mode to show build steps. Use
when generating libraries or executables only.
-? Display help for codegen command.

2-13
2 Function Reference

project_name

Name of the MATLAB Coder project that you want codegen to build. The project name
must not contain spaces.

Examples
Generate a MEX function from a MATLAB function that is suitable for code generation.

1 Write a MATLAB function, coderand, that generates a random scalar value from
the standard uniform distribution on the open interval (0,1).
function r = coderand() %#codegen
% The directive %#codegen indicates that the function
% is intended for code generation
r = rand();
2 Generate and run the MEX function. By default, codegen names the generated
MEX function coderand_mex.
codegen coderand
coderand_mex

Generate C executable files from a MATLAB function that is suitable for code generation.
Specify the main C function as a configuration parameter.

1 Write a MATLAB function, coderand, that generates a random scalar value from
the standard uniform distribution on the open interval (0,1).
function r = coderand() %#codegen
r = rand();
2 Write a main C function, c:\myfiles\main.c, that calls coderand.
/*
** main.c
*/
#include <stdio.h>
#include <stdlib.h>
#include "coderand.h"
#include "coderand_initialize.h"
#include "coderand_terminate.h"
int main()
{

2-14
codegen

coderand_initialize();

printf("coderand=%g\n", coderand());

coderand_terminate();

return 0;
}
3 Configure your code generation parameters to include the main C function, then
generate the C executable.

cfg = coder.config('exe')
cfg.CustomSource = 'main.c'
cfg.CustomInclude = 'c:\myfiles'
codegen -config cfg coderand

codegen generates a C executable, coderand.exe, in the current folder, and


supporting files in the default folder, codegen/exe/coderand.

This example shows how to specify a main function as a parameter in the


configuration object coder.CodeConfig. Alternatively, you can specify the file
containing main() separately at the command line. You can use a source, object, or
library file.

Generate C library files in a custom folder from a MATLAB function with inputs of
different classes and sizes. The first input is a 1-by-4 vector of unsigned 16-bit integers.
The second input is a double-precision scalar.

1 Write a MATLAB function, mcadd, that returns the sum of two values.

function y = mcadd(u,v) %#codegen


y = u + v;
2 Generate the C library files in a custom folder mcaddlib using the -config:lib
option.

codegen -d mcaddlib -config:lib mcadd -args {zeros(1,4,'uint16'),0}

Generate C library files from a MATLAB function that takes a fixed-point input.

1 Write a MATLAB language function, mcsqrtfi, that computes the square root of a
fixed-point input.

function y = mcsqrtfi(x) %#codegen

2-15
2 Function Reference

y = sqrt(x);
2 Define numerictype and fimath properties for the fixed-point input x and generate
C library code for mcsqrtfi using the -config:lib option.

T = numerictype('WordLength',32, ...
'FractionLength',23, ...
'Signed',true)
F = fimath('SumMode','SpecifyPrecision', ...
'SumWordLength',32, ...
'SumFractionLength',23, ...
'ProductMode','SpecifyPrecision', ...
'ProductWordLength',32, ...
'ProductFractionLength',23)
% Define a fixed-point variable with these
% numerictype and fimath properties
myfiprops = {fi(4.0,T,F)}
codegen -config:lib mcsqrtfi -args myfiprops
codegen generates C library and supporting files in the default folder, codegen/
lib/mcsqrtfi.

Specify global data at the command line.

1 Write a MATLAB function, use_globals, that takes one input parameter u and
uses two global variables AR and B.

function y = use_globals(u)
%#codegen
% Turn off inlining to make
% generated code easier to read
coder.inline('never');
global AR;
global B;
AR(1) = u(1) + B(1);
y = AR * 2;
2 Generate a MEX function. By default, codegen generates a MEX function named
use_globals_mex in the current folder. Specify the properties of the global
variables at the command line by using the -globals option. Specify that input u is
a real, scalar, double, by using the -args option.

codegen -globals {'AR', ones(4), 'B', [1 2 3 4]} ...


use_globals -args {0}

2-16
codegen

Alternatively, you can initialize the global data in the MATLAB workspace. At the
MATLAB prompt, enter:

global AR B;
AR = ones(4);
B=[1 2 3];
Compile the function to generate a MEX file named use_globalsx.

codegen use_globals -args {0}

Generate output for a MATLAB Coder project, test_foo.prj, that includes one file,
foo.m, and has it output type set to C/C++ Static Library.

codegen test_foo.prj

codegen generates a C library, foo, in the codegen\lib\foo folder.

Generate a MEX function for a function, displayState, that has an input parameter
that is an enumerated type.

1 Write a function, displayState, that 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. It 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
2 Define an enumeration LEDColor. On the MATLAB path, create a file named
'LEDColor' containing:

classdef LEDcolor < int32


enumeration
GREEN(1),
RED(2),
end
end
3 Create a coder.EnumType object using a value from an existing MATLAB
enumeration.

2-17
2 Function Reference

a Define an enumeration sysMode. On the MATLAB path, create a file named


'sysMode' containing:
classdef sysMode < int32
enumeration
OFF(0)
ON(1)
end
end
b Create a coder.EnumType object from this enumeration.
t = coder.typeof(sysMode.OFF);
4 Generate a MEX function for displayState.
codegen displayState -args {t}

Convert floating-point MATLAB code to fixed-point C code

This example requires a Fixed-Point Designer license.

1 Write a MATLAB function, myadd, that returns the sum of two values.
function y = myadd(u,v) %#codegen
y = u + v;
end
2 Write a MATLAB function, myadd_test, to test myadd.
function y = myadd_test %#codegen
y = myadd(10,20);
end
3 Create a coder.FixptConfig object, fixptcfg, with default settings.

fixptcfg = coder.config('fixpt');
4 Set the test bench name.
fixptcfg.TestBenchName = 'myadd_test';
5 Create a code generation configuration object to generate a standalone C static
library.
cfg = coder.config('lib');
6 Generate the code using the -float2fixed option.

2-18
codegen

codegen -float2fixed fixptcfg -config cfg myadd

Convert double-precision MATLAB code to single-precision C code.

This example requires a Fixed-Point Designer license.

Suppose that myfunction takes two double scalar inputs. Use the -singleC option to
generate single-precision C/C++ code.
codegen -singleC myfunction -args {1 2}

Alternatives
Use the coder function to open the MATLAB Coder app and create a MATLAB Coder
project. The app provides a user interface that facilitates adding MATLAB files, defining
input parameters, and specifying build parameters.

More About
• “Code Generation”
• “Primary Function Input Specification”
• “Specify Cell Array Inputs at the Command Line”
• “Specify Global Cell Arrays at the Command Line”
• “Specify a Language for Code Generation”
• “Paths and File Infrastructure Setup”
• “Generate Code for Global Data”
• “Synchronizing Global Data with MATLAB”
• “Generate Code for Multiple Entry-Point Functions”
• “Convert MATLAB Code to Fixed-Point C Code”
• “Generate Single-Precision C Code at the Command Line”
• “Generate Single-Precision MATLAB Code”
• “Control Compilation of parfor-Loops”

See Also
coder | coder.typeof | coder.EnumType | parfor | fimath | numerictype | mex
| fi | coder.runTest | coder.FixptConfig

2-19
2 Function Reference

Introduced in R2011a

2-20
coder

coder
Open MATLAB Coder app

Syntax
coder
coder projectname
coder -open projectname
coder -build projectname
coder -new projectname
coder -ecoder false -new projectname
coder -tocode projectname -script scriptname
coder -tocode projectname

Description
coder opens the MATLAB Coder app. To create a project, on the Select Source Files
page, provide the entry-point file names. The app creates a project with a default name
that is the name of the first entry-point file. To open an existing project, on the app

toolbar, click , and then click Open existing project.

If the Embedded Coder product is installed, when the app creates a project, it enables
Embedded Coder features. When Embedded Coder features are enabled, code generation
requires an Embedded Coder license. To disable Embedded Coder features, in the project
build settings, on the All Settings tab, under Advanced, set Use Embedded Coder
features to No.

coder projectname opens the MATLAB Coder app using the existing project named
projectname.prj.

coder -open projectname opens the MATLAB Coder app using the existing project
named projectname.prj.

coder -build projectname builds the existing project named projectname.prj.

coder -new projectname opens the MATLAB Coder app creating a project named
projectname.prj. If the Embedded Coder product is installed, the app creates the

2-21
2 Function Reference

project with Embedded Coder features enabled. To disable these features, in the project
build settings, on the All Settings tab, under Advanced, set Use Embedded Coder
features to No.

coder -ecoder false -new projectname opens the MATLAB Coder app creating
a project named projectname.prj. The app creates the project with Embedded Coder
features disabled even if the Embedded Coder product is installed.

coder -tocode projectname -script scriptname converts the existing project


named projectname.prj to the equivalent script of MATLAB commands. The script is
named scriptname.

• If scriptname exists, coder overwrites it.


• The script reproduces the project build configuration in a configuration object and
builds the project. The script:

• Creates a configuration object named cfg.


• Defines the variable ARGS for function input types.
• Defines the variable GLOBALS for global data initial values.
• Runs the codegen command. When you run the script, the entry-point functions
that are arguments to codegen must be on the search path.
• cfg, ARGS, and GLOBALS appear in the base workspace only after you run the script.

If the project includes automated fixed-point conversion, coder generates two scripts:

• A script scriptname that 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 to a
fixed-point C function.
• A script whose file name is a concatenation of the name specified by scriptname and
the generated fixed-point file name suffix specified by the project file. If scriptname
specifies a file extension, the script file name includes the file extension. For example,
if scriptname is myscript.m and the suffix is the default value _fixpt, the script
name is myscript_fixpt.m.

This script 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.

2-22
coder

• Run the codegen command to convert the floating-point MATLAB function to a


fixed-point MATLAB function.

For a project that includes fixed-point conversion, before converting the project to scripts,
complete the Test Numerics step of the fixed-point conversion process.

coder -tocode projectname converts the existing project named


projectname.prj to the equivalent script of MATLAB commands. It writes the script
to the Command Window.

Examples
Open an existing MATLAB Coder project

Open the MATLAB Coder app using the existing MATLAB Coder project named
my_coder_project.

coder -open my_coder_project

Build a MATLAB Coder project

Build the MATLAB Coder project named my_coder_project.

coder -build my_coder_project

Create a MATLAB Coder project

Open the MATLAB Coder app and create a project named my_coder_project.

coder -new my_coder_project

Convert a MATLAB Coder project to a MATLAB script

Convert the MATLAB Coder project named my_coder_project.prj to the MATLAB


script named myscript.m.

coder -tocode my_coder_project -script my_script.m

• “C Code Generation Using the MATLAB Coder App”


• “Convert MATLAB Coder Project to MATLAB Script”
• “Convert Fixed-Point Conversion Project to MATLAB Scripts”

2-23
2 Function Reference

• “Convert MATLAB Code to Fixed-Point C Code”

Input Arguments
projectname — Name of MATLAB Coder project
string

Name of MATLAB Coder project that you want to create, open, or build. The project
name must not contain spaces.

scriptname — Name of script file


string

Name of script that you want to create when using the -tocode option with the -
script option. The script name must not contain spaces.

Alternatives
• On the Apps tab, in the Code Generation section, click MATLAB Coder.
• Use the codegen function to generate code at the command line.

More About
Tips

• If you are sharing an Embedded Coder license, use coder -ecoder false -new
projectname to create a project that does not require this license. If the Embedded
Coder product is installed, the app creates the project with Embedded Coder features
disabled. When these features are disabled, code generation does not require an
Embedded Coder license. To enable Embedded Coder features, in the project build
settings, on the All Settings tab, under Advanced, set Use Embedded Coder
features to Yes.
• Creating a project or opening an existing project causes other MATLAB Coder or
Fixed-Point Converter projects to close.
• If your installation does not include the Embedded Coder product, the Embedded
Coder settings do not show. However, values for these settings are saved in the

2-24
coder

project file. If you open the project in an installation that includes the Embedded
Coder product, you see these settings.
• A Fixed-Point Converter project opens in the Fixed-Point Converter app. To convert
the project to a MATLAB Coder project, in the Fixed-Point Converter app:

1
Click and select Reopen project as.
2 Select MATLAB Coder.

See Also
codegen | MATLAB Coder

Introduced in R2011a

2-25
2 Function Reference

coder.allowpcode
Package: coder

Control code generation from protected MATLAB files

Syntax
coder.allowpcode('plain')

Description
coder.allowpcode('plain') allows you to generate protected MATLAB code (P-code)
that you can then compile into optimized MEX functions or embeddable C/C++ code. This
function does not obfuscate the generated MEX functions or embeddable C/C++ code.

With this capability, you can distribute algorithms as protected P-files that provide
code generation optimizations, providing intellectual property protection for your source
MATLAB code.

Call this function in the top-level function before control-flow statements, such as if,
while, switch, and function calls.

MATLAB functions can call P-code. When the .m and .p versions of a file exist in the
same folder, the P-file takes precedence.

coder.allowpcode is ignored outside of code generation.

Examples
Generate optimized embeddable code from protected MATLAB code:

1 Write an function p_abs that returns the absolute value of its input:

function out = p_abs(in) %#codegen


% The directive %#codegen indicates that the function
% is intended for code generation

2-26
coder.allowpcode

coder.allowpcode('plain');
out = abs(in);
2 Generate protected P-code. At the MATLAB prompt, enter:
pcode p_abs
The P-file, p_abs.p, appears in the current folder.
3 Generate a MEX function for p_abs.p, using the -args option to specify the size,
class, and complexity of the input parameter (requires a MATLAB Coder license). At
the MATLAB prompt, enter:
codegen p_abs -args { int32(0) }
codegen generates a MEX function in the current folder.
4 Generate embeddable C code for p_abs.p (requires a MATLAB Coder license). At
the MATLAB prompt, enter:
codegen p_abs -config:lib -args { int32(0) };
codegen generates C library code in the codegen\lib\p_abs folder.

More About
• “Compilation Directive %#codegen”

See Also
pcode | codegen

Introduced in R2011a

2-27
2 Function Reference

coder.approximation
Create function replacement configuration object

Syntax
q = coder.approximation(function_name)
q = coder.approximation('Function',function_name,Name,Value)

Description
q = coder.approximation(function_name) creates a function replacement
configuration object for use during code generation or fixed-point conversion. The
configuration object specifies how to create a lookup table approximation for the
MATLAB function specified by function_name. To associate this approximation
with a coder.FixptConfig object for use with thecodegen function, use the
coder.FixptConfig configuration object addApproximation method.

Use this syntax only for the functions that coder.approximation can replace
automatically. These functions are listed in the function_name argument description.

q = coder.approximation('Function',function_name,Name,Value) creates
a function replacement configuration object using additional options specified by one or
more name-value pair arguments.

Examples
Replace log Function with Default Lookup Table
Create a function replacement configuration object using the default settings. The
resulting lookup table in the generated code uses 1000 points.
logAppx = coder.approximation('log');

Replace log Function with Uniform Lookup Table


Create a function replacement configuration object. Specify the input range and prefix to
add to the replacement function name. The resulting lookup table in the generated code
uses 1000 points.

2-28
coder.approximation

logAppx = coder.approximation('Function','log','InputRange',[0.1,1000],...
'FunctionNamePrefix','log_replace_');

Replace log Function with Optimized Lookup Table

Create a function replacement configuration object using the 'OptimizeLUTSize'


option to specify to replace the log function with an optimized lookup table. The
resulting lookup table in the generated code uses less than the default number of points.

logAppx = coder.approximation('Function','log','OptimizeLUTSize', true,...


'InputRange',[0.1,1000],'InterpolationDegree',1,'ErrorThreshold',1e-3,...
'FunctionNamePrefix','log_optim_','OptimizeIterations',25);

Replace Custom Function with Optimized Lookup Table

Create a function replacement configuration object that specifies to replace the custom
function, saturateExp, with an optimized lookup table.

Create a custom function, saturateExp.

saturateExp = @(x) 1/(1+exp(-x));

Create a function replacement configuration object that specifies to replace the


saturateExp function with an optimized lookup table. Because the saturateExp
function is not listed as a function for which coder.approximation can generate an
approximation automatically, you must specify the CandidateFunction property.

saturateExp = @(x) 1/(1+exp(-x));


custAppx = coder.approximation('Function','saturateExp',...
'CandidateFunction', saturateExp,...
'NumberOfPoints',50,'InputRange',[0,10]);

• “Replace the exp Function with a Lookup Table”


• “Replace a Custom Function with a Lookup Table”

Input Arguments
function_name — Name of the function to replace
'acos' | 'acosd' | 'acosh' | 'acoth' | 'asin' | 'asind' | 'asinh' |
'atan' | 'atand' | 'atanh' | 'cos' | 'cosd' | 'cosh' | 'erf ' | 'erfc'

2-29
2 Function Reference

| 'exp' | 'log' | 'normcdf' | 'reallog' | 'realsqrt' | 'reciprocal' |


'rsqrt' | 'sin' | 'sinc' | 'sind' | 'sinh' | 'sqrt' | 'tan' | 'tand'

Name of function to replace, specified as a string. The function must be one of the listed
functions.
Example: 'sqrt'
Data Types: char

Name-Value Pair Arguments


Specify optional comma-separated pairs of Name,Value arguments. Name is the
argument name and Value is the corresponding value. Name must appear inside single
quotes (' '). You can specify several name and value pair arguments in any order as
Name1,Value1,...,NameN,ValueN.
Example: 'Function', 'log'

'Architecture' — Architecture of lookup table approximation


'LookupTable' (default) | 'Flat'

Architecture of the lookup table approximation, specified as the comma-separated


pair consisting of 'Architecture' and a string. Use this argument when you want
to specify the architecture for the lookup table. The Flat architecture does not use
interpolation.
Data Types: char

'CandidateFunction' — Function handle of the replacement function


function handle | string

Function handle of the replacement function, specified as the comma-separated pair


consisting of 'CandidateFunction' and a function handle or string referring to
a function handle. Use this argument when the function that you want to replace is
not listed under function_name. Specify the function handle or string referring to a
function handle of the function that you want to replace. You can define the function in a
file or as an anonymous function.

If you do not specify a candidate function, then the function you chose to replace using
the Function property is set as the CandidateFunction.
Example: 'CandidateFunction', @(x) (1./(1+x))

2-30
coder.approximation

Data Types: function_handle | char

'ErrorThreshold' — Error threshold value used to calculate optimal lookup table size
0.001 (default) | nonnegative scalar

Error threshold value used to calculate optimal lookup table size, specified as the
comma-separated pair consisting of 'ErrorThreshold' and a nonnegative scalar. If
'OptimizeLUTSize' is true, this argument is required.

'Function' — Name of function to replace with a lookup table approximation


function_name

Name of function to replace with a lookup table approximation, specified as the comma-
separated pair consisting of 'Function' and a string. The function must be continuous
and stateless. If you specify one of the functions that is listed under function_name,
the conversion process automatically provides a replacement function. Otherwise, you
must also specify the 'CandidateFunction' argument for the function that you want
to replace.

Example: 'Function','log'
Example: 'Function', 'my_log',‘CandidateFunction’,@my_log
Data Types: char

'FunctionNamePrefix' — Prefix for generated fixed-point function names


'replacement_' (default) | string

Prefix for generated fixed-point function names, specified as the comma-separated pair
consisting of 'FunctionNamePrefix' and a string. The name of a generated function
consists of this prefix, followed by the original MATLAB function name.
Example: ‘log_replace_’

'InputRange' — Range over which to replace the function


[ ] (default) | 2x1 row vector | 2xN matrix

Range over which to replace the function, specified as the comma-separated pair
consisting of 'InputRange' and a 2-by-1 row vector or a 2-by-N matrix.
Example: [-1 1]

'InterpolationDegree' — Interpolation degree


1 (default) | 0 | 2 | 3

2-31
2 Function Reference

Interpolation degree, specified as the comma-separated pair consisting of


'InterpolationDegree' and1 (linear), 0 (none), 2 (quadratic), or 3 (cubic).

'NumberOfPoints' — Number of points in lookup table


1000 (default) | positive integer

Number of points in lookup table, specified as the comma-separated pair consisting of


'NumberOfPoints' and a positive integer.

'OptimizeIterations' — Number of iterations


25 (default) | positive integer

Number of iterations to run when optimizing the size of the lookup table, specified as the
comma-separated pair consisting of 'OptimizeIterations' and a positive integer.

'OptimizeLUTSize' — Optimize lookup table size


false (default) | true

Optimize lookup table size, specified as the comma-separated pair consisting of


'OptimizeLUTSize' and a logical value. Setting this property to true generates an
area-optimal lookup table, that is, the lookup table with the minimum possible number of
points. This lookup table is optimized for size, but might not be speed efficient.

'PipelinedArchitecture' — Option to enable pipelining


false (default) | true

Option to enable pipelining, specified as the comma-separated pair consisting of


'PipelinedArchitecture' and a logical value.

Output Arguments
q — Function replacement configuration object, returned as a
coder.mathfcngenerator.LookupTable or a coder.mathfcngenerator.Flat
configuration object
coder.mathfcngenerator.LookupTable configuration object |
coder.mathfcngenerator.Flat configuration object

Function replacement configuration object. Use the coder.FixptConfig configuration


object addApproximation method to associate this configuration object with a
coder.FixptConfig object. Then use the codegen function -float2fixed option with
coder.FixptConfig to convert floating-point MATLAB code to fixed-point code.

2-32
coder.approximation

Property Default Value


Auto-replace function ''
InputRange []
FunctionNamePrefix 'replacement_'
Architecture LookupTable (read only)
NumberOfPoints 1000
InterpolationDegree 1
ErrorThreshold 0.001
OptimizeLUTSize false
OptimizeIterations 25

More About
• “Replacing Functions Using Lookup Table Approximations”

See Also
Classes
coder.FixptConfig

Functions
codegen

2-33
2 Function Reference

coder.ceval
Package: coder

Call external C/C++ function

Syntax
coder.ceval('cfun_name')
coder.ceval('cfun_name', cfun_arguments)
cfun_return = coder.ceval('cfun_name')
cfun_return = coder.ceval('cfun_name', cfun_arguments)
coder.ceval('-global','cfun_name',cfun_arguments)
cfun_return=coder.ceval('-global','cfun_name',cfun_arguments)

Description
coder.ceval('cfun_name') executes the external C/C++ function specified by the
quoted string cfun_name. Define cfun_name in an external C/C++ source file or library.

coder.ceval('cfun_name', cfun_arguments) executes cfun_name with


arguments cfun_arguments. cfun_arguments is a comma-separated list of input
arguments in the order that cfun_name requires.

cfun_return = coder.ceval('cfun_name') executes cfun_name and returns a


single scalar value, cfun_return, corresponding to the value that the C/C++ function
returns in the return statement. To be consistent with C/C++, coder.ceval can return
only a scalar value; it cannot return an array.

cfun_return = coder.ceval('cfun_name', cfun_arguments) executes


cfun_name with arguments cfun_arguments and returns cfun_return.

coder.ceval('-global','cfun_name',cfun_arguments)

cfun_return=coder.ceval('-global','cfun_name',cfun_arguments)

For code generation, you must specify the type, size, and complexity data type of return
values and output arguments before calling coder.ceval.

2-34
coder.ceval

By default, coder.ceval passes arguments by value to the C/C++ function whenever


C/C++ supports passing arguments by value. To make coder.ceval pass arguments
by reference, use the constructs coder.ref, coder.rref, and coder.wref. If C/C
++ does not support passing arguments by value, for example, if the argument is an
array, coder.ceval passes arguments by reference. In this case, if you do not use the
coder.ref, coder.rref, and coder.wref constructs, a copy of the argument might
appear in the generated code to enforce MATLAB semantics for arrays.

If you pass a global variable by reference using coder.ref, coder.rref or


coder.wref, and the custom C code saves the address of this global variable, use
the -global flag to synchronize for the variables passed to the custom C code.
Synchronization occurs before and after calls to the custom code. If you do not
synchronize global variables under these circumstances and the custom C code saves the
address and accesses it again later, the value of the variable might be out of date.

Note: The -global flag does not apply for MATLAB Function blocks.

You cannot use coder.ceval on functions that you declare extrinsic with
coder.extrinsic.

Use coder.ceval only in MATLAB for code generation. coder.ceval generates an


error in uncompiled MATLAB code. Use coder.target to determine if the MATLAB
function is executing in MATLAB. If it is, do not use coder.ceval to call the C/C++
function. Instead, call the MATLAB version of the C/C++ function.

When the LCC compiler creates a library, it adds a leading underscore to the library
function names. If the compiler for the library was LCC and your code generation
compiler is not LCC, you must add the leading underscore to the function name in a
coder.ceval call. For example, coder.ceval('_mylibfun'). If the compiler for
a library was not LCC, you cannot use LCC to generate code from MATLAB code that
calls functions from that library. Those library function names do not have the leading
underscore that the LCC compiler requires.

Examples
Call a C function foo(u) from a MATLAB function from which you intend to generate C
code:

2-35
2 Function Reference

1 Create a C header file foo.h for a function foo that takes two input parameters of
type double and returns a value of type double.

#ifdef MATLAB_MEX_FILE
#include <tmwtypes.h>
#else
#include "rtwtypes.h"
#endif

double foo(double in1, double in2);


2 Write the C function foo.c.

#include <stdio.h>
#include <stdlib.h>
#include "foo.h"

double foo(double in1, double in2)


{
return in1 + in2;
}
3 Write a function callfoo that calls foo using coder.ceval.

function y = callfoo %#codegen


y = 0.0;
if coder.target('MATLAB')
% Executing in MATLAB, call MATLAB equivalent of
% C function foo
y = 10 + 20;
else
% Executing in generated code, call C function foo
y = coder.ceval('foo', 10, 20);
end
end
4 Generate C library code for function callfoo, passing foo.c and foo.h as
parameters to include this custom C function in the generated code.

codegen -config:lib callfoo foo.c foo.h


codegen generates C code in the codegen\lib\callfoo subfolder.

double callfoo(void)
{
/* Executing in generated code, call C function foo */
return foo(10.0, 20.0);

2-36
coder.ceval

In this case, you have not specified the type of the input arguments, that is, the
type of the constants 10 and 20. Therefore, the arguments are implicitly of double-
precision, floating-point type by default, because the default type for constants in
MATLAB is double.

Call a C library function from MATLAB code:

1 Write a MATLAB function absval.

function y = absval(u) %#codegen


y = abs(u);
2 Generate the C library for absval.m, using the -args option to specify the size,
type, and complexity of the input parameter.

codegen -config:lib absval -args {0.0}


codegen creates the library absval.lib and header file absval.h in the folder /
codegen/lib/absval. It also generates the functions absval_initialize and
absval_terminate in the same folder.
3 Write a MATLAB function to call the generated C library functions using
coder.ceval.

function y = callabsval %#codegen


y = -2.75;
% Check the target. Do not use coder.ceval if callabsval is
% executing in MATLAB
if coder.target('MATLAB')
% Executing in MATLAB, call function absval
y = absval(y);
else
% Executing in the generated code.
% Call the initialize function before calling the
% C function for the first time
coder.ceval('absval_initialize');

% Call the generated C library function absval


y = coder.ceval('absval',y);

% Call the terminate function after


% calling the C function for the last time
coder.ceval('absval_terminate');
end

2-37
2 Function Reference

4 Convert the code in callabsval.m to a MEX function so you can call the C library
function absval directly from MATLAB.

codegen -config:mex callabsval codegen/lib/absval/absval.lib...


codegen/lib/absval/absval.h
5 Call the C library by running the MEX function from MATLAB.
callabsval_mex

More About
• “Compilation Directive %#codegen”
• “External Code Integration”
• “Data Definition Basics”

See Also
coder.ref | coder.rref | coder.wref | coder.target | codegen | | | |
coder.extrinsic | coder.opaque | | |

Introduced in R2011a

2-38
coder.cinclude

coder.cinclude
Include header file in generated code

Syntax
coder.cinclude(AppHeaderFile)
coder.cinclude(SysHeaderFile)

Description
coder.cinclude(AppHeaderFile) includes an application header file in generated
code using this format:

#include "HeaderFile"

coder.cinclude(SysHeaderFile) includes a system header file in generated code


using this format:

#include <HeaderFile>

Examples
Include Header File Conditionally in Generated Code

Generate code from a MATLAB function that calls an external C function to double its
input. The MATLAB function uses coder.cinclude to include an application header
file in generated C code running on a target machine, but not when the function runs in
the MATLAB environment.

Write a C function myMult2.c that doubles its input. Save it in a subfolder mycfiles.

#include "myMult2.h"
double myMult2(double u)
{
return 2 * u;

2-39
2 Function Reference

Write the application header file myMult2.h. Save it in the subfolder mycfiles.

#if !defined(MYMULT2)
#define MYMULT2
extern double myMult2(double);
#endif

Write a MATLAB function that conditionally includes the application header file and
calls the external C function.
function y = myfunc
%#codegen
y = 21;
if ~coder.target('MATLAB')
% Running in generated code
coder.cinclude('myMult2.h');
y = coder.ceval('myMult2', y);
else
% Running in MATLAB
y = y * 2;
end
end

Compile the MATLAB function. Use the -I option to specify the path to the external
header and C files.
codegen -config:lib myfunc -I mycfiles

Here is the generated C code:


/* Include files */
#include "rt_nonfinite.h"
#include "myfunc.h"
#include "myMult2.h"

/* Function Definitions */
double myfunc(void)
{
/* Running in generated code */
return myMult2(21.0);
}

/* End of code generation (myfunc.c) */

2-40
coder.cinclude

Besides the files that coder.cinclude specifies, codegen automatically includes the
following files:

• Header file that defines the prototype for your entry-point function (in this case,
myMult2.h)
• rt_nonfinite.h (if you do not specify SupportNonFinite=false using
coder.config when you compile the entry-point function).

Input Arguments
AppHeaderFile — Name of application header file
string

Name of an application header file, specified as a string. The header file must be located
in the include path that you specify with the -I option when generating code using
codegen.
Example: coder.cinclude('myheader.h')
Data Types: char

SysHeaderFile — Name of system header file


string

Name of a system header file, specified as a string enclosed in angle brackets < >. The
header file must come from a standard list of system directories or from the include path
that you specify with the -I option when generating code using codegen.
Example: coder.cinclude('<stdio.h>')
Data Types: char

Limitations
• Do not call coder.cinclude inside run-time conditional constructs such as
if statements, switch statements, while-loops, and for-loops. However, you
can call coder.cinclude inside compile-time conditional statements, such as
coder.target. For example:

...

2-41
2 Function Reference

if ~coder.target('MATLAB')
coder.cinclude('foo.h');
coder.ceval('foo');
end
...

More About
Tips

• Call coder.cinclude before calling an external C/C++ function using coder.ceval


to include in the generated code the header files required for the external function.
• Localize use of coder.cinclude at the call sites where you want to include each
header file. Do not place all of your coder.cinclude calls in the top-level (entry-
point) function unless you want to include the specified header files in every build.

See Also
codegen | coder.ceval | coder.config | coder.target

Introduced in R2013a

2-42
coder.config

coder.config
Package: coder

Create MATLAB Coder code generation configuration objects

Syntax
config_obj = coder.config
config_obj = coder.config('mex')
config_obj = coder.config('lib')
config_obj = coder.config('dll')
config_obj = coder.config('exe')
config_obj = coder.config(c_output_type,'ecoder',false)
config_obj = coder.config(c_output_type,'ecoder',true)
config_obj = coder.config('fixpt')
config_obj = coder.config('single')

Description
config_obj = coder.config creates a coder.MexCodeConfig code generation
configuration object for use with codegen when generating a MEX function.

config_obj = coder.config('mex') creates a coder.MexCodeConfig code


generation configuration object for use with codegen when generating a MEX function.

config_obj = coder.config('lib') creates a code generation configuration object


for use with codegen when generating a C/C++ static library. If the Embedded Coder
product is installed, it creates a coder.EmbeddedCodeConfig object. Otherwise, it
creates a coder.CodeConfig configuration object.

config_obj = coder.config('dll') creates a code generation configuration object


for use with codegen when generating a C/C++ dynamic library. If the Embedded Coder
product is installed, it creates a coder.EmbeddedCodeConfig object. Otherwise, it
creates a coder.CodeConfig configuration object.

config_obj = coder.config('exe') creates a code generation configuration object


for use with codegen when generating a C/C++ executable. If the Embedded Coder

2-43
2 Function Reference

product is installed, it creates a coder.EmbeddedCodeConfig object. Otherwise, it


creates a coder.CodeConfig configuration object.

config_obj = coder.config(c_output_type,'ecoder',false) creates a


coder.CodeConfig configuration object to generate c_output_type even if the
Embedded Coder product is installed. c_output_type is 'lib', 'dll', or 'exe'.

config_obj = coder.config(c_output_type,'ecoder',true) creates a


coder.EmbeddedCodeConfig configuration object to generate c_output_type
even if the Embedded Coder product is not installed. However, code generation
using a coder.EmbeddedCodeConfig object requires an Embedded Coder license.
c_output_type is 'lib', 'dll', or 'exe'.

config_obj = coder.config('fixpt') creates a coder.FixptConfig


configuration object for use with codegen when generating fixed-point C/C++ code from
floating-point MATLAB code. Creation of a coder.FixptConfig code configuration
object requires the Fixed-Point Designer product.

config_obj = coder.config('single') creates a coder.SingleConfig


configuration object for use with codegen when generating single-precision MATLAB
code from double-precision MATLAB code. Creation of a coder.SingleConfig code
configuration object requires the Fixed-Point Designer product.

Examples
Generate a MEX function from a MATLAB function that is suitable for code generation
and enable a code generation report.

1 Write a MATLAB function, coderand, that generates a random scalar value from
the standard uniform distribution on the open interval (0,1).

function r = coderand() %#codegen


% The directive %#codegen declares that the function
% is intended for code generation
r = rand();
2 Create a code generation configuration object to generate a MEX function.

cfg = coder.config % or cfg = coder.config('mex')


3 Enable the code generation report.

2-44
coder.config

cfg.GenerateReport = true;
4 Generate a MEX function in the current folder specifying the configuration object
using the -config option.

% Generate a MEX function and code generation report


codegen -config cfg coderand

Create a code generation configuration object to generate a standalone C static library.

cfg = coder.config('lib')
% Returns a coder.EmbeddedCodeConfig object if the Embedded
% Coder product is installed.
% Otherwise, returns a coder.CodeConfig object.

Create a code generation configuration object to generate a standalone C dynamic


library.

cfg = coder.config('dll')
% Returns a coder.EmbeddedCodeConfig object if the Embedded
% Coder product is installed.
% Otherwise, returns a coder.CodeConfig object.

Create a code generation configuration object to generate a standalone C executable.


cfg = coder.config('exe')
% Returns a coder.EmbeddedCodeConfig object if the Embedded
% Coder product is installed.
% Otherwise, returns a coder.CodeConfig object.

Create a coder.CodeConfig object even if the Embedded Coder product is installed .

cfg = coder.config('lib','ecoder',false)
% Returns a coder.CodeConfig object even if the Embedded
% Coder product is installed.

Create a floating-point to fixed-point conversion configuration object.


fixptcfg = coder.config('fixpt');
% Returns a coder.FixptConfig object

Create a double-precision to single-precision conversion configuration object.

scfg = coder.config('single');
% Returns a coder.SingleConfig object

2-45
2 Function Reference

Alternatives
Use the coder function to open the MATLAB Coder app and create a MATLAB Coder
project. The app provides a user interface that facilitates adding MATLAB files, defining
input parameters, and specifying build parameters.

See Also
coder.MexCodeConfig | coder.CodeConfig | coder.EmbeddedCodeConfig |
coder.FixptConfig | codegen

Introduced in R2011a

2-46
coder.const

coder.const
Fold expressions into constants in generated code

Syntax
out = coder.const(expression)
[out1,...,outN] = coder.const(handle,arg1,...,argN)

Description
out = coder.const(expression) evaluates expression and replaces out with the
result of the evaluation in generated code.

[out1,...,outN] = coder.const(handle,arg1,...,argN) evaluates the multi-


output function having handle handle. It then replaces out1,...,outN with the
results of the evaluation in the generated code.

Examples
Specify Constants in Generated Code

This example shows how to specify constants in generated code using coder.const.

Write a function AddShift that takes an input Shift and adds it to the elements of
a vector. The vector consists of the square of the first 10 natural numbers. AddShift
generates this vector.

function y = AddShift(Shift) %#codegen


y = (1:10).^2+Shift;

Generate code for AddShift using the codegen command. Open the Code Generation
Report.

codegen -config:lib -launchreport AddShift -args 0

2-47
2 Function Reference

The code generation software generates code for creating the vector. It adds Shift
to each element of the vector during vector creation. The definition of AddShift in
generated code looks as follows:

void AddShift(double Shift, double y[10])


{
int k;
for (k = 0; k < 10; k++) {
y[k] = (double)((1 + k) * (1 + k)) + Shift;
}
}

Replace the statement

y = (1:10).^2+Shift;

with

y = coder.const((1:10).^2)+Shift;

Generate code for AddShift using the codegen command. Open the Code Generation
Report.

codegen -config:lib -launchreport AddShift -args 0

The code generation software creates the vector containing the squares of the first 10
natural numbers. In the generated code, it adds Shift to each element of this vector.
The definition of AddShift in generated code looks as follows:

void AddShift(double Shift, double y[10])


{
int i0;
static const signed char iv0[10] = { 1, 4, 9, 16, 25, 36,
49, 64, 81, 100 };

for (i0 = 0; i0 < 10; i0++) {


y[i0] = (double)iv0[i0] + Shift;
}
}

Create Lookup Table in Generated Code

This example shows how to fold a user-written function into a constant in generated code.

2-48
coder.const

Write a function getsine that takes an input index and returns the element referred
to by index from a lookup table of sines. The function getsine creates the lookup table
using another function gettable.
function y = getsine(index) %#codegen
assert(isa(index, 'int32'));
persistent tbl;
if isempty(tbl)
tbl = gettable(1024);
end
y = tbl(index);

function y = gettable(n)
y = zeros(1,n);
for i = 1:n
y(i) = sin((i-1)/(2*pi*n));
end

Generate code for getsine using an argument of type int32. Open the Code Generation
Report.
codegen -config:lib -launchreport getsine -args int32(0)

The generated code contains instructions for creating the lookup table.

Replace the statement:


tbl = gettable(1024);

with:
tbl = coder.const(gettable(1024));

Generate code for getsine using an argument of type int32. Open the Code Generation
Report.

The generated code contains the lookup table itself. coder.const forces the expression
gettable(1024) to be evaluated during code generation. The generated code does not
contain instructions for the evaluation. The generated code contains the result of the
evaluation itself.

Specify Constants in Generated Code Using Multi-Output Function


This example shows how to specify constants in generated code using a multi-output
function in a coder.const statement.

2-49
2 Function Reference

Write a function MultiplyConst that takes an input factor and multiplies every
element of two vectors vec1 and vec2 with factor. The function generates vec1 and
vec2 using another function EvalConsts.

function [y1,y2] = MultiplyConst(factor) %#codegen


[vec1,vec2]=EvalConsts(pi.*(1./2.^(1:10)),2);
y1=vec1.*factor;
y2=vec2.*factor;

function [f1,f2]=EvalConsts(z,n)
f1=z.^(2*n)/factorial(2*n);
f2=z.^(2*n+1)/factorial(2*n+1);

Generate code for MultiplyConst using the codegen command. Open the Code
Generation Report.

codegen -config:lib -launchreport MultiplyConst -args 0

The code generation software generates code for creating the vectors.

Replace the statement

[vec1,vec2]=EvalConsts(pi.*(1./2.^(1:10)),2);

with

[vec1,vec2]=coder.const(@EvalConsts,pi.*(1./2.^(1:10)),2);

Generate code for MultiplyConst using the codegen command. Open the Code
Generation Report.

codegen -config:lib -launchreport MultiplyConst -args 0


The code generation software does not generate code for creating the vectors. Instead, it
calculates the vectors and specifies the calculated vectors in generated code.

Read Constants by Processing XML File

This example shows how to call an extrinsic function using coder.const.

Write an XML file MyParams.xml containing the following statements:

<params>
<param name="hello" value="17"/>
<param name="world" value="42"/>

2-50
coder.const

</params>

Save MyParams.xml in the current folder.

Write a MATLAB function xml2struct that reads an XML file. The function identifies
the XML tag param inside another tag params.

After identifying param, the function assigns the value of its attribute name to the field
name of a structure s. The function also assigns the value of attribute value to the value
of the field.

function s = xml2struct(file)

s = struct();
doc = xmlread(file);
els = doc.getElementsByTagName('params');
for i = 0:els.getLength-1
it = els.item(i);
ps = it.getElementsByTagName('param');
for j = 0:ps.getLength-1
param = ps.item(j);
paramName = char(param.getAttribute('name'));
paramValue = char(param.getAttribute('value'));
paramValue = evalin('base', paramValue);
s.(paramName) = paramValue;
end
end

Save xml2struct in the current folder.

Write a MATLAB function MyFunc that reads the XML file MyParams.xml into a
structure s using the function xml2struct. Declare xml2struct as extrinsic using
coder.extrinsic and call it in a coder.const statement.

function y = MyFunc(u) %#codegen


assert(isa(u, 'double'));
coder.extrinsic('xml2struct');
s = coder.const(xml2struct('MyParams.xml'));
y = s.hello + s.world + u;

Generate code for MyFunc using the codegen command. Open the Code Generation
Report.

codegen -config:dll -launchreport MyFunc -args 0

2-51
2 Function Reference

The code generation software executes the call to xml2struct during code generation.
It replaces the structure fields s.hello and s.world with the values 17 and 42 in
generated code.

Input Arguments
expression — MATLAB expression or user-written function
expression with constants | single-output function with constant arguments

MATLAB expression or user-defined single-output function.

The expression must have compile-time constants only. The function must take constant
arguments only. For instance, the following code leads to a code generation error, because
x is not a compile-time constant.
function y=func(x)
y=coder.const(log10(x));

To fix the error, assign x to a constant in the MATLAB code. Alternatively, during code
generation, you can use coder.Constant to define input type as follows:
codegen -config:lib func -args coder.Constant(10)
Example: 2*pi, factorial(10)

handle — Function handle


function handle

Handle to built-in or user-written function.


Example: @log, @sin
Data Types: function_handle

arg1,...,argN — Arguments to the function with handle handle


function arguments that are constants

Arguments to the function with handle handle.

The arguments must be compile-time constants. For instance, the following code leads to
a code generation error, because x and y are not compile-time constants.
function y=func(x,y)

2-52
coder.const

y=coder.const(@nchoosek,x,y);

To fix the error, assign x and y to constants in the MATLAB code. Alternatively, during
code generation, you can use coder.Constant to define input type as follows:

codegen -config:lib func -args {coder.Constant(10),coder.Constant(2)}

Output Arguments
out — Value of expression
value of the evaluated expression

Value of expression. In the generated code, MATLAB Coder replaces occurrences of


out with the value of expression.

out1,...,outN — Outputs of the function with handle handle


values of the outputs of the function with handle handle

Outputs of the function with handle handle.MATLAB Coder evaluates the function and
replaces occurrences of out1,...,outN with constants in the generated code.

More About
Tips

• The code generation software constant-folds expressions automatically when possible.


Typically, automatic constant-folding occurs for expressions with scalars only. Use
coder.const when the code generation software does not constant-fold expressions
on its own.

• “Constant Folding”

Introduced in R2013b

2-53
2 Function Reference

coder.cstructname
Package: coder

Name structure in generated code

Syntax
coder.cstructname(var,'structName')
coder.cstructname(var,'structName','extern')
coder.cstructname(var,'structName','extern',Name,Value)
newt = coder.cstructname(t,'structName')
newt = coder.cstructname(t,'structName','extern')
newt = coder.cstructname(t,'structName','extern',Name,Value)

Description
coder.cstructname(var,'structName') specifies the name of the structure
type that represents var in the generated C/C++ code. var is a structure or cell array
variable. structName is the name for the structure type in the generated code. Use this
syntax in a function from which you generate code. Call coder.cstructname before the
first use of the variable. If var is a cell array element, call coder.cstructname after
the first assignment to the element.

coder.cstructname(var,'structName','extern') declares an externally defined


structure. It does not generate the definition of the structure type. Provide the definition
in a custom include file.

coder.cstructname(var,'structName','extern',Name,Value) uses additional


options specified by one or more Name,Value pair arguments.

newt = coder.cstructname(t,'structName') returns a copy of the type object


specified by t. The copy specifies the name structName to use for the structure
type that represents t in the generated code. t is a coder.StructType object or a
coder.CellType object. Use this syntax to create a type that you use with the codegen
-args option. You cannot use this syntax in a function from which you generate code.

2-54
coder.cstructname

newt = coder.cstructname(t,'structName','extern') returns a coder.type


that uses an externally defined structure. Provide the structure definition in a custom
include file.

newt = coder.cstructname(t,'structName','extern',Name,Value) uses


additional options specified by one or more Name,Value pair arguments.

Limitations
• You cannot use coder.cstructname with global variables.
• If var is a cell array or t is a coder.CellType object, the field names of externally
defined structures must be f1, f2, and so on.
• If var is a cell array element, call coder.cstructname after the first assignment to
the element. For example:

...
x = cell(2,2);
x{1} = struct('a', 3);
coder.cstructname(x{1}, 'mytype');
...

Tips
• The code generation software represents a heterogeneous cell array as a structure in
the generated C/C++ code. To specify the name of the generated structure type, use
coder.cstructname.
• Using coder.cstructname with a homogeneous coder.CellType object t makes
the returned object heterogeneous unless t is permanently homogeneous. If the
makeHomogeneous method created t or if t is variable size,t is permanently
homogeneous.
• When used with a coder.CellType object, coder.cstructname creates a
coder.CellType object that is permanently heterogeneous.
• In a function from which you generate code, using coder.cstructname with a
cell array variable makes the cell array heterogeneous. Unless the cell array type is
permanently set to homogeneous, you can use coder.cstructname with an entry-
point function input that is a cell array.

2-55
2 Function Reference

• To use coder.cstructname on arrays, use single indexing. For example, you cannot
use coder.cstructname(x(1,2)). Instead, use single indexing, for example
coder.cstructname(x(n)).
• If you use coder.cstructname on an array, it sets the name of the base type of the
array, not the name of the array. Therefore, you cannot use coder.cstructname
on the base element and then on the array. For example, the following code does not
work. The second coder.cstructname attempts to set the name of the base type
to myStructArrayName, which conflicts with the previous coder.cstructname,
myStructName.
% Define scalar structure with field a
myStruct = struct('a', 0);
coder.cstructname(myStruct,'myStructName');
% Define array of structure with field a
myStructArray = repmat(myStruct,k,n);
coder.cstructname(myStructArray,'myStructArrayName');
• If you are using custom structure types, specify the name of the header file that
includes the external definition of the structure. Use the HeaderFile input
argument.
• 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. To take advantage of target-specific function implementations
that require data to be aligned, use the Alignment input argument.
• You can also use coder.cstructname to assign a name to a substructure, which is
a structure that appears as a field of another structure. For more information, see
“Assign a Name to a SubStructure” on page 2-60.

Input Arguments
structName

The name of the structure type in the generated code.

coder.StrucType object or coder.CellType object.

var

Structure or cell array variable.

2-56
coder.cstructname

Name-Value Pair Arguments


Specify optional comma-separated pairs of Name,Value arguments. Name is the
argument name and Value is the corresponding value. Name must appear inside single
quotes (' '). You can specify several name and value pair arguments in any order as
Name1,Value1,...,NameN,ValueN.

'Alignment'

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. This capability allows you to take advantage of target-specific function
implementations that require data to be aligned. By default, the structure is not aligned
on a specific boundary. Hence it is not matched by CRL functions that require alignment.

Alignment must be either -1 or a power of 2 that is not greater than 128.

Default: -1

'HeaderFile'

Name of the header file that contains the external definition of the structure, for
example, 'mystruct.h'. Specify the path to the file. Use the codegen -I option or
the Additional include directories parameter in the MATLAB Coder 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. By specifying the HeaderFile option, MATLAB Coder
includes that header file exactly at the point where it is required.

Must be a non-empty string.

Output Arguments
newt

coder.StrucType object or coder.CellType object.

2-57
2 Function Reference

Examples
Apply coder.cstructname to Top-Level Inputs

Generate code for a MATLAB function that takes structure inputs.

1 Write a MATLAB function, topfun, that assigns the name MyStruct to its input
parameter.
function y = topfun(x) %#codegen
% Assign the name 'MyStruct' to the input variable in
% the generated code
coder.cstructname(x, 'MyStruct');
y = x;
end
2 Declare a structure s in MATLAB. s is the structure definition for the input variable
x.
s = struct('a',42,'b',4711);
3 Generate a MEX function for topfun, using the -args option to specify that the
input parameter is a structure.
codegen topfun.m -args { s }

codegen generates a MEX function in the default folder codegen\mex\topfun. In


this folder, the structure definition is in topfun_types.h.
typedef struct
{
double a;
double b;
} MyStruct;

Assign a Name to a Structure and Pass It to a Function

Assign the name MyStruct to the structure var. Pass the structure to a C function
use_struct.

1 Create a C header file, use_struct.h, for a use_structfunction that takes a


parameter of type MyStruct. Define a structure of type MyStruct in the header file.
#ifdef MATLAB_MEX_FILE
#include <tmwtypes.h>

2-58
coder.cstructname

#else
#include "rtwtypes.h"
#endif

typedef struct MyStruct


{
double s1;
double s2;
} MyStruct;

void use_struct(struct MyStruct *my_struct);


2 Write the C function use_struct.c.

#include <stdio.h>
#include <stdlib.h>

#include "use_struct.h"

void use_struct(struct MyStruct *my_struct)


{
double x = my_struct->s1;
double y = my_struct->s2;
}
3 Write a m_use_struct compliant with MATLAB that declares a structure. Have the
function assign the name MyStruct to the structure. Then, have the function call
the C function use_struct using coder.ceval.

function m_use_struct %#codegen


% The directive %#codegen indicates that the function
% is intended for code generation
% Declare a MATLAB structure
var.s1 = 1;
var.s2 = 2;

% Assign the name MyStruct to the structure variable.


% extern indicates this is an externally defined
% structure.
coder.cstructname(var, 'MyStruct', 'extern');

% Call the C function use_struct. The type of var


% matches the signature of use_struct.
% Use coder.rref to pass the the variable var by
% reference as a read-only input to the external C

2-59
2 Function Reference

% function use_struct
coder.ceval('use_struct', coder.rref(var));
4 Generate C library code for function m_use_struct, passing use_struct.h to
include the structure definition.
codegen -config:lib m_use_struct use_struct.c use_struct.h
codegen generates C code in the default folder codegen\lib\m_use_struct. The
generated header file m_use_struct_types.h in this folder does not contain a
definition of the structure MyStruct because MyStruct is an external type.

Assign a Name to a SubStructure

Use coder.cstructname to assign a name to a substructure.

1 Define a MATLAB structure, top, that has another structure, lower, as a field.
% Define structure top with field lower,
% which is a structure with fields a and b
top.lower = struct('a',1,'b',1);
top.c = 1;
2 Define a function, MyFunc, which takes an argument, TopVar, as input. Mark the
function for code generation using %#codegen.
function out = MyFunc(TopVar) %#codegen
3 Inside MyFunc, include the following lines
coder.cstructname(TopVar,'topType');
coder.cstructname(TopVar.lower,'lowerType');
4 So that TopVar has the same type as top, generate C code for MyFunc with an
argument having the same type as top.
codegen -config:lib MyFunc -args coder.typeof(top)

In the generated C code, the field variable TopVar.lower is assigned the type name
lowerType. For instance, the structure declaration of the variable TopVar.lower
appears in the C code as:
typedef struct
{
/* Definitions of a and b appear here */
} lowerType;

and the structure declaration of the variable TopVar appears as:

2-60
coder.cstructname

typedef struct
{
lowerType lower;
/* Definition of c appears here */
} topType;

Create a coder.type Object

Create a coder.type object and pass it as codegen argument.

S = struct('a',double(0),'b',single(0))
T = coder.typeof(S);
T = coder.cstructname(T,'mytype');
codegen -config:lib MyFile -args T

In this example, you create a coder.type object T. The object is passed as a codegen
argument. However, because of the coder.cstructname statement, T is replaced with
mytype in the generated C code. For instance, the declaration of T appears in the C code
as:

typedef struct
{
/* Field definitions appear here */
} mytype;

Create a coder.type Object Using an Externally Defined Type

Create a C header file, MyFile.h, containing the definition of a structure type, mytype.

typedef struct {
/* Field definitions */
double a;
float b;
} mytype;

Save the file in the folder, C:\MyHeaders.

Define a coder.type object, T, with the same fields as mytype.

T = coder.typeof(struct('a',double(0),'b',single(0)));

Using coder.cstructname, rename T as mytype. Specify that the definition of mytype


is in MyFile.h.

2-61
2 Function Reference

T = coder.cstructname(T,'mytype','extern','HeaderFile','MyFile.h');

Generate code for MATLAB function, MyFunc, which takes a structure of type, T,
as input argument. Add the folder, C:\MyHeaders, to the include path during code
generation.

codegen -config:lib MyFunc -args T -I C:\MyHeaders

In the generated code, the structure, T, is assigned the name, mytype. The code
generation software does not generate the definition of mytype. Instead the software
includes the header file, MyFile.h, in the generated code.

Assign a Structure Type Name to a coder.CellType Object

Create a coder.CellType object for a cell array whose first element is char and whose
second element is double.

T = coder.typeof({'c', 1})

T =

coder.CellType
1x2 heterogeneous cell
f0: 1x1 char
f1: 1x1 double

T is a heterogeneous coder.CellType object.

Create a copy of T that specifies the name myname for the structure type that represents
T in the generated code.

T = coder.cstructname(T, 'myname')

coder.CellType
1x2 heterogeneous cell myname
f0: 1x1 char
f1: 1x1 double

Assign a Name to a Structure That Is an Element of a Cell Array

Write a function struct_in_cell that has a cell array x{1} that contains a structure.
The coder.cstructname call follows the assignment to x{1}.

function z = struct_in_cell()

2-62
coder.cstructname

x = cell(2,2);
x{1} = struct('a', 3);
coder.cstructname(x{1}, 'mytype');
z = x{1};
end

Generate a static library for struct_in_cell.

codegen -config:lib struct_in_cell -report

The type for a has the name mytype.

typedef struct {
double a;
} mytype;

• “Structures”
• “Cell Arrays”

More About
• “Homogeneous vs. Heterogeneous Cell Arrays”

See Also
coder.StructType | coder.CellType | codegen | coder.ceval | coder.rref

Introduced in R2011a

2-63
2 Function Reference

coder.extrinsic
Package: coder

Declare extrinsic function or functions

Syntax
coder.extrinsic('function_name');

coder.extrinsic('function_name_1', ... , 'function_name_n');

coder.extrinsic('-sync:on', 'function_name');

coder.extrinsic('-sync:on', 'function_name_1', ... ,


'function_name_n');

coder.extrinsic('-sync:off','function_name');

coder.extrinsic('-sync:off', 'function_name_1', ... ,


'function_name_n');

Arguments
function_name
function_name_1, ... , function_name_n
Declares function_name or function_name_1 through function_name_n as
extrinsic functions.
–sync:on
function_name or function_name_1 through function_name_n.

Enables synchronization of global data between MATLAB and MEX functions before
and after calls to the extrinsic functions, function_name or function_name_1
through function_name_n. If only a few extrinsic calls modify global data, turn
off synchronization before and after all extrinsic function calls by setting the global
synchronization mode to At MEX-function entry and exit. Use the –sync:on
option to turn on synchronization for only the extrinsic calls that do modify global
data.

2-64
coder.extrinsic

For constant global data, enables verification of consistency between MATLAB


and MEX functions after calls to the extrinsic functions, function_name or
function_name_1 through function_name_n.
–sync:off
Disables synchronization of global data between MATLAB and MEX functions before
and after calls to the extrinsic functions, function_name or function_name_1
through function_name_n. If most extrinsic calls modify global data, but a few do
not, you can use the –sync:off option to turn off synchronization for the extrinsic calls
that do not modify global data.

For constant global data, disables verification of consistency between MATLAB


and MEX functions after calls to the extrinsic functions, function_name or
function_name_1 through function_name_n.

Description
coder.extrinsic declares extrinsic functions. During simulation, the code generation
software generates code for the call to an extrinsic function, but does not generate
the function's internal code. Therefore, simulation can run only on platforms where
MATLAB software is installed. During standalone code generation, MATLAB 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
there is no change to the output, MATLAB proceeds with code generation, but excludes
the extrinsic function from the generated code. Otherwise, compilation errors occur.

You cannot use coder.ceval on functions that you declare extrinsic by using
coder.extrinsic.

coder.extrinsic is ignored outside of code generation.

Tips
• 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.

2-65
2 Function Reference

• Use the coder.screener function to detect which functions you must declare
extrinsic. This function opens the code generations readiness tool that detects code
generation issues in your MATLAB code.

During code generation, MATLAB 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 there is no change to the
output, MATLAB proceeds with code generation, but excludes the extrinsic function
from the generated code. Otherwise, a MATLAB issues a compiler error.

Examples
The following code declares the MATLAB function patch as extrinsic in the MATLAB
local function create_plot.

function c = pythagoras(a,b,color) %#codegen


% Calculates the hypotenuse of a right triangle
% and displays the triangle as a patch object.

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');

By declaring patch as extrinsic, you instruct the code generation software not to compile
or generate code for patch. Instead, the code generation software dispatches patch to
MATLAB for execution.

More About
• “Call MATLAB Functions”

2-66
coder.extrinsic

• “Controlling Synchronization for Extrinsic Function Calls”


• “Define Constant Global Data”
• “Resolution of Function Calls for Code Generation”
• “Restrictions on Extrinsic Functions for Code Generation”

See Also
coder.screener | coder.ceval

Introduced in R2011a

2-67
2 Function Reference

coder.getArgTypes
Determine types of function input arguments by running test file

Syntax
types = coder.getArgTypes(test_fcn,fcn)
structure_of_types = coder.getArgTypes(test_fcn, {fcn_1,...,fcn_n})
structure_of_types = coder.getArgTypes(test_fcn,fcn,'uniform',true)

Description
types = coder.getArgTypes(test_fcn,fcn) returns a cell array of coder.Type
objects determined by executing test_fcn. test_fcn should call the specified entry-
point MATLAB function, fcn. The software uses the input arguments to fcn to construct
the returned types.

structure_of_types = coder.getArgTypes(test_fcn, {fcn_1,...,fcn_n})


returns a structure containing cell arrays of coder.Type objects determined by
executing test_fcn. test_fcn should call the specified entry-point functions, fcn_1
through fcn_n. The software uses the input arguments to these functions to construct
the returned types. The returned structure contains one field for each function. The field
name is the same as the name of the corresponding function.

structure_of_types = coder.getArgTypes(test_fcn,fcn,'uniform',true)
returns a structure even though there is only one entry-point function.

Input Arguments
fcn

Name or handle of entry-point MATLAB function for which you want to determine input
types. The function must be on the MATLAB path; it cannot be a local function. The
function must be in a writable folder.

2-68
coder.getArgTypes

fcn_1,...,fcn_n

Comma-separated list of names or handles of entry-point MATLAB functions for which


you want to determine input types. The functions must be on the MATLAB path; they
cannot be a local function. The functions must be in a writable folder. The entry-point
function names must be unique.

test_fcn

Name or handle of test function or name of test script. The test function or script must
be on the MATLAB path. test_fcn should call at least one of the specified entry-point
functions. The software uses the input arguments to these functions to construct the
returned types.

Output Arguments
types

Cell array of coder.Type objects determined by executing the test function.

structure_of_types

Structure containing cell arrays of coder.Type objects determined by executing the


test_fcn. The structure contains one field for each function. The field name is the same
as the name of the corresponding function.

Examples
Get input parameter types for one entry-point function

Get input parameter types for function my_fun by running test file my_test that calls
my_fun. Use these input types to generate code for my_fun.

In a local writable folder, create the MATLAB function.


function y = my_fun(u,v) %#codegen
y = u+v;
end

In the same folder, create the test function.

2-69
2 Function Reference

function y = my_test
a = single(10);
b = single(20);
y = my_fun(a,b);
end

Run the test function to get the input types for my_fun.

types=coder.getArgTypes('my_test','my_fun')

types =

[1x1 coder.PrimitiveType] [1x1 coder.PrimitiveType]

Generate a MEX function for my_fun using these input types as example inputs.

codegen my_fun -args types

In the current folder, codegen generates a MEX function, my_fun_mex, that accepts
inputs of type single.

You can now test the MEX function. For example:


y = my_fun_mex(single(11),single(22))

Get input types for multiple entry-point functions

Get input parameter types for functions my_fun1 and my_fun2 by running test file
my_test2 that calls my_fun1 and my_fun2. Use these input types to generate code for
my_fun1 and my_fun2.

In a local writable folder, create the MATLAB function, my_fun1.

function y = my_fun1(u) %#codegen


y = u;

In the same folder, create the function, my_fun2.

function y = my_fun2(u, v) %#codegen


y = u + v;

In the same folder, create the test function.


function [y1, y2] = my_test2
a=10;

2-70
coder.getArgTypes

b=20;
y1=my_fun1(a);
y2=my_fun2(a,b);
end

Run the test function to get the input types for my_fun1 and my_fun2.

types=coder.getArgTypes('my_test2',{'my_fun1','my_fun2'})

types =

my_fun1: {[1x1 coder.PrimitiveType]}


my_fun2: {[1x1 coder.PrimitiveType] [1x1 coder.PrimitiveType]}

Generate a MEX function for my_fun1 and my_fun2 using these input types as example
inputs.

codegen my_fun1 -args types.my_fun1 my_fun2 -args types.my_fun2

In the current folder, codegen generates a MEX function, my_fun1_mex, with two entry
points, my_fun1 and my_fun2, that accept inputs of type double.

You can now test each entry point in the MEX function. For example:

y1=my_fun1_mex('my_fun1',10)
y2=my_fun1_mex('my_fun2',15, 25)

Alternatives
• “Specify Properties of Entry-Point Function Inputs Using the App”
• “Define Input Properties Programmatically in the MATLAB File”

More About
Tips

• Before using coder.getArgTypes, run the test function in MATLAB to verify that it
provides the expected results.
• Verify that the test function calls the specified entry-point functions with input data
types suitable for your runtime environment. If the test function does not call a

2-71
2 Function Reference

specified function, coder.getArgTypes cannot determine the input types for this
function.
• coder.getArgTypes might not compute the ideal type for your application. For
example, you might want the size to be unbounded. coder.getArgTypes returns a
bound based on the largest input that it has seen. Use coder.resize to adjust the
sizes of the returned types.
• For some combinations of inputs, coder.getArgTypes cannot produce a valid type.
For example, if the test function calls the entry-point function with single inputs and
then calls it with double inputs, coder.getArgTypes generates an error because
there is no single type that can represent both calls.
• When you generate code for the MATLAB function, use the returned types as example
inputs by passing them to the codegen using the -args option.

• “Primary Function Input Specification”

See Also
codegen | coder.resize | coder.runTest | coder.typeof

Introduced in R2012a

2-72
coder.inline

coder.inline
Package: coder

Control inlining in generated code

Syntax
coder.inline('always')
coder.inline('never')
coder.inline('default')

Description
coder.inline('always') forces inlining of the current function in generated code.

coder.inline('never') prevents inlining of the current function in generated code.


For example, you may want to prevent inlining to simplify the mapping between the
MATLAB source code and the generated code.

coder.inline('default') uses internal heuristics to determine whether or not to


inline the current function.

In most cases, the heuristics used produce highly optimized code. Use coder.inline
only when you need to fine-tune these optimizations.

Place the coder.inline directive inside the function to which it applies. The code
generation software does not inline entry-point functions.

coder.inline('always') does not inline functions called from parfor-loops. The


code generation software does not inline functions into parfor-loops.

Examples
• “Preventing Function Inlining” on page 2-74
• “Using coder.inline In Control Flow Statements” on page 2-74

2-73
2 Function Reference

Preventing Function Inlining


In this example, function foo is not inlined in the generated code:

function y = foo(x)
coder.inline('never');
y = x;
end

Using coder.inline In Control Flow Statements


You can use coder.inline in control flow code. If the software detects contradictory
coder.inline directives, the generated code uses the default inlining heuristic and
issues a warning.

Suppose you want to generate code for a division function that will be embedded in
a system with limited memory. To optimize memory use in the generated code, the
following function, inline_division, manually controls inlining based on whether it
performs scalar division or vector division:

function y = inline_division(dividend, divisor)

% For scalar division, inlining produces smaller code


% than the function call itself.
if isscalar(dividend) && isscalar(divisor)
coder.inline('always');
else
% Vector division produces a for-loop.
% Prohibit inlining to reduce code size.
coder.inline('never');
end

if any(divisor == 0)
error('Can not divide by 0');
end

y = dividend / divisor;

2-74
coder.inline

More About
inlining

Technique that replaces a function call with the contents (body) of that function. Inlining
eliminates the overhead of a function call, but can produce larger C/C++ code. Inlining
can create opportunities for further optimization of the generated C/C++ code.

Introduced in R2011a

2-75
2 Function Reference

coder.load
Load compile-time constants from MAT-file or ASCII file into caller workspace

Syntax
S = coder.load(filename)
S = coder.load(filename,var1,...,varN)
S = coder.load(filename,'-regexp',expr1,...,exprN)
S = coder.load(filename,'-ascii')
S = coder.load(filename,'-mat')
S = coder.load(filename,'-mat',var1,...,varN)
S = coder.load(filename,'-mat','-regexp', expr1,...,exprN)

Description
S = coder.load(filename) loads compile-time constants from filename.

• If filename is a MAT-file, then coder.load loads variables from the MAT-file into a
structure array.
• If filename is an ASCII file, then coder.load loads data into a double-precision
array.

S = coder.load(filename,var1,...,varN) loads only the specified variables from


the MAT-file filename.

S = coder.load(filename,'-regexp',expr1,...,exprN) loads only the variables


that match the specified regular expressions.

S = coder.load(filename,'-ascii') treats filename as an ASCII file, regardless


of the file extension.

S = coder.load(filename,'-mat') treats filename as a MAT-file, regardless of


the file extension.

S = coder.load(filename,'-mat',var1,...,varN) treats filename as a MAT-


file and loads only the specified variables from the file.

2-76
coder.load

S = coder.load(filename,'-mat','-regexp', expr1,...,exprN) treats


filename as a MAT-file and loads only the variables that match the specified regular
expressions.

Examples
Load compile-time constants from MAT-file

Generate code for a function edgeDetect1 which given a normalized image, returns an
image where the edges are detected with respect to the threshold value. edgeDetect1
uses coder.load to load the edge detection kernel from a MAT-file at compile time.

Save the Sobel edge-detection kernel in a MAT-file.

k = [1 2 1; 0 0 0; -1 -2 -1];

save sobel.mat k

Write the function edgeDetect1.

function edgeImage = edgeDetect1(originalImage, threshold) %#codegen


assert(all(size(originalImage) <= [1024 1024]));
assert(isa(originalImage, 'double'));
assert(isa(threshold, 'double'));

S = coder.load('sobel.mat','k');
H = conv2(double(originalImage),S.k, 'same');
V = conv2(double(originalImage),S.k','same');
E = sqrt(H.*H + V.*V);
edgeImage = uint8((E > threshold) * 255);

Create a code generation configuration object for a static library.

cfg = coder.config('lib');

Generate a static library for edgeDetect1.

codegen -report -config cfg edgeDetect1

2-77
2 Function Reference

codegen generates C code in the codegen\lib\edgeDetect1 folder.

Load compile-time constants from ASCII file

Generate code for a function edgeDetect2 which given a normalized image, returns an
image where the edges are detected with respect to the threshold value. edgeDetect2
uses coder.load to load the edge detection kernel from an ASCII file at compile time.

Save the Sobel edge-detection kernel in an ASCII file.

k = [1 2 1; 0 0 0; -1 -2 -1];
save sobel.dat k -ascii

Write the function edgeDetect2.

function edgeImage = edgeDetect2(originalImage, threshold) %#codegen


assert(all(size(originalImage) <= [1024 1024]));
assert(isa(originalImage, 'double'));
assert(isa(threshold, 'double'));

k = coder.load('sobel.dat');
H = conv2(double(originalImage),k, 'same');
V = conv2(double(originalImage),k','same');
E = sqrt(H.*H + V.*V);
edgeImage = uint8((E > threshold) * 255);

Create a code generation configuration object for a static library.

cfg = coder.config('lib');

Generate a static library for edgeDetect2.

codegen -report -config cfg edgeDetect2

codegen generates C code in the codegen\lib\edgeDetect2 folder.

Input Arguments
filename — Name of file
string

Name of file, specified as a string constant.

2-78
coder.load

filename can include a file extension and a full or partial path. If filename has no
extension, load looks for a file named filename.mat. If filename has an extension
other than .mat, load treats the file as ASCII data.

ASCII files must contain a rectangular table of numbers, with an equal number of
elements in each row. The file delimiter (the character between elements in each row)
can be a blank, comma, semicolon, or tab character. The file can contain MATLAB
comments (lines that begin with a percent sign, %).
Example: 'myFile.mat’
Data Types: char

var1,...,varN — Names of variables to load


string

Names of variables, specified as string constants. Use the * wildcard to match patterns.
Example: load('myFile.mat','A*') loads all variables in the file whose names start
with A.
Data Types: char

expr1,...,exprN — Regular expressions indicating which variables to load


string

Regular expressions indicating which variables to load, specified as string constants.


Example: load('myFile.mat', '^A', '^B') loads only variables whose names begin
with A or B.
Data Types: char

Output Arguments
S — Loaded variables or data
structure array | m-by-n array

If filename is a MAT-file, S is a structure array.

If filename is an ASCII file, S is an m-by-n array of type double. m is the number of


lines in the file and n is the number of values on a line.

2-79
2 Function Reference

Limitations
• coder.load does not support loading objects.
• Arguments to coder.load must be compile-time constant strings.
• The output S must be the name of a structure or array without any subscripting. For
example, S(i) = coder.load('myFile.mat') is not allowed.
• You cannot use save to save workspace data to a file inside 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 workspace data to a file.

More About
Tips

• coder.load loads data at compile time, not at run time. If you are generating MEX
code or code for Simulink® simulation, you can use the MATLAB function load to
load run-time values.
• If the MAT-file contains unsupported constructs, use
coder.load(filename,var1,...,varN) to load only the supported constructs.
• If you generate code in a MATLAB Coder project, the code generation software
practices incremental code generation for the coder.load function. When the MAT-
file or ASCII file used by coder.load changes, the software rebuilds the code.

• “Regular Expressions”

See Also
matfile | regexp | save

Introduced in R2013a

2-80
coder.newtype

coder.newtype
Package: coder

Create a coder.Type object

Syntax
t = coder.newtype(numeric_class, sz, variable_dims)
t = coder.newtype(numeric_class, sz, variable_dims, Name, Value)
t = coder.newtype('constant', value)
t = coder.newtype('struct', struct_fields, sz, variable_dims)
t = coder.newtype('cell', cells, sz, variable_dims)
t = coder.newtype('embedded.fi', numerictype, sz, variable_dims,
Name, Value)
t = coder.newtype(enum_value, sz, variable_dims)

Description

Note: coder.newtype is an advanced function that you can use to control the
coder.Type object. Consider using coder.typeof instead. coder.typeof creates a
type from a MATLAB example.

t = coder.newtype(numeric_class, sz, variable_dims) creates a


coder.Type object representing values of class numeric_class with (upper bound)
sizes sz and variable dimensions variable_dims. If sz specifies inf for a dimension,
then the size of the dimension is unbounded and the dimension is variable size. When
variable_dims is not specified, the dimensions of the type are fixed except for those
that are unbounded. When variable_dims is a scalar, it is applied to dimensions of the
type that are not 1 or 0, which are fixed.

t = coder.newtype(numeric_class, sz, variable_dims, Name, Value)


creates a coder.Type object with additional options specified by one or more Name,
Value pair arguments.

2-81
2 Function Reference

t = coder.newtype('constant', value) creates a coder.Constant object


representing a single value. Use this type to specify a value that must be treated as a
constant in the generated code.

t = coder.newtype('struct', struct_fields, sz, variable_dims) creates


a coder.StructType object for an array of structures that has the same fields as the
scalar structure struct_fields. The structure array type has the size specified by sz
and variable-size dimensions specified by variable_dims.

t = coder.newtype('cell', cells, sz, variable_dims) creates a


coder.CellType object for a cell array that has the cells and cell types specified by
cells. The cell array type has the size specified by sz and variable-size dimensions
specified by variable_dims. You cannot change the number of cells or specify variable-
size dimensions for a heterogeneous cell array.

t = coder.newtype('embedded.fi', numerictype, sz, variable_dims,


Name, Value) creates a coder.FiType object representing a set of fixed-point values
with numerictype and additional options specified by one or more Name, Value pair
arguments.

t = coder.newtype(enum_value, sz, variable_dims) creates a coder.Type


object representing a set of enumeration values of class enum_value.

Input Arguments
numeric_class

Class of the set of values represented by the type object

struct_fields

Scalar structure used to specify the fields in a new structure type

cells

Cell array of coder.Type objects that specify the types of the cells in a new cell array
type.

sz

Size vector specifying each dimension of type object. sz cannot change the number of
cells for a heterogeneous cell array.

2-82
coder.newtype

Default: [1 1]

variable_dims

Logical vector that specifies whether each dimension is variable size (true) or fixed size
(false). You cannot specify variable-size dimensions for a heterogeneous cell array.

Default: true for dimensions for which sz specifies an upper bound of inf; false for
all other dimensions.

Name-Value Pair Arguments


Specify optional comma-separated pairs of Name,Value arguments. Name is the
argument name and Value is the corresponding value. Name must appear inside single
quotes (' '). You can specify several name and value pair arguments in any order as
Name1,Value1,...,NameN,ValueN.

'complex'

Set complex to true to create a coder.Type object that can represent complex values.
The type must support complex data.

Default: false

'fimath'

Specify local fimath. If fimath is not specified, uses default fimath values.

Use only with t=coder.newtype('embedded.fi', numerictype,sz, variable_dims, Name,


Value).

'sparse'

Set sparse to true to create a coder.Type object representing sparse data. The type
must support sparse data.

Not for use with t=coder.newtype('embedded.fi', numerictype,sz, variable_dims,


Name, Value)

Default: false

2-83
2 Function Reference

Output Arguments
t

New coder.Type object.

Examples
Create a type for use in code generation.

t=coder.newtype('double',[2 3 4],[1 1 0])


% Returns double :2x:3x4
% ':' indicates variable-size dimensions

Create a type for a matrix of doubles, first dimension unbounded, second dimension with
fixed size

coder.newtype('double',[inf,3])
% returns double:inf x 3

coder.newtype('double', [inf, 3], [1 0])


% also returns double :inf x3
% ':' indicates variable-size dimensions

Create a type for a matrix of doubles, first dimension unbounded, second dimension with
variable size with an upper bound of 3

coder.newtype('double', [inf,3],[0 1])


% returns double :inf x :3
% ':' indicates variable-size dimensions

Create a structure type to use in code generation.

ta = coder.newtype('int8',[1 1]);
tb = coder.newtype('double',[1 2],[1 1]);
coder.newtype('struct',struct('a',ta,'b',tb))
% returns struct 1x1
% a: int8 1x1
% b: double :1x:2
% ':' indicates variable-size dimensions

Create a cell array to use in code generation.

2-84
coder.newtype

ta = coder.newtype('int8',[1 1]);
tb = coder.newtype('double',[1 2],[1 1]);
coder.newtype('cell',{ta, tb})
% returns 1x2 heterogeneous cell
% f0: 1x1 int8
% f1: :1x:2 double
% ':' indicates variable-size dimensions

Create a new constant type to use in code generation.


k = coder.newtype('constant', 42);
% Returns
% k =
%
% coder.Constant
% 42

Create a coder.EnumType object using the name of an existing MATLAB enumeration.

1 Define an enumeration MyColors. On the MATLAB path, create a file named


'MyColors' containing:
classdef MyColors < int32
enumeration
green(1),
red(2),
end
end
2 Create a coder.EnumType object from this enumeration.
t = coder.newtype('MyColors');

Create a new fixed-point type for use in code generation. The fixed-point type uses
default fimath values.
t = coder.newtype('embedded.fi',...
numerictype(1, 16, 15), [1 2])

t =
% Returns
% coder.FiType
% 1x2 embedded.fi
% DataTypeMode: Fixed-point: binary point scaling
% Signedness: Signed
% WordLength: 16

2-85
2 Function Reference

% FractionLength: 15

Alternatives
coder.typeof

See Also
coder.Type | coder.ArrayType | coder.EnumType | coder.FiType | coder.PrimitiveType
| coder.StructType | coder.CellType | codegen | coder.resize

Introduced in R2011a

2-86
coder.nullcopy

coder.nullcopy
Package: coder

Declare uninitialized variables

Syntax

X = coder.nullcopy(A)

Description
X = coder.nullcopy(A) copies type, size, and complexity of A to X, but does not copy
element values. Preallocates memory for X without incurring the overhead of initializing
memory.

coder.nullcopy does not support MATLAB classes as inputs.

Use With Caution


Use this function with caution. See “How to Eliminate Redundant Copies by Defining
Uninitialized Variables”.

Examples
The following example shows how to declare variable X as a 1-by-5 vector of real doubles
without performing an unnecessary initialization:
function X = foo

N = 5;
X = coder.nullcopy(zeros(1,N));
for i = 1:N
if mod(i,2) == 0
X(i) = i;
else

2-87
2 Function Reference

X(i) = 0;
end
end

Using coder.nullcopy with zeros lets you specify the size of vector X without
initializing each element to zero.

More About
• “Eliminate Redundant Copies of Variables in Generated Code”

Introduced in R2011a

2-88
coder.opaque

coder.opaque
Declare variable in generated code

Syntax
y = coder.opaque(type)
y = coder.opaque(type,value)
y = coder.opaque(type,'HeaderFile',HeaderFile)
y = coder.opaque(type,value,'HeaderFile',HeaderFile)

Description
y = coder.opaque(type) declares a variable y with the specified type and no initial
value in the generated code.

• y can be a variable or a structure field.


• MATLAB code cannot set or access y, but external C functions can accept y as an
argument.
• y can be an:

• Argument to coder.rref, coder.wref, or coder.ref


• Input or output argument to coder.ceval
• Input or output argument to a user-written MATLAB function
• Input to a subset of MATLAB toolbox functions supported for code generation
• Assignment from y declares another variable with the same type in the generated
code. For example:

y = coder.opaque('int');
z = y;
declares a variable z of type int in the generated code.
• You can assign y from another variable declared using either coder.opaque or
assignment from a variable declared using coder.opaque. The variables must have
identical types.

2-89
2 Function Reference

• You can compare y to another variable declared using either coder.opaque or


assignment from a variable declared using coder.opaque. The variables must have
identical types.

y = coder.opaque(type,value) declares a variable y and specifies the initial value


of y in the generated code.

y = coder.opaque(type,'HeaderFile',HeaderFile) declares a variable y


and specifies the header file that contains the definition of type. The code generation
software generates the #include statement for the header file where required in the
generated code.

y = coder.opaque(type,value,'HeaderFile',HeaderFile) declares a variable y


with the specified type, initial value, and header file in the generated code.

Examples
Declare Variable Specifying Initial Value

Generate code for a function valtest which returns 1 if the call to myfun is successful.
This function uses coder.opaque to declare a variable x1 with type int and initial
value 0. The assignment x2 = x1 declares x2 to be a variable with the type and initial
value of x1 .

Write a function valtest.

function y = valtest
%codegen
%declare x1 to be an integer with initial value '0')
x1 = coder.opaque('int','0');
%Declare x2 to have same type and intial value as x1
x2 = x1;
x2 = coder.ceval('myfun');
%test the result of call to 'myfun' by comparing to value of x1
if x2 == x1;
y = 0;
else
y = 1;
end
end

2-90
coder.opaque

Create a code generation configuration object for a static library.

cfg = coder.config('lib');

Generate a static library for valtest.

codegen -report -config cfg valtest

codegen generates C code in the codegen\lib\valtest folder.

Declare Variable Specifying Initial Value and Header File

Generate code for a MATLAB function filetest which returns its own source
code using fopen/fread/fclose. This function uses coder.opaque to declare
the variable that stores the file pointer used by fopen/fread/fclose. The call to
coder.opaque declares the variable f with type FILE *, initial value NULL, and
header file <stdio.h>.

Write a MATLAB function filetest.


function buffer = filetest
%#codegen

% Declare 'f' as an opaque type 'FILE *' with intial value 'NULL"
%Specify the header file that contains the type definition of 'FILE *';

f = coder.opaque('FILE *', 'NULL','HeaderFile','<stdio.h>');


% Open file in binary mode
f = coder.ceval('fopen', cstring('filetest.m'), cstring('rb'));

% Read from file until end of file is reached and put


% contents into buffer
n = int32(1);
i = int32(1);
buffer = char(zeros(1,8192));
while n > 0
% By default, MATLAB converts constant values
% to doubles in generated code
% so explicit type conversion to int32 is inserted.
n = coder.ceval('fread', coder.ref(buffer(i)), int32(1), ...
int32(numel(buffer)), f);
i = i + n;
end
coder.ceval('fclose',f);

buffer = strip_cr(buffer);

% Put a C termination character '\0' at the end of MATLAB string


function y = cstring(x)
y = [x char(0)];

2-91
2 Function Reference

% Remove all character 13 (CR) but keep character 10 (LF)


function buffer = strip_cr(buffer)
j = 1;
for i = 1:numel(buffer)
if buffer(i) ~= char(13)
buffer(j) = buffer(i);
j = j + 1;
end
end
buffer(i) = 0;

Create a code generation configuration object for a static library.

cfg = coder.config('lib');

Generate a static library for filetest.

codegen -report -config cfg filetest

codegen generates C code in the codegen\lib\filetest folder.

Compare Variables Declared Using coder.opaque

Compare variables declared using coder.opaque to test for successfully opening a file.

Use coder.opaque to declare a variable null with type FILE * and initial value NULL.

null = coder.opaque('FILE *', 'NULL', 'HeaderFile', '<stdio.h>');

Use assignment to declare another variable ftmp with the same type and value as null.

ftmp = null;
ftmp = coder.ceval('fopen', ['testfile.txt', char(0)], ['r', char(0)]);

Compare the variables.

if ftmp == null
%error condition
end

Cast to and from Types of Variables Declared Using coder.opaque

This example shows how to cast to and from types of variables that are declared using
coder.opaque. The function castopaque calls the C run-time function strncmp to
compare at most n characters of the strings s1 and s2. n is the number of characters in

2-92
coder.opaque

the shorter of the strings. To generate the correct C type for the strncmp input nsizet,
the function casts n to the C type size_t and assigns the result to nsizet. The function
uses coder.opaque to declare nsizet. Before using the output retval from strncmp,
the function casts retval to the MATLAB type int32 and stores the results in y.

Write this MATLAB function:

function y = castopaque(s1,s2)

% <0 - the first character that does not match has a lower value in s1 than in s2
% 0 - the contents of both strings are equal
% >0 - the first character that does not match has a greater value in s1 than in s2
%
%#codegen

coder.cinclude('<string.h>');
n = min(numel(s1), numel(s2));

% Convert the number of characters to compare to a size_t

nsizet = cast(n,'like',coder.opaque('size_t','0'));

% The return value is an int


retval = coder.opaque('int');
retval = coder.ceval('strncmp', cstr(s1), cstr(s2), nsizet);

% Convert the opaque return value to a MATLAB value


y = cast(retval, 'int32');

%--------------
function sc = cstr(s)
% NULL terminate a MATLAB string for C
sc = [s, char(0)];

Generate the MEX function.

codegen castopaque -args {blanks(3), blanks(3)} -report

Call the MEX function with inputs 'abc' and 'abc'.

castopaque_mex('abc','abc')

ans =

2-93
2 Function Reference

The output is 0 because the strings are equal.

Call the MEX function with inputs 'abc' and 'abd'.

castopaque_mex('abc','abd')

ans =

-1

The output is -1 because the third character d in the second string is greater than the
third character c in the first string.

Call the MEX function with inputs 'abd' and 'abc'.

castopaque_mex('abd','abc')

ans =

The output is 1 because the third character d in the first string is greater than the third
character c in the second string.

In the MATLAB workspace, you can see that the type of y is int32.

Input Arguments
type — Type of variable
string

Type of variable in generated code specified as a string constant. The type must be a:

• Built-in C data type or a type defined in a header file


• C type that supports copy by assignment
• Legal prefix in a C declaration

Example: 'FILE *'

2-94
coder.opaque

Data Types: char

value — Initial value of variable


string

Initial value of variable in generated code specified as a string constant. Specify a C


expression not dependent on MATLAB variables or functions.

If you do not provide the initial value in value, initialize the value of the variable prior
to using it. To initialize a variable declared using coder.opaque:

• Assign a value from another variable with the same type declared using either
coder.opaque or assignment from a variable declared using coder.opaque.
• Assign a value from an external C function.
• Pass the variable’s address to an external function using coder.wref.

Specify a value that has the type that type specifies. Otherwise, the generated code can
produce unexpected results.
Example: 'NULL'
Data Types: char

HeaderFile — Name of header file


string

Name of header file, specified as a string constant, that contains the definition of type.

For a system header file, use angle brackets.


Example: '<stdio.h>' generates #include <stdio.h>

For an application header file, use double quotes.


Example: '"foo.h"' generates #include "foo.h"

If you omit the angle brackets or double quotes, the code generation software generates
double quotes.
Example: 'foo.h' generates #include "foo.h"

Specify the include path in the build configuration parameters.


Example: cfg.CustomInclude = 'c:\myincludes'

2-95
2 Function Reference

Data Types: char

More About
Tips

• Specify a value that has the type that type specifies. Otherwise, the generated
code can produce unexpected results. For example, the following coder.opaque
declaration can produce unexpected results.
y = coder.opaque('int', '0.2')
• coder.opaque declares the type of a variable. It does not instantiate the variable.
You can instantiate a variable by using it later in the MATLAB code. In the following
example, assignment of fp1 from coder.ceval instantiates fp1.
% Declare fp1 of type FILE *
fp1 = coder.opaque('FILE *');
%Create the variable fp1
fp1 = coder.ceval('fopen', ['testfile.txt', char(0)], ['r', char(0)]);

• In the MATLAB environment, coder.opaque returns the value specified in value. If


value is not provided, it returns the empty string.
• You can compare variables declared using either coder.opaque or assignment from
a variable declared using coder.opaque. The variables must have identical types.
The following example demonstrates how to compare these variables. “Compare
Variables Declared Using coder.opaque” on page 2-92
• To avoid multiple inclusions of the same header file in generated code, enclose the
header file in the conditional preprocessor statements #ifndef and #endif. For
example:
#ifndef MyHeader_h
#define MyHeader_h
<body of header file>
#endif
• You can use the MATLAB cast function to cast a variable to or from a variable that
is declared using coder.opaque. Use cast with coder.opaque only for numeric
types.

To cast a variable declared by coder.opaque to a MATLAB type, you can use the B
= cast(A,type) syntax. For example:
x = coder.opaque('size_t','0');

2-96
coder.opaque

x1 = cast(x, 'int32');

You can also use the B = cast(A,'like',p) syntax. For example:

x = coder.opaque('size_t','0');
x1 = cast(x, 'like', int32(0));

To cast a MATLAB variable to the type of a variable declared by coder.opaque, you


must use the B = cast(A,'like',p) syntax. For example:

x = int32(12);
x1 = coder.opaque('size_t', '0');
x2 = cast(x, 'like', x1));

Use cast with coder.opaque to generate the correct data types for:

• Inputs to C/C++ functions that you call using coder.ceval.


• Variables that you assign to outputs from C/C++ functions that you call using
coder.ceval.

Without this casting, it is possible to receive compiler warnings during code


generation.

• “Specify Build Configuration Parameters”

See Also
coder.ceval | coder.ref | coder.rref | coder.wref

Introduced in R2011a

2-97
2 Function Reference

coder.ref
Package: coder

Pass argument by reference as read input or write output

Syntax
[y =] coder.ceval('function_name', coder.ref(arg), ... un)

Arguments
arg
Variable passed by reference as an input or an output to the external C/C++ function
called in coder.ceval. arg must be a scalar variable, a matrix variable, or an
element of a matrix variable.

Description
[y =] coder.ceval('function_name', coder.ref(arg), ... un) passes
the variable arg by reference as an input or an output to the external C/C++ function
called in coder.ceval. You add coder.ref inside coder.ceval as an argument to
function_name. The argument list can contain multiple coder.ref constructs. Add a
separate coder.ref construct for each argument that you want to pass by reference to
function_name.

Only use coder.ref in MATLAB code that you have compiled with codegen.
coder.ref generates an error in uncompiled MATLAB code.

Examples
In the following example, a MATLAB function fcn has a single input u and a single
output y. fcn calls a C function my_fcn, passing u by reference as an input. The value of
output y is passed to fcn by the C function through its return statement.

2-98
coder.ref

Here is the MATLAB function code:

function y = fcn(u) %#codegen

y = 0; %Constrain return type to double


y = coder.ceval('my_fcn', coder.ref(u));

The C function prototype for my_fcn must be as follows:

double my_fcn(double *u)

In this example, the generated code infers the type of the input u from the codegen
argument.

The C function prototype defines the input as a pointer because it is passed by reference.

The generated code cannot infer the type of the output y, so you must set it explicitly—in
this case to a constant value 0 whose type defaults to double.

See Also
coder.ceval | coder.rref | coder.wref

Introduced in R2011a

2-99
2 Function Reference

coder.resize
Package: coder

Resize a coder.Type object

Syntax
t_out = coder.resize(t, sz, variable_dims)
t_out = coder.resize(t, sz)
t_out = coder.resize(t,[],variable_dims)
t_out = coder.resize(t, sz, variable_dims, Name, Value)
t_out = coder.resize(t, 'sizelimits', limits)

Description
t_out = coder.resize(t, sz, variable_dims) returns a modified copy of
coder.Type t with upper-bound size sz, and variable dimensions variable_dims.
If variable_dims or sz are scalars, the function applies them to all dimensions of t.
By default, variable_dims does not apply to dimensions where sz is 0 or 1, which
are fixed. Use the 'uniform' option to override this special case. coder.resize ignores
variable_dims for dimensions with size inf. These dimensions are always variable
size. t can be a cell array of types, in which case, coder.resize resizes all elements of
the cell array.

t_out = coder.resize(t, sz) resizes t to have size sz.

t_out = coder.resize(t,[],variable_dims) changes t to have variable


dimensions variable_dims while leaving the size unchanged.

t_out = coder.resize(t, sz, variable_dims, Name, Value) resizes t using


additional options specified by one or more Name, Value pair arguments.

t_out = coder.resize(t, 'sizelimits', limits) resizes t with dimensions


becoming variable based on the limits vector. When the size S of a dimension is greater
than or equal to the first threshold defined in limits, the dimension becomes variable
size with upper bound S. When the size S of a dimension is greater than or equal to the
second threshold defined in limits, the dimension becomes unbounded variable size.

2-100
coder.resize

Input Arguments
limits

Two-element vector (or a scalar-expanded, one-element vector) of variable-sizing


thresholds. If the size sz of a dimension of t is greater than or equal to the first
threshold, the dimension becomes variable size with upper bound sz. If the size sz of a
dimension of t is greater than or equal to the second threshold, the dimension becomes
unbounded variable size.

sz

New size for coder.Type object, t_out

coder.Type object that you want to resize. If t is a coder.CellType object, the


coder.CellType object must be homogeneous.

variable_dims

Specify whether each dimension of t_out is fixed or variable size.

Name-Value Pair Arguments


Specify optional comma-separated pairs of Name,Value arguments. Name is the
argument name and Value is the corresponding value. Name must appear inside single
quotes (' '). You can specify several name and value pair arguments in any order as
Name1,Value1,...,NameN,ValueN.

'recursive'

Setting recursive to true resizes t and all types contained within it.

Default: false

'uniform'

Setting uniform to true resizes t but does not apply the heuristic for dimensions of size
one.

Default: false

2-101
2 Function Reference

Output Arguments
t_out

Resized coder.Type object

Examples
Change a fixed-size array to a bounded, variable-size array.
t = coder.typeof(ones(3,3))
% t is 3x3
coder.resize(t, [4 5], 1)
% returns :4 x :5
% ':' indicates variable-size dimensions

Change a fixed-size array to an unbounded, variable-size array.


t = coder.typeof(ones(3,3))
% t is 3x3
coder.resize(t, inf)
% returns :inf x :inf
% ':' indicates variable-size dimensions
% 'inf' indicates unbounded dimensions

Resize a structure field.


ts = coder.typeof(struct('a', ones(3, 3)))
% returns field a as 3x3
coder.resize(ts, [5, 5], 'recursive', 1)
% returns field as 5x5

Resize a cell array.


tc = coder.typeof({1 2 3})
% returns 1x3 cell array
coder.resize(tc, [5, 5], 'recursive', 1)
% returns cell array as 5x5

Make a fixed-sized array variable size based on bounded and unbounded thresholds.
t = coder.typeof(ones(100,200))
% t is 100x200

2-102
coder.resize

coder.resize(t,'sizelimits', [99 199])


% returns :100x:inf
% ':' indicates variable-size dimensions
% :inf is unbounded variable size

See Also
codegen | coder.typeof | coder.newtype

Introduced in R2011a

2-103
2 Function Reference

coder.rref
Package: coder

Pass argument by reference as read-only input

Syntax
[y =] coder.ceval('function_name', coder.rref(argI), ... un)

Arguments
argI
Variable passed by reference as a read-only input to the external C/C++ function
called in coder.ceval.

Description
[y =] coder.ceval('function_name', coder.rref(argI), ... un) passes
the variable argI by reference as a read-only input to the external C/C++ function
called in coder.ceval. You add coder.rref inside coder.ceval as an argument to
function_name. The argument list can contain multiple coder.rref constructs. Add
a separate coder.rref construct for each read-only argument that you want to pass by
reference to function_name.

Caution The generated code assumes that a variable passed by coder.rref is read-only
and is optimized accordingly. Consequently, the C/C++ function must not write to the
variable or results can be unpredictable.

Only use coder.rref in MATLAB code that you have compiled with codegen.
coder.rref generates an error in uncompiled MATLAB code.

2-104
coder.rref

Examples
In the following example, a MATLAB function fcn has a single input u and a single
output y. fcn calls a C function foo, passing u by reference as a read-only input. The
value of output y is passed to fcn by the C function through its return statement.

Here is the MATLAB function code:

function y = fcn(u) %#codegen

y = 0; % Constrain return type to double


y = coder.ceval('foo', coder.rref(u));

The C function prototype for foo must be as follows:

double foo(const double *u)

In this example, the generated code infers the type of the input u from the codegen
argument.

The C function prototype defines the input as a pointer because it is passed by reference.

The generated code cannot infer the type of the output y, so you must set it explicitly—in
this case to a constant value 0 whose type defaults to double.

See Also
| | | | coder.ceval | coder.opaque | coder.ref | coder.wref

Introduced in R2011a

2-105
2 Function Reference

coder.runTest
Run test replacing calls to MATLAB functions with calls to MEX functions

Syntax
coder.runTest(test,fcn)
coder.runTest(test,fcns,mexfcn)
coder.runTest(test,mexfile)

Description
coder.runTest(test,fcn) runs test replacing calls to fcn with calls to the compiled
version of fcn. test is the file name for a MATLAB function or script that calls the
MATLAB function fcn. The compiled version of fcn must be in a MEX function that has
the default name. The default name is the name specified by fcn followed by _mex.

coder.runTest(test,fcns,mexfcn) replaces calls to the specified MATLAB


functions with calls to the compiled versions of the functions. The MEX function mexfcn
must contain the compiled versions of all of the specified MATLAB functions.

coder.runTest(test,mexfile) replaces a call to a MATLAB function with a call


to the compiled version of the function when the compiled version of the function is in
mexfile. mexfile includes the platform-specific file extension. If mexfile does not
contain the compiled version of a function, coder.runTest runs the original MATLAB
function. If you do not want to specify the individual MATLAB functions to replace, use
this syntax.

Examples
Run Test File Replacing One Function

Use coder.runTest to run a test file. Specify replacement of one MATLAB function
with the compiled version. You do not provide the name of the MEX function that
contains the compiled version. Therefore, coder.runTest looks for a MEX function that
has the default name.

2-106
coder.runTest

In a local, writable folder, create a MATLAB function, myfun.


function y = myfun(u,v) %#codegen
y = u+v;
end

In the same folder, create a test function, mytest1, that calls myfun.
function mytest1
c = myfun(10,20);
disp(c);
end

Run the test function in MATLAB.


mytest1

30

Generate a MEX function for myfun.


codegen myfun -args {0,0}

In the current folder, codegen generates a MEX function that has the default name,
myfun_mex.

Run coder.runTest. Specify that you want to run the test file mytest1. Specify
replacement of myfun with the compiled version in myfun_mex.
coder.runTest('mytest1','myfun')

30

The results are the same as when you run mytest1 at the MATLAB command line.

Replace Multiple Functions That You Specify

Use coder.runTest to run a test file. Specify replacement of two functions with calls to
the compiled versions. Specify the MEX function that contains the compiled versions of
the functions.

In a local writable folder, create a MATLAB function, myfun1.


function y = myfun1(u) %#codegen
y = u;
end

2-107
2 Function Reference

In the same folder, create another MATLAB function, myfun2.


function y = myfun2(u, v) %#codegen
y = u + v;
end

In the same folder, create a test function that calls myfun1 and myfun2.
function mytest2
c1 = myfun1(10);
disp(c1)
c2 = myfun2(10,20);
disp(c2)
end

Run the test function.


mytest2

10

30

Generate a MEX function for myfun1 and myfun2. Use the -o option to specify the name
of the generated MEX function.
codegen -o mymex myfun1 -args {0} myfun2 -args {0,0}

Run coder.runTest. Specify that you want to run mytest2. Specify that you want to
replace the calls to myfun1 and myfun2 with calls to the compiled versions in the MEX
function mymex.
coder.runTest('mytest2',{'myfun1','myfun2'},'mymex')

10

30

The results are the same as when you run mytest2 at the MATLAB command line.

Replace Functions That Have Compiled Versions in Specified MEX File

Use coder.runTest to run a test that replaces calls to MATLAB functions in the test
with calls to the compiled versions. Specify the file name for the MEX function that
contains the compiled versions of the functions.

2-108
coder.runTest

In a local writable folder, create a MATLAB function, myfun1.

function y = myfun1(u) %#codegen


y = u;
end

In the same folder, create another MATLAB function, myfun2.

function y = myfun2(u, v) %#codegen


y = u + v;
end

In the same folder, create a test function that calls myfun1 and myfun2.

function mytest2
c1 = myfun1(10);
disp(c1)
c2 = myfun2(10,20);
disp(c2)
end

Run the test.

mytest2

10

30

Generate a MEX function for myfun1 and myfun2. Use the -o option to specify the name
of the generated MEX function.

codegen -o mymex myfun1 -args {0} myfun2 -args {0,0}

Run coder.runTest. Specify that you want to run mytest2. Specify that you want
to replace calls to functions called by mytest2 with calls to the compiled versions in
mymex. Specify the complete MEX file name including the platform-specific extension.
Use mexext to get the platform-specific extension.

coder.runTest('mytest2',['mymex.', mexext])

10

30

2-109
2 Function Reference

The results are the same as when you run mytest2 at the MATLAB command line.

Input Arguments
test — File name for test function or script
string

File name for MATLAB function or script that calls the functions to replace with
compiled versions of the functions.
Example: 'mytest'
Data Types: char

fcn — Name of MATLAB function to replace


string

Name of MATLAB function to replace when running test. coder.runTest replaces calls
to this function with calls to the compiled version of this function.
Example: 'myfun'
Data Types: char

fcns — Names of MATLAB functions to replace


string | cell array of strings

Names of MATLAB functions to replace when running test. coder.runTest replaces


calls to these functions with calls to the compiled versions of these functions.

Specify one function as a string.


Example: 'myfun'

Specify multiple functions as a cell array of strings. Before using coder.runTest,


compile these functions into a single MEX function.
Example: {'myfun1', 'myfun2', 'myfun3'}
Data Types: char | cell

mexfcn — MEX function name


string

2-110
coder.runTest

Name of a MEX function generated for one or more functions.

Generate this MEX function using the MATLAB Coder app or the codegen function.
Example: 'mymex'
Data Types: char

mexfile — MEX file name with extension


string

The file name and platform-specific extension of a MEX file for one or more functions.
Use mexext to get the platform-specific MEX file extension.

Generate this MEX file using the MATLAB Coder app or the codegen function.
Example: ['myfunmex.', mexext]
Data Types: char

More About
Tips

• coder.runTest does not return outputs. To see test results, in the test, include code
that displays the results.
• To compare MEX and MATLAB function behavior:

• Run the test in MATLAB.


• Use codegen to generate a MEX function.
• Use coder.runTest to run the test replacing the call to the original function with
a call to the compiled version in the MEX function.
• Before using coder.runTest to test multiple functions, compile the MATLAB
functions into a single MEX function.
• If you use the syntax coder.runTest(test, mexfile), use mexext to get the
platform-specific MEX file name extension. For example:
coder.runTest('my_test', ['mymexfun.', mexext])
• If errors occur during the test, you can debug the code using call stack information.

• “MATLAB Code Analysis”

2-111
2 Function Reference

See Also
codegen | coder | coder.getArgTypes

Introduced in R2012a

2-112
coder.screener

coder.screener
Determine if function is suitable for code generation

Syntax
coder.screener(fcn)
coder.screener(fcn_1,...,fcn_n )

Description
coder.screener(fcn) analyzes the entry-point MATLAB function, fcn. It identifies
unsupported functions and language features, such as recursion and nested functions,
as code generation compliance issues. It displays the code generation compliance issues
in a report. If fcn calls other functions directly or indirectly that are not MathWorks®
functions, coder.screener analyzes these functions. It does not analyze MathWorks
functions. It is possible that coder.screener does not detect all code generation issues.
Under certain circumstances, it is is possible that coder.screener reports false errors.

coder.screener(fcn_1,...,fcn_n ) analyzes entry-point functions


(fcn_1,...,fcn_n).

Input Arguments
fcn

Name of entry-point MATLAB function that you want to analyze.

fcn_1,...,fcn_n

Comma-separated list of names of entry-point MATLAB functions that you want to


analyze.

2-113
2 Function Reference

Examples
Identify Unsupported Functions

The coder.screener function identifies calls to functions that are not supported for
code generation. It checks both the entry-point function, foo1, and the function foo2
that foo1 calls.

Analyze the MATLAB function foo1 that calls foo2. Put foo1 and foo2 in separate
files.

function out = foo1(in)


out = foo2(in);
disp(out);
end

function out = foo2(in)


out = eval(in);
end

coder.screener('foo1')

The code generation readiness report displays a summary of the unsupported MATLAB
function calls. The function foo2 calls one unsupported MATLAB function.

2-114
coder.screener

In the report, click the Code Structure tab and select the Show MATLAB functions
check box.

This tab displays a pie chart showing the relative size of each file and how suitable each
file is for code generation. In this case, the report:

• Colors foo1.m green to indicate that it is suitable for code generation.


• Colors foo2.m yellow to indicate that it requires significant changes.

2-115
2 Function Reference

• Assigns foo1.m a code generation readiness score of 4 and foo2.m a score of 3. The
score is based on a scale of 1–5. 1 indicates that significant changes are required; 5
indicates that the code generation readiness tool does not detect issues.
• Displays a call tree.

The report Summary tab indicates that foo2.m contains one call to the eval function
which code generation does not support. To generate a MEX function for foo2.m, modify
the code to make the call to eval extrinsic.

2-116
coder.screener

function out = foo2(in)


coder.extrinsic('eval');
out = eval(in);
end

Rerun the code generation readiness tool.

coder.screener('foo1')

The report no longer flags that code generation does not support the eval function.
When you generate a MEX function for foo1, the code generation software dispatches
eval to MATLAB for execution. For standalone code generation, it does not generate
code for it.

Identify Unsupported Data Types

The coder.screener function identifies data types that code generation does not
support.

Analyze the MATLAB function foo3 that uses unsupported data types.

function [outSparse,outCategorical] = foo3(A,B,C)


outSparse = sparse(A);
outCategorical = categorical(B);
outTable = table(C);
end

coder.screener('foo3')

The code generation readiness report displays a summary of the unsupported data types.

2-117
2 Function Reference

The report assigns the code a code readiness score of 2. This score indicates that the code
requires extensive changes.

Before generating code, you must fix the reported issues.

Determine Code Generation Readiness for Multiple Entry-Point Functions

The coder.screener function identifies calls to functions that code generation does not
support. It checks the entry-point functions foo4 and foo5.

Analyze the MATLAB functions foo4 and foo5.

function out = foo4(in)


out = in;
disp(out);
end

function out = foo5(in)


out = eval(in);
end

2-118
coder.screener

coder.screener('foo4', 'foo5')

The code generation readiness report displays a summary of the unsupported MATLAB
function calls. The function foo5 calls one unsupported MATLAB function.

In the report, click the Code Structure tab. Select the Show MATLAB functions
check box.

This tab displays a pie chart showing the relative size of each file and how suitable each
file is for code generation. In this case, the report:

2-119
2 Function Reference

• Colors foo4.m green to indicate that it is suitable for code generation.


• Colors foo5.m yellow to indicate that it requires significant changes.
• Assigns foo4.m a code generation readiness score of 4 and foo5.m a score of 4. The
score is based on a scale of 1–5. 1 indicates that significant changes are required; 5
indicates that the code generation readiness tool cannot detect issues.
• Displays a call tree.

2-120
coder.screener

Alternatives
• “Run Code Generation Readiness Tool from the Current Folder Browser”
• “Run the Code Generation Readiness Tool Using the MATLAB Coder App”.

2-121
2 Function Reference

More About
Tips

• Before using coder.screener, fix issues that the Code Analyzer identifies.
• Before generating code, use coder.screener to check that a function is suitable for
code generation. Fix all the issues that it detects.
• It is possible that coder.screener does not detect all issues, and can report false
errors. Therefore, before generating C code, verify that your code is suitable for code
generation by generating a MEX function.

• “MATLAB Language Features Supported for C/C++ Code Generation”


• “Functions and Objects Supported for C and C++ Code Generation — Alphabetical
List”
• “Functions and Objects Supported for C and C++ Code Generation — Category List”
• “Code Generation Readiness Tool”

See Also
codegen

Introduced in R2012b

2-122
coder.target

coder.target
Determine if code generation target is specified target

Syntax
tf = coder.target(target)

Description
tf = coder.target(target) returns true (1) if the code generation target is target.
Otherwise, it returns false (0).

If you generate code for MATLAB classes, MATLAB computes class initial values at
class loading time before code generation. If you use coder.target in MATLAB class
property initialization, coder.target('MATLAB') returns true.

Examples
Use coder.target to parameterize a MATLAB function

Parameterize a MATLAB function so that it works in MATLAB or generated code. When


the function runs in MATLAB, it calls the MATLAB function myabsval. The generated
code, however, calls a C library function myabsval.

Write a MATLAB function myabsval.

function y = myabsval(u) %#codegen


y = abs(u);

Generate the C library for myabsval.m, using the -args option to specify the size, type,
and complexity of the input parameter.
codegen -config:lib myabsval -args {0.0}
codegen creates the library myabsval.lib and header file myabsval.h in the folder /
codegen/lib/myabsval. It also generates the functions myabsval_initialize and
myabsval_terminate in the same folder.

2-123
2 Function Reference

Write a MATLAB function to call the generated C library function using coder.ceval.

function y = callmyabsval %#codegen


y = -2.75;
% Check the target. Do not use coder.ceval if callmyabsval is
% executing in MATLAB
if coder.target('MATLAB')
% Executing in MATLAB, call function myabsval
y = myabsval(y);
else
% Executing in the generated code.
% Call the initialize function before calling the
% C function for the first time
coder.ceval('myabsval_initialize');

% Call the generated C library function myabsval


y = coder.ceval('myabsval',y);

% Call the terminate function after


% calling the C function for the last time
coder.ceval('myabsval_terminate');
end

Convert callmyabsval.m to the MEX function callmyabsval_mex.

codegen -config:mex callmyabsval codegen/lib/myabsval/myabsval.lib...


codegen/lib/myabsval/myabsval.h

Run the MATLAB function callmyabsval .

callmyabsval

ans =

2.7500

Run the MEX function callmyabsval_mex which calls the library function myabsval.

callmyabsval_mex

ans =

2-124
coder.target

2.7500

Input Arguments
target — code generation target
string

Code generation target specified as one of the following strings:

'MATLAB' Running in MATLAB (not generating code)


'MEX' Generating a MEX function
'Sfun' Simulating a Simulink model
'Rtw' Generating a LIB, DLL, or EXE target
'HDL ' Generating an HDL target
'Custom' Generating a custom target

Example: tf = coder.target('MATLAB')
Data Types: char

See Also
coder.ceval

Introduced in R2011a

2-125
2 Function Reference

coder.typeof
Package: coder

Convert MATLAB value into its canonical type

Syntax
t = coder.typeof(v)
t = coder.typeof(v, sz, variable_dims)
t = coder.typeof(t)

Description
t = coder.typeof(v) creates a coder.Type object denoting the smallest nonconstant
type that contains v. v must be a MATLAB numeric, logical, char, enumeration or fixed-
point array, or a cell array or struct constructed from these types. Use coder.typeof
to specify only input parameter types. For example, use it with the codegen function
-args option or in a MATLAB Coder project when you are defining an input type by
example. Do not use it in MATLAB code from which you intend to generate code.

t = coder.typeof(v, sz, variable_dims) returns a modified copy of t =


coder.typeof(v) with (upper bound) size specified by sz and variable dimensions
variable_dims. If sz specifies inf for a dimension, then the size of the dimension is
unbounded and the dimension is variable size. When sz is [], the (upper bound) sizes of
v do not change. If you do not specify the variable_dims input parameter, the bounded
dimensions of the type are fixed. When variable_dims is a scalar, it is applied to
bounded dimensions or dimensions that are 1 or 0, which are fixed.

When v is a cell array whose elements have the same classes, but different sizes, if you
specify variable-size dimensions, coder.typeof creates a homogeneous cell array type.
If the elements have different classes, coder.typeof reports an error.

t = coder.typeof(t), where t is a coder.Type object, returns t itself.

2-126
coder.typeof

Input Arguments
sz

Size vector specifying each dimension of type object.

coder.Type object

MATLAB expression that describes the set of values represented by this type.

v must be a MATLAB numeric, logical, char, enumeration or fixed-point array, or a cell


array or struct constructed from the preceding types.

variable_dims

Logical vector that specifies whether each dimension is variable size (true) or fixed size
(false).

For a cell array, if the elements have different classes, you cannot specify variable-size
dimensions.

Output Arguments
t

coder.Type object

Examples
Create a type for a simple fixed-size 5x6 matrix of doubles.

coder.typeof(ones(5, 6))
% returns 5x6 double
coder.typeof(0, [5 6])
% also returns 5x6 double

2-127
2 Function Reference

Create a type for a variable-size matrix of doubles.


coder.typeof(ones(3,3), [], 1)
% returns :3 x :3 double
% ':' indicates variable-size dimensions

Create a type for a structure with a variable-size field.


x.a = coder.typeof(0,[3 5],1);
x.b = magic(3);
coder.typeof(x)
% Returns
% coder.StructType
% 1x1 struct
% a: :3x:5 double
% b: 3x3 double
% ':' indicates variable-size dimensions

Create a type for a homogeneous cell array with a variable-size field.


a = coder.typeof(0,[3 5],1);
b = magic(3);
coder.typeof({a b})
% Returns
% coder.CellType
% 1x2 homogeneous cell
% base: :3x:5 double
% ':' indicates variable-size dimensions

Create a type for a heterogeneous cell array.


a = coder.typeof('a');
b = coder.typeof(1);
coder.typeof({a b})
% Returns
% coder.CellType
% 1x2 heterogeneous cell
% f0: 1x1 char
% f1: 1x1 double

Create a variable-size homogeneous cell array type from a cell array that has the same
class but different sizes.

1 Create a type for a cell array that has two strings with different sizes. The cell array
type is heterogeneous.

2-128
coder.typeof

coder.typeof({'aa', 'bbb'})
% Returns
% coder.CellType
% 1x2 heterogeneous cell
% f0: 1x2 char
% f1: 1x3 char
2 Create a type using the same cell array input. This time, specify that the cell array
type has variable-size dimensions. The cell array type is homogeneous.
coder.typeof({'aa','bbb'},[1,10],[0,1])
% Returns
% coder.CellType
% 1x:10 homogeneous cell
% base: 1x:3 char

Create a type for a matrix with fixed-size and variable-size dimensions.


coder.typeof(0, [2,3,4], [1 0 1]);
% Returns :2x3x:4 double
% ':' indicates variable-size dimensions

coder.typeof(10, [1 5], 1)
% returns double 1 x :5
% ':' indicates variable-size dimensions

Create a type for a matrix of doubles, first dimension unbounded, second dimension with
fixed size.
coder.typeof(10,[inf,3])
% returns double:inf x 3
% ':' indicates variable-size dimensions

Create a type for a matrix of doubles, first dimension unbounded, second dimension with
variable size with an upper bound of 3.
coder.typeof(10, [inf,3],[0 1])
% returns double :inf x :3
% ':' indicates variable-size dimensions

Convert a fixed-size matrix to a variable-size matrix.


coder.typeof(ones(5,5), [], 1)
% returns double :5x:5
% ':' indicates variable-size dimensions

2-129
2 Function Reference

Create a nested structure (a structure as a field of another structure).


S = struct('a',double(0),'b',single(0))
SuperS.x = coder.typeof(S)
SuperS.y = single(0)
coder.typeof(SuperS)
% Returns
% coder.StructType
% SuperS: 1x1 struct
% with fields
% x: 1x1 struct
% with fields
% a: 1x1 double
% b: 1x1 single
% y: 1x1 single

Create a structure containing a variable-size array of structures as a field.


S = struct('a',double(0),'b',single(0))
SuperS.x = coder.typeof(S,[1 inf],[0 1])
SuperS.y = single(0)
coder.typeof(SuperS)
% Returns
% coder.StructType
% SuperS: 1x1 struct
% with fields
% x: 1x:inf struct
% with fields
% a: 1x1 double
% b: 1x1 single
% y: 1x1 single
% ':' indicates variable-size dimensions

Tips
• If you are already specifying the type of an input variable using a type function, do
not use coder.typeof unless you also want to specify the size. For instance, instead
of coder.typeof(single(0)), use the syntax single(0).
• For cell array types, coder.typeof determines whether the cell array type is
homogeneous or heterogeneous. If the cell array elements have the same class
and size, coder.typeof returns a homogeneous cell array type. If the elements
have different classes, coder.typeof returns a heterogeneous cell array type. For
some cell arrays, the classification as homogeneous or heterogeneous is ambiguous.

2-130
coder.typeof

For example, the type for {1 [2 3]} can be a 1x2 heterogeneous type where the first
element is double and the second element is 1x2 double. The type can also be a 1x3
homogeneous type in which the elements have class double and size 1x:2. For these
ambiguous cases, coder.typeof uses heuristics to classify the type as homogeneous
or heterogeneous. If you want a different classification, use the coder.CellType
makeHomogeneous or makeHeterogeneous methods to make a type with the
classification that you want. The makeHomogeneous method makes a homogeneous
copy of a type. The makeHeterogeneous method makes a heterogeneous copy of a
type.

The makeHomogeneous and makeHeterogeneous methods permanently assign the


classification as heterogeneous and homogeneous, respectively. You cannot later use
one of these methods to create a copy that has a different classification.

See Also
coder.CellType | | codegen | coder.ArrayType | coder.EnumType | coder.FiType
| coder.newtype | coder.PrimitiveType | coder.resize | coder.StructType |
coder.Type

Introduced in R2011a

2-131
2 Function Reference

coder.unroll
Package: coder

Copy body of for-loop in generated code for each iteration

Syntax
for i = coder.unroll(range)
for i = coder.unroll(range,flag)

Description
for i = coder.unroll(range) copies the body of a for-loop (unrolls a for-loop) in
generated code for each iteration specified by the bounds in range. i is the loop counter
variable.

for i = coder.unroll(range,flag) unrolls a for-loop as specified in range if


flag is true.

You must use coder.unroll in a for-loop header. coder.unroll modifies the


generated code, but does not change the computed results.

coder.unroll must be able to evaluate the bounds of the for-loop at compile time. The
number of iterations cannot exceed 1024; unrolling large loops can increase compile time
significantly and generate inefficient code

This function is ignored outside of code generation.

Input Arguments
flag

Boolean expression that indicates whether to unroll the for-loop:

true Unroll the for-loop

2-132
coder.unroll

false Do not unroll the for-loop

range

Specifies the bounds of the for-loop iteration:

init_val : end_val Iterate from init_val to end_val, using


an increment of 1
init_val : step_val : end_val Iterate from init_val to end_val, using
step_val as an increment if positive or as
a decrement if negative
Matrix variable Iterate for a number of times equal to the
number of columns in the matrix

Examples
To limit the number of times to copy the body of a for-loop in generated code:

1 Write a MATLAB function getrand(n) that uses a for-loop to generate a vector


of length n and assign random numbers to specific elements. Add a test function
test_unroll. This function calls getrand(n) with n equal to values both less than
and greater than the threshold for copying the for-loop in generated code.

function [y1, y2] = test_unroll() %#codegen


% The directive %#codegen indicates that the function
% is intended for code generation
% Calling getrand 8 times triggers unroll
y1 = getrand(8);
% Calling getrand 50 times does not trigger unroll
y2 = getrand(50);

function y = getrand(n)
% Turn off inlining to make
% generated code easier to read
coder.inline('never');

% Set flag variable dounroll to repeat loop body


% only for fewer than 10 iterations
dounroll = n < 10;
% Declare size, class, and complexity

2-133
2 Function Reference

% of variable y by assignment
y = zeros(n, 1);
% Loop body begins
for i = coder.unroll(1:2:n, dounroll)
if (i > 2) && (i < n-2)
y(i) = rand();
end;
end;
% Loop body ends
2 In the default output folder, codegen/lib/test_unroll, generate C static library
code for test_unroll :

codegen -config:lib test_unroll

In test_unroll.c, the generated C code for getrand(8) repeats the body of the
for-loop (unrolls the loop) because the number of iterations is less than 10:

static void getrand(double y[8])


{
/* Turn off inlining to make */
/* generated code easier to read */
/* Set flag variable dounroll to repeat loop body */
/* only for fewer than 10 iterations */
/* Declare size, class, and complexity */
/* of variable y by assignment */
memset(&y[0], 0, sizeof(double) << 3);

/* Loop body begins */


y[2] = b_rand();
y[4] = b_rand();

/* Loop body ends */


}

The generated C code for getrand(50) does not unroll the for-loop because the
number of iterations is greater than 10:

static void b_getrand(double y[50])


{
int i;
int b_i;

/* Turn off inlining to make */


/* generated code easier to read */

2-134
coder.unroll

/* Set flag variable dounroll to repeat loop body */


/* only for fewer than 10 iterations */
/* Declare size, class, and complexity */
/* of variable y by assignment */
memset(&y[0], 0, 50U * sizeof(double));

/* Loop body begins */


for (i = 0; i < 25; i++) {
b_i = (i << 1) + 1;
if ((b_i > 2) && (b_i < 48)) {
y[b_i - 1] = b_rand();
}
}

More About
• “Using Logicals in Array Indexing”
• “Unroll for-Loops”

See Also
coder.inline | coder.nullcopy | for | |

Introduced in R2011a

2-135
2 Function Reference

coder.updateBuildInfo
Update build information object RTW.BuildInfo

Syntax
coder.updateBuildInfo('addCompileFlags',options)
coder.updateBuildInfo('addLinkFlags',options)
coder.updateBuildInfo('addDefines',options)
coder.updateBuildInfo( ___ ,group)

coder.updateBuildInfo('addLinkObjects',filename,path)
coder.updateBuildInfo('addLinkObjects',filename,path, priority,
precompiled)
coder.updateBuildInfo('addLinkObjects',filename,path, priority,
precompiled,linkonly)
coder.updateBuildInfo( ___ ,group)

coder.updateBuildInfo('addNonBuildFiles',filename)
coder.updateBuildInfo('addSourceFiles',filename)
coder.updateBuildInfo('addIncludeFiles',filename)
coder.updateBuildInfo( ___ ,path)
coder.updateBuildInfo( ___ ,path,group)

coder.updateBuildInfo('addSourcePaths',path)
coder.updateBuildInfo('addIncludePaths',path)
coder.updateBuildInfo( ___ ,group)

Description
coder.updateBuildInfo('addCompileFlags',options) adds compiler options to
the build information object.

coder.updateBuildInfo('addLinkFlags',options) adds link options to the build


information object.

coder.updateBuildInfo('addDefines',options) adds preprocessor macro


definitions to the build information object.

2-136
coder.updateBuildInfo

coder.updateBuildInfo( ___ ,group) assigns a group name to options for later


reference.

coder.updateBuildInfo('addLinkObjects',filename,path) adds a link object


from a file to the build information object.

coder.updateBuildInfo('addLinkObjects',filename,path, priority,
precompiled) specifies if the link object is precompiled.

coder.updateBuildInfo('addLinkObjects',filename,path, priority,
precompiled,linkonly) specifies if the object is to be built before being linked or used
for linking alone. If the object is to be built, it specifies if the object is precompiled.

coder.updateBuildInfo( ___ ,group) assigns a group name to the link object for
later reference.

coder.updateBuildInfo('addNonBuildFiles',filename) adds a nonbuild-related


file to the build information object.

coder.updateBuildInfo('addSourceFiles',filename) adds a source file to the


build information object.

coder.updateBuildInfo('addIncludeFiles',filename) adds an include file to


the build information object.

coder.updateBuildInfo( ___ ,path) adds the file from specified path.

coder.updateBuildInfo( ___ ,path,group) assigns a group name to the file for


later reference.

coder.updateBuildInfo('addSourcePaths',path) adds a source file path to the


build information object.

coder.updateBuildInfo('addIncludePaths',path) adds an include file path to


the build information object.

coder.updateBuildInfo( ___ ,group) assigns a group name to the path for later
reference.

2-137
2 Function Reference

Examples
Add Multiple Compiler Options

Add the compiler options -Zi and -Wall during code generation for function, func.

Anywhere in the MATLAB code for func, add the following line:

coder.updateBuildInfo('addCompileFlags','-Zi -Wall');

Generate code for func using the codegen command. Open the Code Generation Report.

codegen -config:lib -launchreport func

You can see the added compiler options under the Target Build Log tab in the Code
Generation Report.

Add Source File Name

Add a source file to the project build information while generating code for a function,
calc_factorial.

1 Write a header file fact.h that declares a C function factorial.

double factorial(double x);

fact.h will be included as a header file in generated code. This inclusion ensures
that the function is declared before it is called.

Save the file in the current folder.


2 Write a C file fact.c that contains the definition of factorial. factorial
calculates the factorial of its input.

#include "fact.h"

double factorial(double x)
{
int i;
double fact = 1.0;
if (x == 0 || x == 1) {
return 1.0;
} else {
for (i = 1; i <= x; i++) {

2-138
coder.updateBuildInfo

fact *= (double)i;
}
return fact;
}
}

fact.c is used as a source file during code generation.

Save the file in the current folder.


3 Write a MATLAB function calc_factorial that uses coder.ceval to call the
external C function factorial.

Use coder.updateBuildInfo with option 'addSourceFiles' to add the source


file fact.c to the build information. Use coder.cinclude to include the header
file fact.h in the generated code.

function y = calc_factorial(x) %#codegen

coder.cinclude('fact.h');
coder.updateBuildInfo('addSourceFiles', 'fact.c');

y = 0;
y = coder.ceval('factorial', x);
4 Generate code for calc_factorial using the codegen command.

codegen -config:dll -launchreport calc_factorial -args 0

In the Code Generation Report, on the C Code tab, you can see the added source file
fact.c.

Add Link Object

Add a link object LinkObj.lib to the build information while generating code for a
function func. For this example, you must have a link object LinkObj.lib saved in a
local folder, for example, c:\Link_Objects.

Anywhere in the MATLAB code for func, add the following lines:

libPriority = '';
libPreCompiled = true;
libLinkOnly = true;
libName = 'LinkObj.lib';

2-139
2 Function Reference

libPath = 'c:\Link_Objects';
coder.updateBuildInfo('addLinkObjects', libName, libPath, ...
libPriority, libPreCompiled, libLinkOnly);

Generate a MEX function for func using the codegen command. Open the Code
Generation Report.
codegen -launchreport func

You can see the added link object under the Target Build Log tab in the Code
Generation Report.

Add Include Paths

Add an include path to the build information while generating code for a function, adder.
Include a header file, adder.h, existing on the path.

When header files do not reside in the current folder, to include them, use this method:

1 Write a header file mysum.h that contains the declaration for a C function mysum.
double mysum(double, double);

Save it in a local folder, for example c:\coder\myheaders.


2 Write a C file mysum.c that contains the definition of the function mysum.
#include "mysum.h"

double mysum(double x, double y)


{
return(x+y);
}

Save it in the current folder.


3 Write a MATLAB function adder that adds the path c:\coder\myheaders to the
build information.

Use coder.cinclude to include the header file mysum.h in the generated code.
function y = adder(x1, x2) %#codegen
coder.updateBuildInfo('addIncludePaths','c:\coder\myheaders');
coder.updateBuildInfo('addSourceFiles','mysum.c');
%Include the source file containing C function definition

2-140
coder.updateBuildInfo

coder.cinclude('mysum.h');
y = 0;
if coder.target('MATLAB')
% This line ensures that the function works in MATLAB
y = x1 + x2;
else
y = coder.ceval('mysum', x1, x2);
end
end
4 Generate code for adder using the codegen command.

codegen -config:lib -launchreport adder -args {0,0}

Open the Code Generation Report. The header file adder.h is included in the
generated code.

Input Arguments
options — Build options
string

Build options, specified as a string. The string must be a compile-time constant.

Depending on the leading argument, options specifies the relevant build options to be
added to the project’s build information.

Leading Argument Values in options


'addCompileFlags' Compiler options
'addLinkFlags' Link options
'addDefines' Preprocessor macro definitions

The function adds the options to the end of an option vector.


Example: coder.updateBuildInfo('addCompileFlags','-Zi -Wall')

group — Group name


string

Name of user-defined group, specified as a string. The string must be a compile-time


constant.

2-141
2 Function Reference

The group option assigns a group name to the parameters in the second argument.

Leading Argument Second Argument Parameters Named by group


'addCompileFlags' options Compiler options
'addLinkFlags' options Link options
'addLinkObjects' filename Name of file containing
linkable objects
'addNonBuildFiles' filename Name of nonbuild-related file
'addSourceFiles' filename Name of source file
'addSourcePaths' path Name of source file path

You can use group to:

• Document the use of specific parameters.


• Retrieve or apply multiple parameters together as one group.

filename — File name


string

File name, specified as a string. The string must be a compile-time constant.

Depending on the leading argument, filename specifies the relevant file to be added to
the project’s build information.

Leading Argument File Specified by filename


'addLinkObjects' File containing linkable objects
'addNonBuildFiles' Nonbuild-related file
'addSourceFiles' Source file

The function adds the file name to the end of a file name vector.

path — Full path name


string

Full path name, specified as a string. The string must be a compile-time constant.

Depending on the leading argument, path specifies the relevant path name to be added
to the project’s build information.

2-142
coder.updateBuildInfo

Leading Argument Path Specified by path


'addLinkObjects' Path to linkable objects
'addNonBuildFiles' Path to nonbuild-related files
'addSourceFiles', 'addSourcePaths' Path to source files

The function adds the path to the end of a path name vector.

priority — Relative priority of link object


''

Priority of link objects.

This feature applies only when several link objects are added. Currently, only a single
link object file can be added for every coder.updateBuildInfo statement. Therefore,
this feature is not available for use.

To use the succeeding arguments, include '' as a placeholder argument.

precompiled — Variable indicating if link objects are precompiled


logical value

Variable indicating if the link objects are precompiled, specified as a logical value. The
value must be a compile-time constant.

If the link object has been prebuilt for faster compiling and linking and exists in a
specified location, specify true. Otherwise, the MATLAB Coder build process creates the
link object in the build folder.

If linkonly is set to true, this argument is ignored.


Data Types: logical

linkonly — Variable indicating if objects must be used for linking only


logical value

Variable indicating if objects must be used for linking only, specified as a logical value.
The value must be a compile-time constant.

If you want that the MATLAB Coder build process must not build or generate rules in
the makefile for building the specified link object, specify true. Instead, when linking
the final executable, the process should just include the object. Otherwise, rules for
building the link object are added to the makefile.

2-143
2 Function Reference

You can use this argument to incorporate link objects for which source files are not
available.

If linkonly is set to true, the value of precompiled is ignored.


Data Types: logical

More About
• “Customize the Post-Code-Generation Build Process”

Introduced in R2013b

2-144
coder.varsize

coder.varsize
Package: coder

Declare variable-size array

Syntax
coder.varsize('var1', 'var2', ...)
coder.varsize('var1', 'var2', ..., ubound)
coder.varsize('var1', 'var2', ..., ubound, dims)
coder.varsize('var1', 'var2', ..., [], dims)

Description
coder.varsize('var1', 'var2', ...) declares one or more variables as variable-
size data, allowing subsequent assignments to extend their size. Each 'varn' must
be a quoted string that represents a variable or structure field. If the structure field
belongs to an array of structures, use colon (:) as the index expression to make
the field variable-size for all elements of the array. For example, the expression
coder.varsize('data(:).A') declares that the field A inside each element of data is
variable sized.

coder.varsize('var1', 'var2', ..., ubound) declares one or more variables


as variable-size data with an explicit upper bound specified in ubound. The argument
ubound must be a constant, integer-valued vector of upper bound sizes for every
dimension of each 'varn'. If you specify more than one 'varn', each variable must have
the same number of dimensions.

coder.varsize('var1', 'var2', ..., ubound, dims) declares one or more


variables as variable size with an explicit upper bound and a mix of fixed and varying
dimensions specified in dims. The argument dims is a logical vector, or double vector
containing only zeros and ones. Dimensions that correspond to zeros or false in dims
have fixed size; dimensions that correspond to ones or true vary in size. If you specify
more than one variable, each fixed dimension must have the same value across all
'varn'.

2-145
2 Function Reference

coder.varsize('var1', 'var2', ..., [], dims) declares one or more variables


as variable size with a mix of fixed and varying dimensions. The empty vector [] means
that you do not specify an explicit upper bound.

When you do not specify ubound, the upper bound is computed for each 'varn' in
generated code.

When you do not specify dims, dimensions are assumed to be variable except the
singleton ones. A singleton dimension is a dimension for which size(A,dim) = 1.

You must add the coder.varsize declaration before each 'varn' is used (read). You
can add the declaration before the first assignment to each 'varn'. However, for a cell
array element, the coder.varsize declaration must follow the first assignment to the
element. For example:
...
x = cell(3, 3);
x{1} = [1 2];
coder.varsize('x{1}');
...

You cannot use coder.varsize outside the MATLAB code intended for code generation.
For example, the following code does not declare the variable, var, as variable-size data:
coder.varsize('var',10);
codegen -config:lib MyFile -args var

Instead, include the coder.varsize statement inside MyFile to declare var as


variable-size data. Alternatively, you can use coder.typeof to declare var as variable-
size outside MyFile. It can then be passed to MyFile during code generation using the -
args option. For more information, see coder.typeof.

Examples
Develop a Simple Stack That Varies in Size up to 32 Elements as You Push and Pop Data at Run
Time.

Write primary function test_stack to issue commands for pushing data on and popping
data from a stack.
function test_stack %#codegen
% The directive %#codegen indicates that the function

2-146
coder.varsize

% is intended for code generation


stack('init', 32);
for i = 1 : 20
stack('push', i);
end
for i = 1 : 10
value = stack('pop');
% Display popped value
value
end
end

Write local function stack to execute the push and pop commands.
function y = stack(command, varargin)
persistent data;
if isempty(data)
data = ones(1,0);
end
y = 0;
switch (command)
case {'init'}
coder.varsize('data', [1, varargin{1}], [0 1]);
data = ones(1,0);
case {'pop'}
y = data(1);
data = data(2:size(data, 2));
case {'push'}
data = [varargin{1}, data];
otherwise
assert(false, ['Wrong command: ', command]);
end
end

The variable data is the stack. The statement coder.varsize('data', [1,


varargin{1}], [0 1]) declares that:

• data is a row vector


• Its first dimension has a fixed size
• Its second dimension can grow to an upper bound of 32

Generate a MEX function for test_stack:


codegen -config:mex test_stack

2-147
2 Function Reference

codegen generates a MEX function in the current folder.

Run test_stack_mex to get these results:

value =
20

value =
19

value =
18

value =
17

value =
16

value =
15

value =
14

value =
13

value =
12

value =
11

At run time, the number of items in the stack grows from zero to 20, and then shrinks to
10.

Declare a Variable-Size Structure Field.

Write a function struct_example that declares an array data, where each element is a
structure that contains a variable-size field:

function y=struct_example() %#codegen

2-148
coder.varsize

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 statement coder.varsize('data(:).values') marks as variable-size the field


values inside each element of the matrix data.

Generate a MEX function for struct_example:


codegen -config:mex struct_example

Run struct_example.

Each time you run struct_example you get a different answer because the function
loads the array with random numbers.

Make a Cell Array Variable Size

Write the function make_varsz_cell that defines a local cell array variable c whose
elements have the same class, but different sizes. Use coder.varsize to indicate that c
has variable size.
function y = make_varsz_cell()
c = {1 [2 3]};
coder.varsize('c', [1 3], [0 1]);
y = c;
end

Generate a C static library.


codegen -config:lib make_varsz_cell -report

In the report, view the MATLAB variables.

2-149
2 Function Reference

c is a 1x:3 homogeneous cell array whose elements are 1x:2 double.

• “Generate Code for Variable-Size Data”


• “Defining Variable-Size Structure Fields”
• “Defining Variable-Size Global Data”
• “Incompatibilities with MATLAB in Variable-Size Support for Code Generation”

Limitations
• If you use the cell function to create a cell array, you cannot use coder.varsize
with that cell array.
• If you use coder.varsize with a cell array element, the coder.varsize
declaration must follow the first assignment to the element. For example:

...
x = cell(3, 3);
x{1} = [1 2];
coder.varsize('x{1}');
...
• You cannot use coder.varsize with a cell array input that is heterogeneous.
• You cannot use coder.varsize with global variables.
• You cannot use coder.varsize with MATLAB class properties.

More About
Tips

• If you use input variables (or result of a computation using input variables) to specify
the size of an array, it is declared as variable-size in the generated code. Do not use
coder.varsize on the array again, unless you also want to specify an upper bound
for its size.
• Using coder.varsize on an array without explicit upper bounds causes dynamic
memory allocation of the array. This dynamic memory allocation can reduce the
speed of generated code. To avoid dynamic memory allocation, use the syntax
coder.varsize('var1', 'var2', ..., ubound) to specify an upper bound for
the array size (if you know it in advance).

2-150
coder.varsize

• A cell array can be variable size only if it is homogeneous. When you use
coder.varsize with a cell array, the code generation software tries to make the cell
array homogeneous. It tries to find a class and size that apply to all elements of the
cell array. For example, if the first element is double and the second element is 1x2
double, all elements can be represented as 1x:2 double. If the code generation software
cannot find a common class and size, code generation fails. For example, suppose that
the first element of a cell array is char and the second element is double. The code
generation software cannot find a class that can represent both elements.

• “Homogeneous vs. Heterogeneous Cell Arrays”

See Also
codegen | size | varargin

Introduced in R2011a

2-151
2 Function Reference

coder.wref
Package: coder

Pass argument by reference as write-only output

Syntax
[y =] coder.ceval('function_name', coder.wref(argO), ... un);

Arguments
argO
Variable passed by reference as a write-only output to the external C/C++ function
called in coder.ceval.

Description
[y =] coder.ceval('function_name', coder.wref(argO), ... un); passes
the variable argO by reference as a write-only output to the external C/C++ function
called in coder.ceval. You add coder.wref inside coder.ceval as an argument to
function_name. The argument list can contain multiple coder.wref constructs. Add
a separate coder.wref construct for each write-only argument that you want to pass by
reference to function_name.

Caution The generated code assumes that a variable passed by coder.wref is write-
only and optimizes the code accordingly. Consequently, the C/C++ function must write to
the variable. If the variable is a vector or matrix, the C/C++ function must write to every
element of the variable. Otherwise, results are unpredictable.

Only use coder.wref in MATLAB code that you have compiled with codegen.
coder.wref generates an error in uncompiled MATLAB code.

2-152
coder.wref

Examples
In the following example, a MATLAB function fcn has a single input u and a single
output y, a 5-by-10 matrix. fcn calls a C function init to initialize the matrix, passing y
by reference as a write-only output. Here is the MATLAB function code:

function y = fcn(u)
%#codegen
y = zeros(5,10);
coder.ceval('init', coder.wref(y));

The C function prototype for init must be as follows:

void init(double *x);

In this example:

• Although the C function is void, coder.wref allows it to access, modify, and return a
matrix to the MATLAB function.
• The C function prototype defines the output as a pointer because it is passed by
reference.
• For C/C++ code generation, you must set the type of the output y explicitly—in this
case to a matrix of type double.
• The generated code collapses matrices to a single dimension.

See Also
coder.ceval | coder.ref | coder.rref

Introduced in R2011a

2-153
2 Function Reference

parfor
Parallel for-loop

Syntax
parfor LoopVar = InitVal:EndVal; Statements; end
parfor (LoopVar = InitVal:EndVal, NumThreads); Statements; end

Description
parfor LoopVar = InitVal:EndVal; Statements; end creates a loop in a
generated MEX function or in C/C++ code that runs in parallel on shared-memory
multicore platforms.

The parfor-loop executes the Statements for values of LoopVar between InitVal and
Endval. LoopVar specifies a vector of integer values increasing by 1.

parfor (LoopVar = InitVal:EndVal, NumThreads); Statements; end uses a


maximum of NumThreads threads when creating a parallel for-loop.

Examples
Generate MEX for parfor

Generate a MEX function for a parfor-loop to execute on the maximum number of cores
available.

Write a MATLAB function, test_parfor, that calls the fast Fourier transform function,
fft, in a parfor-loop. Because the loop iterations run in parallel, this evaluation can be
completed much faster than an analogous for-loop.

function a = test_parfor %#codegen


a=ones(10,256);
r=rand(10,256);
parfor i=1:10

2-154
parfor

a(i,:)=real(fft(r(i)));
end

Generate a MEX function for test_parfor. At the MATLAB command line, enter:

codegen test_parfor

codegen generates a MEX function, test_parfor_mex, in the current folder.

Run the MEX function. At the MATLAB command line, enter:

test_parfor_mex

The MEX function runs using the available cores.

Specify Maximum Number of Threads for parfor

Specify the maximum number of threads when generating a MEX function for a parfor-
loop.

Write a MATLAB function, specify_num_threads, that uses input, u, to specify the


maximum number of threads in the parfor-loop.

function y = specify_num_threads(u) %#codegen


y = ones(1,100);
% u specifies maximum number of threads
parfor (i = 1:100,u)
y(i) = i;
end
end

Generate a MEX function for specify_num_threads. Use -args 0 to specify the type
of the input. At the MATLAB command line, enter:

% -args 0 specifies that input u is a scalar double


% u is typecast to an integer by the code generation software
codegen -report specify_num_threads -args 0

codegen generates a MEX function, specify_num_threads_mex, in the current folder.

Run the MEX function, specifying that it run in parallel on at most four threads. At the
MATLAB command line, enter:

specify_num_threads_mex(4)

2-155
2 Function Reference

The generated MEX function runs on up to four cores. If fewer than four cores are
available, the MEX function runs on the maximum number of cores available at the time
of the call.

Generate MEX for parfor Without Parallelization

Disable parallelization before generating a MEX function for a parfor-loop.

Write a MATLAB function, test_parfor, that calls the fast Fourier transform function,
fft, in a parfor-loop.
function a = test_parfor %#codegen
a=ones(10,256);
r=rand(10,256);
parfor i=1:10
a(i,:)=real(fft(r(i)));
end

Generate a MEX function for test_parfor. Disable the use of OpenMP so that codegen
does not generate a MEX function that can run on multiple threads.
codegen -O disable:OpenMP test_parfor

codegen generates a MEX function, test_parfor_mex, in the current folder.

Run the MEX function.


test_parfor_mex

The MEX function runs on a single thread.

If you disable parallelization, MATLAB Coder treats parfor-loops as for-loops. The


software generates a MEX function that runs on a single thread. Disable parallelization
to compare performance of the serial and parallel versions of the generated MEX function
or C/C++ code. You can also disable parallelization to debug issues with the parallel
version.

• “Generate Code with Parallel for-Loops (parfor)”

Input Arguments
LoopVar — Loop index
integer

2-156
parfor

Loop index variable whose initial value is InitVal and final value is EndVal.

InitVal — Initial value of loop index


integer

Initial value for loop index variable, Loopvar. With EndVal, specifies the parfor range
vector, which must be of the form M:N.

EndVal — Final value of loop index


integer

Final value for loop index variable, LoopVar. With InitVal, specifies the parfor range
vector, which must be of the form M:N.

Statements — Loop body


strings, separated by semicolon or newline

The series of MATLAB commands to execute in the parfor-loop.

If you put more than one statement on the same line, separate the statements with
semicolons. For example:
parfor i=1:10
arr(i) = rand(); arr(i) = 2*arr(i)-1;
end

NumThreads — Maximum number of threads running in parallel


number of available cores (default) | nonnegative integer

Maximum number of threads to use. If you specify the upper limit, MATLAB Coder uses
no more than this number, even if additional cores are available. If you request more
threads than the number of available cores, MATLAB Coder uses the maximum number
of cores available at the time of the call. If the loop iterations are fewer than the threads,
some threads perform no work.

If the parfor-loop cannot run on multiple threads (for example, if only one core is
available or NumThreads is 0), MATLAB Coder executes the loop in a serial manner.

Limitations
• You must use a compiler that supports the Open Multiprocessing (OpenMP)
application interface. See http://www.mathworks.com/support/compilers/

2-157
2 Function Reference

current_release/. If you use a compiler that does not support OpenMP, MATLAB
Coder treats the parfor-loops as for-loops. In the generated MEX function or C/C++
code, the loop iterations run on a single thread.
• Do not use the following constructs inside parfor loops:

• You cannot call extrinsic functions using coder.extrinsic in the body of a


parfor-loop.
• You cannot write to a global variable inside a parfor-loop.
• MATLAB Coder does not support the use of coder.ceval in reductions. For
example, you cannot generate code for the following parfor-loop:

parfor i=1:4
y=coder.ceval('myCFcn',y,i);
end
Instead, write a local function that calls the C code using coder.ceval and call
this function in the parfor-loop. For example:

parfor i=1:4
y = callMyCFcn(y,i);
end
function y = callMyCFcn(y,i)
y = coder.ceval('mCyFcn', y , i);
end
• You cannot use varargin or varargout in parfor-loops.
• The type of the loop index must be representable by an integer type on the target
hardware. Use a type that does not require a multiword type in the generated code.
• parfor for standalone code generation requires the toolchain approach for building
executables or libraries. Do not change settings that cause the code generation
software to use the template makefile approach. See “Project or Configuration is
Using the Template Makefile”.

For a comprehensive list of restrictions, see “parfor Restrictions”.

More About
Tips

• Use a parfor-loop when:

2-158
parfor

• You need many loop iterations of a simple calculation. parfor divides the loop
iterations into groups so that each thread can execute one group of iterations.
• You have loop iterations that take a long time to execute.
• Do not use a parfor-loop when an iteration in your loop depends on the results of
other iterations.

Reductions are one exception to this rule. A reduction variable accumulates a value
that depends on all the iterations together, but is independent of the iteration order.

• “Algorithm Acceleration Using Parallel for-Loops (parfor)”


• “Control Compilation of parfor-Loops”
• “When to Use parfor-Loops”
• “When Not to Use parfor-Loops”
• “Classification of Variables in parfor-Loops”

See Also
Functions
codegen

Introduced in R2012b

2-159
2 Function Reference

addOption
Class: coder.make.BuildConfiguration
Package: coder.make

Add new option

Syntax
h.addOption(OptionName, buildItemHandle)

Description
h.addOption(OptionName, buildItemHandle) adds an option to
coder.make.BuildConfiguration.Options.

Tips
Before using addOption, create a coder.make.BuildItem object to use as the second
argument.

Input Arguments
h — BuildConfiguration handle
object handle

BuildConfiguration handle, specified as a coder.make.BuildConfiguration object.


Example: h

OptionName — Name of option


new option name

Name of option, specified as a string. Choose a new option name.


Example: 'faster2'

2-160
addOption

Data Types: char

buildItemHandle — BuildItem handle


object handle

BuildItem handle, specified as a coder.make.BuildItem object that contains an option


value.
Example: bi

Examples

Using the Option-related methods interactively


tc = coder.make.ToolchainInfo;
cfg = tc.getBuildConfiguration('Faster Builds');
cfg.isOption('X Compiler')

ans =

bi = coder.make.BuildItem('WV','wrongvalue')

bi =

Macro : WV
Value : wrongvalue

cfg.addOption('X Compiler',bi);
value = cfg.getOption('X Compiler')

value =

Macro : WV
Value : wrongvalue

cfg.setOption('X Compiler','rightvalue');
value = cfg.getOption('X Compiler')

value =

Macro : WV

2-161
2 Function Reference

Value : rightvalue

See Also
coder.make.BuildConfiguration.getOption |
coder.make.BuildConfiguration.isOption |
coder.make.BuildConfiguration.setOption | coder.make.BuildItem

2-162
getOption

getOption
Class: coder.make.BuildConfiguration
Package: coder.make

Get value of option

Syntax
OptionValue = h.getOption(OptionName)

Description
OptionValue = h.getOption(OptionName) returns the value and optional macro
name of a build configuration option.

Input Arguments
h — BuildConfiguration handle
object handle

BuildConfiguration handle, specified as a coder.make.BuildConfiguration object.


Example: h

OptionName — Name of option


new option name

Name of option, specified as a string. Choose a new option name.


Example: 'faster2'
Data Types: char

Output Arguments
OptionValue — Value of option
coder.make.BuildItem object

2-163
2 Function Reference

Value of the option, returned as a coder.make.BuildItem object that contains a value


and an optional macro name.

Examples
Using the Option-related methods interactively
tc = coder.make.ToolchainInfo;
cfg = tc.getBuildConfiguration('Faster Builds');
cfg.isOption('X Compiler')

ans =

bi = coder.make.BuildItem('WV','wrongvalue')

bi =

Macro : WV
Value : wrongvalue

cfg.addOption('X Compiler',bi);
value = cfg.getOption('X Compiler')

value =

Macro : WV
Value : wrongvalue

cfg.setOption('X Compiler','rightvalue');
value = cfg.getOption('X Compiler')

value =

Macro : WV
Value : rightvalue

See Also
coder.make.BuildConfiguration.addOption |
coder.make.BuildConfiguration.isOption |
coder.make.BuildConfiguration.setOption

2-164
info

info
Class: coder.make.BuildConfiguration
Package: coder.make

Get information about build configuration

Syntax
h.info
OutputInfo = h.info

Description
h.info displays information about the coder.make.BuildConfiguration object in
the MATLAB Command Window.

OutputInfo = h.info returns information about the


coder.make.BuildConfiguration object

Input Arguments
h — BuildConfiguration handle
object handle

BuildConfiguration handle, specified as a coder.make.BuildConfiguration object.


Example: h

Output Arguments
OutputInfo — Build configuration information
character string

Build configuration information, returned as a character string.

2-165
2 Function Reference

Examples
The intel_tc.m file from “Adding a Custom Toolchain”, uses the following lines to
display information about the BuildConfiguration property:

tc = intel_tc
cfg = tc.getBuildConfiguration('Faster Builds');
cfg.info
##############################################
# Build Configuration : Faster Builds
# Description : Default settings for faster compile/link of code
##############################################

ARFLAGS = /nologo
CFLAGS = $(cflags) $(CVARSFLAG) $(CFLAGS_ADDITIONAL) /c /Od
CPPFLAGS = $(cflags) $(CVARSFLAG) $(CPPFLAGS_ADDITIONAL) /c /Od
DOWNLOAD_FLAGS =
EXECUTE_FLAGS =
LDFLAGS = $(ldebug) $(conflags) $(LIBS_TOOLCHAIN)
MEX_CFLAGS =
MEX_LDFLAGS =
MAKE_FLAGS = -f $(MAKEFILE)
SHAREDLIB_LDFLAGS = $(ldebug) $(conflags) $(LIBS_TOOLCHAIN) -dll -def:$(DEF_FILE)

2-166
isOption

isOption
Class: coder.make.BuildConfiguration
Package: coder.make

Determine if option exists

Syntax
OutputValue = isOption(OptionName)

Description
OutputValue = isOption(OptionName) returns '1' (true) if the specified option
exists. Otherwise, it returns '0' (false).

Input Arguments
h — BuildConfiguration handle
object handle

BuildConfiguration handle, specified as a coder.make.BuildConfiguration object.


Example: h

OptionName — Name of option


new option name

Name of option, specified as a string. Choose a new option name.


Example: 'faster2'
Data Types: char

Output Arguments
OutputValue — Option exists
0|1

2-167
2 Function Reference

Option exists, returned as a logical value. If the option exists, the value is '1' (true).
Otherwise, the output is '0' (false).

Examples
Using the Option-related methods interactively
tc = coder.make.ToolchainInfo;
cfg = tc.getBuildConfiguration('Faster Builds');
cfg.isOption('X Compiler')

ans =

bi = coder.make.BuildItem('WV','wrongvalue')

bi =

Macro : WV
Value : wrongvalue

cfg.addOption('X Compiler',bi);
value = cfg.getOption('X Compiler')

value =

Macro : WV
Value : wrongvalue

cfg.setOption('X Compiler','rightvalue');
value = cfg.getOption('X Compiler')

value =

Macro : WV
Value : rightvalue

See Also
coder.make.BuildConfiguration.addOption |
coder.make.BuildConfiguration.getOption |
coder.make.BuildConfiguration.setOption | coder.make.BuildItem

2-168
keys

keys
Class: coder.make.BuildConfiguration
Package: coder.make

Get all option names

Syntax
Out = h.keys

Description
Out = h.keys returns a list of all option names or keys in the build configuration.

Input Arguments
h — BuildConfiguration handle
object handle

BuildConfiguration handle, specified as a coder.make.BuildConfiguration object.


Example: h

Output Arguments
Output — List of all option names or keys in build configuration
cell array of strings

List of all option names or keys in build configuration, returned as a cell array of strings.

Examples
The intel_tc.m file from “Adding a Custom Toolchain”, uses the following lines to
display keys from the BuildConfiguration property:

2-169
2 Function Reference

tc = intel_tc
cfg = tc.getBuildConfiguration('Faster Builds');
cfg.keys

ans =

Columns 1 through 5

'Archiver' 'C Compiler' 'C++ Compiler' 'Download' 'Execute'

Columns 6 through 10

'Linker' 'MEX Compiler' 'MEX Linker' 'Make Tool' [1x21 char]

2-170
setOption

setOption
Class: coder.make.BuildConfiguration
Package: coder.make

Set value of option

Syntax
h.setOption(OptionName, OptionValue)

Description
h.setOption(OptionName, OptionValue) updates the values within a
coder.make.BuildConfiguration object.

Input Arguments
h — BuildConfiguration handle
object handle

BuildConfiguration handle, specified as a coder.make.BuildConfiguration object.


Example: h

OptionName — Name of option


new option name

Name of option, specified as a string. Choose a new option name.


Example: 'faster2'
Data Types: char

OptionValue — Value of option


string or object handle

2-171
2 Function Reference

Value of option, specified as a character string, or as the handle of a


coder.make.BuildItem object that contains an option value.
Example: linkerOpts

Examples

The setOption method in intel_tc


The intel_tc.m file from “Adding a Custom Toolchain”, gets a default
BuildConfiguration object and then uses setOption to update the values in that
object:
% --------------------------------------------
% BUILD CONFIGURATIONS
% --------------------------------------------

optimsOffOpts = {'/c /Od'};


optimsOnOpts = {'/c /O2'};
cCompilerOpts = '$(cflags) $(CVARSFLAG) $(CFLAGS_ADDITIONAL)';
cppCompilerOpts = '$(cflags) $(CVARSFLAG) $(CPPFLAGS_ADDITIONAL)';
linkerOpts = {'$(ldebug) $(conflags) $(LIBS_TOOLCHAIN)'};
sharedLinkerOpts = horzcat(linkerOpts,'-dll -def:$(DEF_FILE)');
archiverOpts = {'/nologo'};

% Get the debug flag per build tool


debugFlag.CCompiler = '$(CDEBUG)';
debugFlag.CppCompiler = '$(CPPDEBUG)';
debugFlag.Linker = '$(LDDEBUG)';
debugFlag.Archiver = '$(ARDEBUG)';

cfg = tc.getBuildConfiguration('Faster Builds');


cfg.setOption('C Compiler',horzcat(cCompilerOpts,optimsOffOpts));
cfg.setOption('C++ Compiler',horzcat(cppCompilerOpts,optimsOffOpts));
cfg.setOption('Linker',linkerOpts);
cfg.setOption('Shared Library Linker',sharedLinkerOpts);
cfg.setOption('Archiver',archiverOpts);

cfg = tc.getBuildConfiguration('Faster Runs');


cfg.setOption('C Compiler',horzcat(cCompilerOpts,optimsOnOpts));
cfg.setOption('C++ Compiler',horzcat(cppCompilerOpts,optimsOnOpts));
cfg.setOption('Linker',linkerOpts);
cfg.setOption('Shared Library Linker',sharedLinkerOpts);
cfg.setOption('Archiver',archiverOpts);

cfg = tc.getBuildConfiguration('Debug');
cfg.setOption('C Compiler',horzcat(cCompilerOpts,optimsOffOpts,debugFlag.CCompiler));
cfg.setOption ...
('C++ Compiler',horzcat(cppCompilerOpts,optimsOffOpts,debugFlag.CppCompiler));
cfg.setOption('Linker',horzcat(linkerOpts,debugFlag.Linker));
cfg.setOption('Shared Library Linker',horzcat(sharedLinkerOpts,debugFlag.Linker));
cfg.setOption('Archiver',horzcat(archiverOpts,debugFlag.Archiver));

tc.setBuildConfigurationOption('all','Download','');

2-172
setOption

tc.setBuildConfigurationOption('all','Execute','');
tc.setBuildConfigurationOption('all','Make Tool','-f $(MAKEFILE)');

Using the Option-related methods interactively


tc = coder.make.ToolchainInfo;
cfg = tc.getBuildConfiguration('Faster Builds');
cfg.isOption('X Compiler')

ans =

bi = coder.make.BuildItem('WV','wrongvalue')

bi =

Macro : WV
Value : wrongvalue

cfg.addOption('X Compiler',bi);
value = cfg.getOption('X Compiler')

value =

Macro : WV
Value : wrongvalue

cfg.setOption('X Compiler','rightvalue');
value = cfg.getOption('X Compiler')

value =

Macro : WV
Value : rightvalue

See Also
coder.make.BuildConfiguration.addOption |
coder.make.BuildConfiguration.getOption |
coder.make.BuildConfiguration.isOption | coder.make.BuildItem

2-173
2 Function Reference

values
Class: coder.make.BuildConfiguration
Package: coder.make

Get all option values

Syntax
Out = h.values

Description
Out = h.values returns a list of all option values in the build configuration.

Input Arguments
h — BuildConfiguration handle
object handle

BuildConfiguration handle, specified as a coder.make.BuildConfiguration object.


Example: h

Output Arguments
Out — List of all option values in build configuration
string or object handle

List of all option values in the build configuration, returned as a cell array of strings.

Examples
Starting from the “Adding a Custom Toolchain” example, enter the following lines:

2-174
values

tc = intel_tc
cfg = tc.getBuildConfiguration('Faster Builds');
cfg.values

ans =

Columns 1 through 2

[1x1 coder.make.BuildItem] [1x1 coder.make.BuildItem]

Columns 3 through 4

[1x1 coder.make.BuildItem] [1x1 coder.make.BuildItem]

Columns 5 through 6

[1x1 coder.make.BuildItem] [1x1 coder.make.BuildItem]

Columns 7 through 8

[1x1 coder.make.BuildItem] [1x1 coder.make.BuildItem]

Columns 9 through 10

[1x1 coder.make.BuildItem] [1x1 coder.make.BuildItem]

2-175
2 Function Reference

getMacro
Class: coder.make.BuildItem
Package: coder.make

Get macro name of build item

Syntax
h.getMacro

Description
h.getMacro returns the macro name of an existing build item.

Input Arguments
buildItemHandle — BuildItem handle
object handle

BuildItem handle, specified as a coder.make.BuildItem object that contains an option


value.
Example: bi

Examples
bi = coder.make.BuildItem('bldtmvalue')

bi =

Macro : (empty)
Value : bldtmvalue

bi.setMacro('BIMV2');
bi.getMacro

2-176
getMacro

ans =

BIMV2

See Also
coder.make.BuildItem.getMacro | coder.make.BuildItem.getValue |
coder.make.BuildItem.setMacro | coder.make.BuildItem.setValue

More About
• “About coder.make.ToolchainInfo”

2-177
2 Function Reference

getValue
Class: coder.make.BuildItem
Package: coder.make

Get value of build item

Syntax
h.getValue

Description
h.getValue returns the value of an existing build item.

Input Arguments
buildItemHandle — BuildItem handle
object handle

BuildItem handle, specified as a coder.make.BuildItem object that contains an option


value.
Example: bi

Examples
bi = coder.make.BuildItem('wrongvalue')

bi =

Macro : (empty)
Value : wrongvalue

bi.setValue('rightvalue')
bi.getValue

2-178
getValue

ans =

rightvalue

See Also
coder.make.BuildItem.getMacro | coder.make.BuildItem.getValue |
coder.make.BuildItem.setMacro | coder.make.BuildItem.setValue

More About
• “About coder.make.ToolchainInfo”

2-179
2 Function Reference

setMacro
Class: coder.make.BuildItem
Package: coder.make

Set macro name of build item

Syntax
h.setMacro(blditm_macroname)

Description
h.setMacro(blditm_macroname) sets the macro name of an existing build item.

Input Arguments
buildItemHandle — BuildItem handle
object handle

BuildItem handle, specified as a coder.make.BuildItem object that contains an option


value.
Example: bi

blditm_macroname — Macro name of build item


string

Macro name of build item, specified as a string.


Data Types: char

Examples
bi = coder.make.BuildItem('bldtmvalue')

bi =

2-180
setMacro

Macro : (empty)
Value : bldtmvalue

bi.setMacro('BIMV2');
bi.getMacro

ans =

BIMV2

See Also
coder.make.BuildItem.getMacro | coder.make.BuildItem.getValue |
coder.make.BuildItem.setMacro | coder.make.BuildItem.setValue

More About
• “About coder.make.ToolchainInfo”

2-181
2 Function Reference

setValue
Class: coder.make.BuildItem
Package: coder.make

Set value of build item

Syntax
h.setValue(blditm_value)

Description
h.setValue(blditm_value) sets the value of an existing build item macro.

Input Arguments
buildItemHandle — BuildItem handle
object handle

BuildItem handle, specified as a coder.make.BuildItem object that contains an option


value.
Example: bi

blditm_value — Value of build item


string

Value of build item


Data Types: char

Examples
bi = coder.make.BuildItem('wrongvalue')

bi =

2-182
setValue

Macro : (empty)
Value : wrongvalue

bi.setValue('rightvalue')
bi.getValue

ans =

rightvalue

See Also
coder.make.BuildItem.getMacro | coder.make.BuildItem.getValue |
coder.make.BuildItem.setMacro | coder.make.BuildItem.setValue

More About
• “About coder.make.ToolchainInfo”

2-183
2 Function Reference

addDirective
Class: coder.make.BuildTool
Package: coder.make

Add directive to Directives

Syntax
h.addDirective(name,value)

Description
h.addDirective(name,value) creates a named directive, assigns a value to it, and
adds it to coder.make.BuildTool.Directives.

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

name — Name of directive


string

Name of directive, specified as a string.


Data Types: char

value — Value of directive


string

Value of directive, specified as a string.


Data Types: char

2-184
addDirective

Examples
tc = coder.make.ToolchainInfo;
tool = tc.getBuildTool('C Compiler');
tool.addDirective('IncludeSearchPath','-O');
tool.setDirective('IncludeSearchPath','-I');
tool.getDirective('IncludeSearchPath')

ans =

-I

See Also
“Properties” on page 3-132 | coder.make.BuildTool.getDirective |
coder.make.BuildTool.setDirective

2-185
2 Function Reference

addFileExtension
Class: coder.make.BuildTool
Package: coder.make

Add new file extension entry to FileExtensions

Syntax
h.addFileExtension(name,buildItemHandle)

Description
h.addFileExtension(name,buildItemHandle) creates a named
extension, assigns a coder.make.BuildItem object to it, and adds it to
coder.make.BuildTool.FileExtensions.

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

name — Name of file type.


string

Name of file type, specified as a string.


Data Types: char

buildItemHandle — BuildItem handle


object handle

BuildItem handle, specified as a coder.make.BuildItem object that contains an option


value.

2-186
addFileExtension

Example: bi

Examples
tc = coder.make.ToolchainInfo;
tool = tc.getBuildTool('C Compiler');
blditm = coder.make.BuildItem('CD','.cd')

bldtm =

Macro : CD
Value : .cd

tool.addFileExtension('SourceX',blditm)
value = tool.getFileExtension('SourceX')

value =

.cd

tool.setFileExtension('SourceX','.ef')
value = tool.getFileExtension('SourceX')

value =

.ef

See Also
“Properties” on page 3-132 | coder.make.BuildTool.getFileExtension |
coder.make.BuildTool.setFileExtension

2-187
2 Function Reference

getCommand
Class: coder.make.BuildTool
Package: coder.make

Get build tool command

Syntax
c_out = h.getCommand
c_out = h.getCommand('value')
c_out = h.getCommand('macro')

Description
c_out = h.getCommand returns the value of the coder.make.BuildTool.Command
property.

c_out = h.getCommand('value') also returns the value of


coder.make.BuildTool.Command.

c_out = h.getCommand('macro') returns the macro name of


coder.make.BuildTool.Command.

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

'value' — Get command value

Gets the command value.

2-188
getCommand

'macro'

Gets the command macro.

Output Arguments
c_out — Command value or macro

The command value or macro of the build tool, returned as a scalar.


Data Types: char

Examples
tc = coder.make.ToolchainInfo;
btl = tc.getBuildTool('C Compiler');
btl.getCommand

ans =

icl

btl.getCommand('value')

ans =

icl

c_out = btl.getCommand('macro')

c_out =

CC

See Also
coder.make.BuildTool.setCommand

2-189
2 Function Reference

getDirective
Class: coder.make.BuildTool
Package: coder.make

Get value of named directive from Directives

Syntax
value = h.getDirective(name)

Description
value = h.getDirective(name) gets the value of the named directive from
Directives

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

name — Name of directive


string

Name of directive, specified as a string.


Data Types: char

Output Arguments
value — Value of directive
string

2-190
getDirective

Value of directive, specified as a string.


Data Types: char

Examples
tc = coder.make.ToolchainInfo;
tool = tc.getBuildTool('C Compiler');
tool.addDirective('IncludeSearchPath','-O');
tool.setDirective('IncludeSearchPath','-I');
tool.getDirective('IncludeSearchPath')

ans =

-I

See Also
“Properties” on page 3-132 | coder.make.BuildTool.addDirective |
coder.make.BuildTool.setDirective

2-191
2 Function Reference

getFileExtension
Class: coder.make.BuildTool
Package: coder.make

Get file extension for named file type in FileExtensions

Syntax
value = h.getFileExtension(name)

Description
value = h.getFileExtension(name) gets the file extension of the named file type
from coder.make.BuildTool.FileExtensions.

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

name — Name of file type.


string

Name of file type, specified as a string.


Data Types: char

Output Arguments
value — Value of file extension
string

2-192
getFileExtension

Value of file extension, specified as a string.


Data Types: char

Examples
tc = coder.make.ToolchainInfo;
tool = tc.getBuildTool('C Compiler');
blditm = coder.make.BuildItem('CD','.cd')

bldtm =

Macro : CD
Value : .cd

tool.addFileExtension('SourceX',blditm)
value = tool.getFileExtension('SourceX')

value =

.cd

tool.setFileExtension('SourceX','.ef')
value = tool.getFileExtension('SourceX')

value =

.ef

See Also
“Properties” on page 3-132 | coder.make.BuildTool.addFileExtension |
coder.make.BuildTool.setFileExtension

2-193
2 Function Reference

getName
Class: coder.make.BuildTool
Package: coder.make

Get build tool name

Syntax
toolname = h.getName

Description
toolname = h.getName returns the name of the coder.make.BuildTool object.

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

Output Arguments
toolname — Name of BuildTool object

The name of the coder.make.BuildTool object

Examples
Using the getName and setName methods interactively
Starting from the “Adding a Custom Toolchain” example, enter the following lines:

2-194
getName

tc = coder.make.ToolchainInfo;
tool = tc.getBuildTool('C Compiler');
tool.getName

ans =

C Compiler

tool.setName('X Compiler')
tool.getName

ans =

X Compiler

See Also
coder.make.BuildTool.setName

2-195
2 Function Reference

getPath
Class: coder.make.BuildTool
Package: coder.make

Get path and macro of build tool in Path

Syntax
btpath = h.getPath
btmacro = h.getPath('macro')

Description
btpath = h.getPath returns the path of the build tool from
coder.make.BuildTool.Paths.

btmacro = h.getPath('macro') returns the macro for the path of the build tool from
coder.make.BuildTool.Paths

Tips
If the system command environment specifies a path variable for the build tool, the value
of the path does not need to be specified by the BuildTool object.

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

2-196
getPath

Output Arguments
btpath — Path of build tool object

The path of BuildTool object, returned as a scalar.


Data Types: char

btmacro — Macro for path of build tool object

Macro for path of BuildTool object, returned as a scalar.


Data Types: char

Examples
Enter the following lines:
tc = coder.make.ToolchainInfo;
tool = tc.getBuildTool('C Compiler');
tool.getPath

ans =

''

tool.getPath('macro')

ans =

CC_PATH

tool.setPath('/gcc')
tool.Path

ans =

Macro : CC_PATH
Value : /gcc

See Also
“Properties” on page 3-132 | coder.make.BuildTool.setPath

2-197
2 Function Reference

info
Class: coder.make.BuildTool
Package: coder.make

Display build tool properties and values

Syntax
h.info

Description
h.info returns information about the coder.make.BuildTool object.

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

Examples
Starting from the “Adding a Custom Toolchain” example, enter the following lines:
tc = intel_tc;
tool = tc.getBuildTool('C Compiler');
tool.info

##############################################
# Build Tool: Intel C Compiler
##############################################

Language : 'C'
OptionsRegistry : {'C Compiler','CFLAGS'}
InputFileExtensions : {'Source'}
OutputFileExtensions : {'Object'}

2-198
info

DerivedFileExtensions : {'|>OBJ_EXT<|'}
SupportedOutputs : {'*'}
CommandPattern : '|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<||>OUTPUT<|'

# ---------
# Command
# ---------
CC = icl
CC_PATH =

# ------------
# Directives
# ------------
Debug = -Zi
Include =
IncludeSearchPath = -I
OutputFlag = -Fo
PreprocessorDefine = -D

# -----------------
# File Extensions
# -----------------
Header = .h
Object = .obj
Source = .c

2-199
2 Function Reference

setCommandPattern
Class: coder.make.BuildTool
Package: coder.make

Set pattern of commands for build tools

Syntax
h.setCommandPattern(commandpattern);

Description
h.setCommandPattern(commandpattern); sets the command pattern of a specific
coder.make.BuildTool object in coder.make.ToolchainInfo.BuildTools.

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

commandpattern — Pattern of commands and options


string

Pattern of commands and options that a BuildTool can use to run a build tool, specified
as a string.

Use |> and <| as the left and right delimiters of a command element. Use a space
character between the <| and |> delimiters to require a space between two command
elements. For example:

• |>TOOL<| |>TOOL_OPTIONS<| requires a space between the two command


elements.

2-200
setCommandPattern

• |>OUTPUT_FLAG<||>OUTPUT<| requires no space between the two command


elements.

Data Types: char

Examples
The intel_tc.m file from “Adding a Custom Toolchain”, uses the following lines to get
and update one of the BuildTool objects, including the command pattern:
% ------------------------------
% C Compiler
% ------------------------------

tool = tc.getBuildTool('C Compiler');

tool.setName('Intel C Compiler');
tool.setCommand('icl');
tool.setPath('');

tool.setDirective('IncludeSearchPath','-I');
tool.setDirective('PreprocessorDefine','-D');
tool.setDirective('OutputFlag','-Fo');
tool.setDirective('Debug','-Zi');

tool.setFileExtension('Source','.c');
tool.setFileExtension('Header','.h');
tool.setFileExtension('Object','.obj');

tool.setCommandPattern('|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<||>OUTPUT<|');

See Also
coder.make.ToolchainInfo.addBuildTool |
coder.make.BuildTool.setCommandPattern

2-201
2 Function Reference

setCommand
Class: coder.make.BuildTool
Package: coder.make

Set build tool command

Syntax
h.setCommand(commandvalueinput)

Description
h.setCommand(commandvalueinput) sets the value of the
coder.make.BuildTool.Command property.

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

commandvalueinput — Value of coder.make.BuildTool.Command property

Value of the coder.make.BuildTool.Command property. Enter a character string, or


the handle of a coder.make.BuildItem object that contains an option value.

Examples
Get a default build tool and set its properties
The intel_tc.m file from “Adding a Custom Toolchain”, uses the following lines to set
the command of a default build tool, C Compiler, from a ToolchainInfo object called
tc, and then sets its properties.

2-202
setCommand

% ------------------------------
% C Compiler
% ------------------------------

tool = tc.getBuildTool('C Compiler');

tool.setName('Intel C Compiler');
tool.setCommand('icl');
tool.setPath('');

tool.setDirective('IncludeSearchPath','-I');
tool.setDirective('PreprocessorDefine','-D');
tool.setDirective('OutputFlag','-Fo');
tool.setDirective('Debug','-Zi');

tool.setFileExtension('Source','.c');
tool.setFileExtension('Header','.h');
tool.setFileExtension('Object','.obj');

tool.setCommandPattern('|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<||>OUTPUT<|');

See Also
coder.make.BuildTool.getCommand

2-203
2 Function Reference

setDirective
Class: coder.make.BuildTool
Package: coder.make

Set value of directive in Directives

Syntax
h.setDirective(name,value)

Description
h.setDirective(name,value) assigns a value to the named directive in
coder.make.Directives.

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

name — Name of directive


string

Name of directive, specified as a string.


Data Types: char

value — Value of directive


string

Value of directive, specified as a string.


Data Types: char

2-204
setDirective

Examples

Get a default build tool and set its properties


The following example code shows setDirective in a portion of the intel_tc.m file
from the “Adding a Custom Toolchain” tutorial.
% ------------------------------
% C Compiler
% ------------------------------

tool = tc.getBuildTool('C Compiler');

tool.setName('Intel C Compiler');
tool.setCommand('icl');
tool.setPath('');

tool.setDirective('IncludeSearchPath','-I');
tool.setDirective('PreprocessorDefine','-D');
tool.setDirective('OutputFlag','-Fo');
tool.setDirective('Debug','-Zi');

tool.setFileExtension('Source','.c');
tool.setFileExtension('Header','.h');
tool.setFileExtension('Object','.obj');

tool.setCommandPattern('|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<||>OUTPUT<|');

Use the setDirective method interactively


tc = coder.make.ToolchainInfo;
tool = tc.getBuildTool('C Compiler');
tool.addDirective('IncludeSearchPath','-O');
tool.setDirective('IncludeSearchPath','-I');
tool.getDirective('IncludeSearchPath')

ans =

-I

See Also
“Properties” on page 3-132 | coder.make.BuildTool.addDirective |
coder.make.BuildTool.getDirective

2-205
2 Function Reference

setFileExtension
Class: coder.make.BuildTool
Package: coder.make

Set file extension for named file type in FileExtensions

Syntax
h.setFileExtension(name,value)

Description
h.setFileExtension(name,value) sets the extension value of the named file type in
coder.make.BuildTool.FileExtensions.

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

name — Name of file type.


string

Name of file type, specified as a string.


Data Types: char

value — Value of file extension


string

Value of file extension, specified as a string.


Data Types: char

2-206
setFileExtension

Examples
Get a default build tool and set its properties
The following example code shows setFileExtension in a portion of the intel_tc.m
file from the “Adding a Custom Toolchain” tutorial.
% ------------------------------
% C Compiler
% ------------------------------

tool = tc.getBuildTool('C Compiler');

tool.setName('Intel C Compiler');
tool.setCommand('icl');
tool.setPath('');

tool.setDirective('IncludeSearchPath','-I');
tool.setDirective('PreprocessorDefine','-D');
tool.setDirective('OutputFlag','-Fo');
tool.setDirective('Debug','-Zi');

tool.setFileExtension('Source','.c');
tool.setFileExtension('Header','.h');
tool.setFileExtension('Object','.obj');

tool.setCommandPattern('|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<||>OUTPUT<|');

Use the setFileExtension interactively


tc = coder.make.ToolchainInfo;
tool = tc.getBuildTool('C Compiler');
blditm = coder.make.BuildItem('CD','.cd')

bldtm =

Macro : CD
Value : .cd

tool.addFileExtension('SourceX',blditm)
value = tool.getFileExtension('SourceX')

value =

.cd

tool.setFileExtension('SourceX','.ef')
value = tool.getFileExtension('SourceX')

value =

2-207
2 Function Reference

.ef

See Also
“Properties” on page 3-132 | coder.make.BuildTool.addFileExtension |
coder.make.BuildTool.getFileExtension

2-208
setName

setName
Class: coder.make.BuildTool
Package: coder.make

Set build tool name

Syntax
h.setName(name)

Description
h.setName(name) sets the name of the coder.make.BuildTool.Name property.

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

name — Name of build tool


string

The name of the build tool, specified as a string.


Example: 'Intel C Compiler'
Data Types: char

2-209
2 Function Reference

Examples

Get a default build tool and set its properties


The following example code shows setName in a portion of the intel_tc.m file from the
“Adding a Custom Toolchain” tutorial:
% ------------------------------
% C Compiler
% ------------------------------

tool = tc.getBuildTool('C Compiler');

tool.setName('Intel C Compiler');
tool.setCommand('icl');
tool.setPath('');

tool.setDirective('IncludeSearchPath','-I');
tool.setDirective('PreprocessorDefine','-D');
tool.setDirective('OutputFlag','-Fo');
tool.setDirective('Debug','-Zi');

tool.setFileExtension('Source','.c');
tool.setFileExtension('Header','.h');
tool.setFileExtension('Object','.obj');

tool.setCommandPattern('|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<||>OUTPUT<|');

Using the getName and setName methods interactively


Starting from the “Adding a Custom Toolchain” example, enter the following lines:
tc = coder.make.ToolchainInfo;
tool = tc.getBuildTool('C Compiler');
tool.getName

ans =

C Compiler

tool.setName('X Compiler')
tool.getName

ans =

X Compiler

2-210
setPath

setPath
Class: coder.make.BuildTool
Package: coder.make

Set path and macro of build tool in Path

Syntax
h.setPath(btpath,btmacro)

Description
h.setPath(btpath,btmacro) sets the path and macro of the build tool in
coder.make.BuildTool.Paths.

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

btpath — Path of build tool object

The path of BuildTool object, returned as a scalar.


Data Types: char

btmacro — Macro for path of build tool object

Macro for path of BuildTool object, returned as a scalar.


Data Types: char

2-211
2 Function Reference

Examples

Get a default build tool and set its properties


The following example code shows setPath in a portion of the intel_tc.m file from the
“Adding a Custom Toolchain” tutorial.
% ------------------------------
% C Compiler
% ------------------------------

tool = tc.getBuildTool('C Compiler');

tool.setName('Intel C Compiler');
tool.setCommand('icl');
tool.setPath('');

tool.setDirective('IncludeSearchPath','-I');
tool.setDirective('PreprocessorDefine','-D');
tool.setDirective('OutputFlag','-Fo');
tool.setDirective('Debug','-Zi');

tool.setFileExtension('Source','.c');
tool.setFileExtension('Header','.h');
tool.setFileExtension('Object','.obj');

tool.setCommandPattern('|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<||>OUTPUT<|');

Use the getPath and setPath methods interactively


This example shows example inputs and outputs for the methods in a MATLAB
Command Window:

Enter the following lines:

tc = coder.make.ToolchainInfo;
tool = tc.getBuildTool('C Compiler');
tool.getPath

ans =

''

tool.getPath('macro')

ans =

CC_PATH

2-212
setPath

tool.setPath('/gcc')
tool.Path

ans =

Macro : CC_PATH
Value : /gcc

See Also
“Properties” on page 3-132 | coder.make.BuildTool.getPath

2-213
2 Function Reference

validate
Class: coder.make.BuildTool
Package: coder.make

Validate build tool properties

Syntax
validtool = h.validate

Description
validtool = h.validate validates the coder.make.BuildTool object, and
generates errors if any properties are incorrectly defined.

Input Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

Output Arguments
validtool — Validity of coder.make.BuildTool object

The validity of the coder.make.BuildTool object. If the method detects a problem it


returns '0' or an error message.

2-214
validate

Examples
The coder.make.BuildTool.validate method returns warning and error messages if
you try to validate a build tool before you have installed the build tool software (compiler,
linker, archiver).

Starting from the “Adding a Custom Toolchain” example, enter the following lines:
tc = intel_tc;
tool = tc.getBuildTool('C Compiler');
tool.validate

If your host computer does not have the Intel® toolchain installed, validate displays the
following messages:
Warning: Validation of build tool 'Intel C Compiler' may require the toolchain
to be set up first. The setup information is registered in the toolchain
this build tool belong to. Pass the parent ToolchainInfo object to VALIDATE
in order for any toolchain setup to be done before validation.
> In C:\Program Files\MATLAB\R2013a\toolbox\coder\foundation\build\+coder\+make\
BuildTool.p>BuildTool.checkForPresence at 634
In C:\Program Files\MATLAB\R2013a\toolbox\coder\foundation\build\+coder\+make\
BuildTool.p>BuildTool.validate at 430
Error using message
In 'CoderFoundation:toolchain:ValidateBuildToolError',data type supplied is
incorrect for parameter {1}.

Error in C:\Program
Files\MATLAB\R2013a\toolbox\coder\foundation\build\+coder\+make\
BuildTool.p>BuildTool.checkForPresence
(line 664)

Error in C:\Program
Files\MATLAB\R2013a\toolbox\coder\foundation\build\+coder\+make\
BuildTool.p>BuildTool.validate
(line 430)

Trial>>

For more information, see “Troubleshooting Custom Toolchain Validation”.

See Also
coder.make.ToolchainInfo.validate

2-215
2 Function Reference

addAttribute
Class: coder.make.ToolchainInfo
Package: coder.make

Add custom attribute to Attributes

Syntax
h.addAttribute(att_name, att_value)
h.addAttribute(att_name)

Description
h.addAttribute(att_name, att_value) adds a custom attribute with the specified
name to coder.make.ToolchainInfo.Attributes. Use att_value to override the
default attribute value, true.

h.addAttribute(att_name) adds an attribute and initializes its value to true.

All attributes are optional. You can add attributes for the toolchain to use. The following
attributes are used during the build process:

• TransformPathsWithSpaces (value = True/False) When enabled, this method looks


for spaces in paths to source files, include files, include paths, additional source paths,
object paths, and prebuild object paths, library paths, and within MACROS used in
any of the stated paths. If any path contains spaces, an alternate version of the path
is returned. For long path names or paths with spaces, this returns the '~' version
on Windows. On UNIX platforms, paths with spaces are returned with the spaces
escaped.
• RequiresBatchFile: (value = True/False) When enabled, creates a batch file that
runs the make file that is generated.
• SupportsUNCPaths: (value = True/False) Looks in the same locations for UNC paths
(Windows only, ignored on Linux/Mac platforms). If there is a drive mapped to the
UNC the path is pointing to, then paths that are UNC paths will have a mapped drive
letter put in place.

2-216
addAttribute

• SupportsDoubleQuotes: (not defined or value = True) Wraps each path in double


quotes if they contain spaces.
• RequiresCommandFile: (not defined or value = True) This is used to handle long
archiver/linker lines in Windows. If specified the make file replace a long object list
with a call to a command file.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

att_name — Name of attribute


string

Name of attribute, specified as a string of alphanumeric characters.


Data Types: char

att_value — Value of attribute


true (default)

Attribute value. Any data type.

Examples
Add an attribute and initialize its value, overriding the default value
h.Attribute

ans =

# -------------------
# "Attribute" List
# -------------------
(empty)

h.addAttribute('TransformPathsWithSpaces',false)

2-217
2 Function Reference

h.getAttribute('TransformPathsWithSpaces')

ans =

Add attribute without overriding its default value


h.addAttribute('CustomAttribute')
h.Attributes

ans =

# -------------------
# "Attributes" List
# -------------------
CustomAttribute = true

Add attribute using toolchain definition file


The intel_tc.m file from the “Adding a Custom Toolchain” example defines the
following custom attributes:

tc.addAttribute('TransformPathsWithSpaces');
tc.addAttribute('RequiresCommandFile');
tc.addAttribute('RequiresBatchFile');

To see the property values from that example in the MATLAB Command Window, enter:

h = intel_tc;
h.Attributes

ans =

# -------------------
# "Attributes" List
# -------------------
RequiresBatchFile = true
RequiresCommandFile = true
TransformPathsWithSpaces = true

2-218
addAttribute

See Also
coder.make.ToolchainInfo.addAttribute |
coder.make.ToolchainInfo.getAttribute |
coder.make.ToolchainInfo.getAttributes
| coder.make.ToolchainInfo.isAttribute |
coder.make.ToolchainInfo.removeAttribute

More About
• “About coder.make.ToolchainInfo”

2-219
2 Function Reference

addBuildConfiguration
Class: coder.make.ToolchainInfo
Package: coder.make

Add build configuration

Syntax
h.addBuildConfiguration(bldcfg_name)
h.addBuildConfiguration(bldcfg_name, bldcfg_desc)
h.addBuildConfiguration(bldcfg_handle)

Description
h.addBuildConfiguration(bldcfg_name) creates a
coder.make.BuildConfiguration object, assigns the value of
bldcfg_name to Name property of the object, and adds the object to
coder.make.ToolchainInfo.BuildConfigurations.

h.addBuildConfiguration(bldcfg_name, bldcfg_desc) assigns the value of


bldcfg_desc to Description property of the object.

h.addBuildConfiguration(bldcfg_handle) adds an existing build configuration


object to coder.make.ToolchainInfo.BuildConfigurations. The build configuration must
have a name that is unique within coder.make.ToolchainInfo.BuildConfigurations.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldcfg_name — Build configuration name


string

2-220
addBuildConfiguration

Build configuration name, specified as a string.


Data Types: char

bldcfg_handle — BuildConfiguration object handle

Handle of coder.make.BuildConfiguration object

bldcfg_desc — Build configuration description


string

Build configuration description, specified as a string.


Data Types: char

Examples
h.getBuildConfigurations

ans =

'Faster Builds'
'Faster Runs'
'Debug'

bldcfg_handle = h.getBuildConfiguration('Debug')
bldcfg_handle =

##############################################
# Build Configuration : Debug
# Description : Default debug settings for compiling/linking code
##############################################

ARFLAGS = /nologo $(ARDEBUG)


CFLAGS = $(cflags) $(CVARSFLAG) $(CFLAGS_ADDITIONAL) /c /Od $(CDEBUG)
CPPFLAGS = $(cflags) $(CVARSFLAG) $(CPPFLAGS_ADDITIONAL) /c /Od $(CPPDEBUG)
DOWNLOAD_FLAGS =
EXECUTE_FLAGS =
LDFLAGS = $(ldebug) $(conflags) $(LIBS_TOOLCHAIN) $(LDDEBUG)
MEX_CFLAGS =
MEX_LDFLAGS =
MAKE_FLAGS = -f $(MAKEFILE)
SHAREDLIB_LDFLAGS = $(ldebug) $(conflags) $(LIBS_TOOLCHAIN) -dll -def:$(DEF_FILE) $(LDDEBUG)

h.addBuildConfiguration('Debug2','Variant debugging configuration')


h.setBuildConfiguration('Debug2',bldcfg_handle)
h.getBuildConfigurations

2-221
2 Function Reference

ans =

'Faster Builds'
'Faster Runs'
'Debug'
'Debug2'

See Also
coder.make.BuildConfiguration | coder.make.BuildItem |
coder.make.BuildTool

More About
• “About coder.make.ToolchainInfo”

2-222
addBuildTool

addBuildTool
Class: coder.make.ToolchainInfo
Package: coder.make

Add BuildTool object to BuildTools

Syntax
tool = h.addBuildTool(bldtl_name)
tool = h.addBuildTool(bldtl_name, bldtl_handle)

Description
tool = h.addBuildTool(bldtl_name) creates and adds a named BuildTool object
to coder.make.ToolchainInfo.BuildTools.

tool = h.addBuildTool(bldtl_name, bldtl_handle) adds an existing


BuildTool object to coder.make.ToolchainInfo.BuildTools. The bldtl_name
argument overrides the Name property of the existing BuildTool object.

Tips
Refer to the “Example” on page 3-134 for coder.make.BuildTool for an example of
how to create a BuildTool object.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldtl_name — Build tool name


string

2-223
2 Function Reference

Build tool name, specified as a string.


Data Types: char

bldtl_handle — BuildTool object handle

Handle of coder.make.BuildTool object.

Output Arguments
bldtl_handle — BuildTool object handle

Handle of coder.make.BuildTool object.

Examples
Refer to the coder.make.BuildTool “Example” on page 3-134 for a complete example of
how to create a addBuildTool.

Create a build tool and specify its name


h.addBuildTool('ExampleBuildTool')

ans =

##############################################
# Build Tool: Build Tool
##############################################

Language : 'C'
OptionsRegistry : {}
InputFileExtensions : {}
OutputFileExtensions : {}
DerivedFileExtensions : {}
SupportedOutputs : {'*'}
CommandPattern : '|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<| |>OUTPUT<|'

# ---------
# Command
# ---------

# ------------
# Directives
# ------------
(none)

# -----------------

2-224
addBuildTool

# File Extensions
# -----------------
(none)

See Also
coder.make.BuildTool | coder.make.ToolchainInfo.addBuildTool
| coder.make.ToolchainInfo.getBuildTool |
coder.make.ToolchainInfo.removeBuildTool |
coder.make.ToolchainInfo.setBuildTool

More About
• “About coder.make.ToolchainInfo”

2-225
2 Function Reference

addIntrinsicMacros
Class: coder.make.ToolchainInfo
Package: coder.make

Add intrinsic macro to Macros

Syntax
h.addIntrinsicMacros(intrnsc_macroname)

Description
h.addIntrinsicMacros(intrnsc_macroname) adds an intrinsic macro to Macros.
The value of the intrinsic macro is defined by a build tool, not by ToolchainInfo or your
MathWorks software.

Tips
The value of intrinsic macros are intentionally not declared in ToolchainInfo. The
value of the intrinsic macro is defined by the build tools in the toolchain, outside the
scope of your MathWorks software.

During the software build process, your MathWorks software inserts intrinsic macros
into a build artifact, such as a makefile, without altering their form. During the build
process, the build artifact passes the intrinsic macros to the build tools in the toolchain.
The build tools interpret the macros based on their own internal definitions.

The validate method does not validate the intrinsic macros.

Because intrinsic macros have undeclared values, they remain unchanged in the
generated code, where they can be used and interpreted by the software build toolchain.
In contrast, ordinary macros are replaced by their assigned values when you create them.

2-226
addIntrinsicMacros

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

intrnsc_macronames — Intrinsic macro name or names

Intrinsic macro name or names, specified as a string or cell array of strings.

Examples
h.addIntrinsicMacros('GCCROOT')
h.getMacro('GCCROOT')

ans =

[]

h.removeIntrinsicMacros('GCCROOT')
h.getMacro('GCCROOT')

See Also
coder.make.ToolchainInfo.addMacro | coder.make.ToolchainInfo.getMacro
| coder.make.ToolchainInfo.removeMacro
| coder.make.ToolchainInfo.setMacro |
coder.make.ToolchainInfo.addIntrinsicMacros |
coder.make.ToolchainInfo.removeIntrinsicMacros

More About
• “About coder.make.ToolchainInfo”

2-227
2 Function Reference

addMacro
Class: coder.make.ToolchainInfo
Package: coder.make

Add macro to Macros

Syntax
h.addMacro(macroname)
h.addMacro(macroname, macrovalue)

Description
h.addMacro(macroname) adds a macro to coder.make.ToolchainInfo.Macros
without initializing the value of the Macro.

h.addMacro(macroname, macrovalue) adds a macro and initializes the value of the


macro.

Tips
Use setMacro to update the value of a macro in
coder.make.ToolchainInfo.Macros.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

macroname — Name of macro

Name of macro.

2-228
addMacro

macrovalue — Value of macro


string | cell

Value of the macro, specified as a string or cell array.

If the value contains MATLAB functions or other macros, ToolchainInfo interprets the
value of functions and macros.
Data Types: cell | char

Examples
h.setMacro('CYGWIN','C:\cygwin\');
h.getMacro('CYGWIN')

ans =

C:\cygwin\bin\

h.removeMacro('CYGWIN')

See Also
coder.make.ToolchainInfo.addMacro | coder.make.ToolchainInfo.getMacro
| coder.make.ToolchainInfo.removeMacro
| coder.make.ToolchainInfo.setMacro |
coder.make.ToolchainInfo.addIntrinsicMacros |
coder.make.ToolchainInfo.removeIntrinsicMacros

More About
• “About coder.make.ToolchainInfo”

2-229
2 Function Reference

addPostbuildTool
Class: coder.make.ToolchainInfo
Package: coder.make

Add postbuild tool to PostbuildTools

Syntax
h.addPostbuildTool(bldtl_name)
h.addPostbuildTool(bldtl_name, bldtl_handle)

Description
h.addPostbuildTool(bldtl_name) adds a BuildTool object to PostbuildTools.

h.addPostbuildTool(bldtl_name, bldtl_handle) adds a postbuild tool to


PostbuildTools and assigns a BuildTool object to it.

Tips
Refer to the “Example” on page 3-134 for coder.make.BuildTool for an example of
how to create a BuildTool object.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldtl_name — Build tool name


string

Build tool name, specified as a string.


Data Types: char

2-230
addPostbuildTool

bldtl_handle — BuildTool object handle

Handle of coder.make.BuildTool object.

Examples
h = coder.make.ToolchainInfo;
bt = coder.make.BuildTool('postbuildtoolname');
h.addPostbuildTool('examplename',bt)

ans =

##############################################
# Build Tool: postbuildtoolname
##############################################

Language : 'C'
OptionsRegistry : {}
InputFileExtensions : {}
OutputFileExtensions : {}
DerivedFileExtensions : {}
SupportedOutputs : {'*'}
CommandPattern : '|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<| |>OUTPUT<|'

# ---------
# Command
# ---------

# ------------
# Directives
# ------------
(none)

# -----------------
# File Extensions
# -----------------
(none)

See Also
coder.make.ToolchainInfo.addPostbuildTool |
coder.make.ToolchainInfo.getPostbuildTool |
coder.make.ToolchainInfo.removePostbuildTool

2-231
2 Function Reference

| coder.make.ToolchainInfo.setPostbuildTool |
coder.make.ToolchainInfo.addPostDownloadTool |
coder.make.ToolchainInfo.addPostExecuteTool

More About
• “About coder.make.ToolchainInfo”

2-232
addPostDownloadTool

addPostDownloadTool
Class: coder.make.ToolchainInfo
Package: coder.make

Add post-download tool to PostDownloadTool

Syntax
h.addPostDownloadTool(bldtl_name,bldtl_handle)

Description
h.addPostDownloadTool(bldtl_name,bldtl_handle) adds a BuildTool object
between the download tool and the execute tool specified by the PostbuildTools
property.

Tips
Refer to the “Example” on page 3-134 for coder.make.BuildTool for an example of
how to create a BuildTool object.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldtl_name — Build tool name


string

Build tool name, specified as a string.


Data Types: char

2-233
2 Function Reference

bldtl_handle — BuildTool object handle

Handle of coder.make.BuildTool object.

Examples
h = coder.make.ToolchainInfo;
bt = coder.make.BuildTool('toolname');
h.addPostDownloadTool('examplename',bt)

ans =

##############################################
# Build Tool: toolname
##############################################

Language : 'C'
OptionsRegistry : {}
InputFileExtensions : {}
OutputFileExtensions : {}
DerivedFileExtensions : {}
SupportedOutputs : {'*'}
CommandPattern : '|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<| |>OUTPUT<|'

# ---------
# Command
# ---------

# ------------
# Directives
# ------------
(none)

# -----------------
# File Extensions
# -----------------
(none)

References
“About coder.make.ToolchainInfo”

2-234
addPostDownloadTool

See Also
coder.make.ToolchainInfo.addPostbuildTool |
coder.make.ToolchainInfo.getPostbuildTool |
coder.make.ToolchainInfo.removePostbuildTool
| coder.make.ToolchainInfo.setPostbuildTool |
coder.make.ToolchainInfo.addPostDownloadTool |
coder.make.ToolchainInfo.addPostExecuteTool

More About
• “About coder.make.ToolchainInfo”

2-235
2 Function Reference

addPostExecuteTool
Class: coder.make.ToolchainInfo
Package: coder.make

Add post-execute tool to PostbuildTools

Syntax
h.addPostExecuteTool(name,bldtl_handle)

Description
h.addPostExecuteTool(name,bldtl_handle) adds a named build tool to
PostbuildTools after the Execute tool.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

name — Name of post execute tool

Name of post execute tool, specified as a string.

bldtl_handle — BuildTool object handle

Handle of coder.make.BuildTool object.

Examples
Refer to the coder.make.BuildTool “Example” on page 3-134 for an example of to create
a BuildTool.

2-236
addPostExecuteTool

To use addPostExecuteTool, enter the following commands:


h = coder.make.ToolchainInfo;
bt = coder.make.BuildTool('toolname');
h.addPostExecuteTool('ExampleName',bt)

ans =

##############################################
# Build Tool: toolname
##############################################

Language : 'C'
OptionsRegistry : {}
InputFileExtensions : {}
OutputFileExtensions : {}
DerivedFileExtensions : {}
SupportedOutputs : {'*'}
CommandPattern : '|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<| |>OUTPUT<|'

# ---------
# Command
# ---------

# ------------
# Directives
# ------------
(none)

# -----------------
# File Extensions
# -----------------
(none)

See Also
coder.make.ToolchainInfo.addPostbuildTool |
coder.make.ToolchainInfo.addPostDownloadTool

More About
• “About coder.make.ToolchainInfo”

2-237
2 Function Reference

addPrebuildTool
Class: coder.make.ToolchainInfo
Package: coder.make

Add prebuild tool to PrebuildTools

Syntax
h.addPrebuildTool(bldtl_name)
h.addPrebuildTool(bldtl_name, bldtl_handle)

Description
h.addPrebuildTool(bldtl_name) creates a BuildTool object and adds it to the
PrebuildTools property.

h.addPrebuildTool(bldtl_name, bldtl_handle) adds an existing BuildTool


object to the PrebuildTools property.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldtl_name — Build tool name


string

Build tool name, specified as a string.


Data Types: char

bldtl_handle — BuildTool object handle

Handle of coder.make.BuildTool object.

2-238
addPrebuildTool

See Also
coder.make.ToolchainInfo.addPrebuildTool |
coder.make.ToolchainInfo.getPrebuildTool |
coder.make.ToolchainInfo.removePrebuildTool |
coder.make.ToolchainInfo.setPrebuildTool

Related Examples
• “Adding a Custom Toolchain”

More About
• “About coder.make.ToolchainInfo”

2-239
2 Function Reference

cleanup
Class: coder.make.ToolchainInfo
Package: coder.make

Run cleanup commands

Syntax
h.cleanup

Description
h.cleanup runs cleanup commands after completing the
software build process. First, it runs the commands specified by
coder.make.ToolchainInfo.ShellCleanup, and then it runs the commands
specified by coder.make.ToolchainInfo.MATLABCleanup.

The commands in ShellCleanup run as system calls to the standard input of the
operating system on your host computer. These commands are similar to what you enter
when you use the command line.

The commands in MATLABCleanup run in your MATLAB software.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

Output Arguments
success — Indication whether cleanup completed

Indication whether cleanup completed (0 = false, 1 = true), returned as a scalar.

2-240
cleanup

Data Types: double

report — Information generated by the cleanup commands

Detailed information generated by the cleanup commands, returned as a string.


Data Types: double

Examples
[success,report] = h.cleanup

success =

report =

''

See Also
coder.make.ToolchainInfo.setup | coder.make.ToolchainInfo.validate

More About
• “About coder.make.ToolchainInfo”

2-241
2 Function Reference

getAttribute
Class: coder.make.ToolchainInfo
Package: coder.make

Get value of attribute

Syntax
att_value = h.getAttribute(att_name)

Description
att_value = h.getAttribute(att_name) returns the value of a specific attribute in
coder.make.ToolchainInfo.Attributes.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

att_name — Name of attribute


string

Name of attribute, specified as a string of alphanumeric characters.


Data Types: char

Output Arguments
att_value — Value of attribute
true (default)

Attribute value. Any data type.

2-242
getAttribute

Examples
h.Attribute

ans =

# -------------------
# "Attribute" List
# -------------------
(empty)

h.addAttribute('TransformPathsWithSpaces',false)
h.getAttribute('TransformPathsWithSpaces')

ans =

See Also
coder.make.ToolchainInfo.addAttribute |
coder.make.ToolchainInfo.getAttribute |
coder.make.ToolchainInfo.getAttributes
| coder.make.ToolchainInfo.isAttribute |
coder.make.ToolchainInfo.removeAttribute

More About
• “About coder.make.ToolchainInfo”

2-243
2 Function Reference

getAttributes
Class: coder.make.ToolchainInfo
Package: coder.make

Get list of attribute names

Syntax
names = h.getAttributes

Description
names = h.getAttributes returns the list of attribute names in
coder.make.ToolchainInfo.Attributes.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

Output Arguments
names — List of names

A list of the names, returned as a cell array.


Data Types: cell

Examples
h.addAttribute('FirstAttribute')

2-244
getAttributes

h.addAttribute('SecondAttribute')
h.addAttribute('ThirdAttribute')
names = h.getAttributes

names =

'FirstAttribute' 'SecondAttribute' 'ThirdAttribute'

See Also
coder.make.ToolchainInfo.addAttribute |
coder.make.ToolchainInfo.getAttribute |
coder.make.ToolchainInfo.getAttributes
| coder.make.ToolchainInfo.isAttribute |
coder.make.ToolchainInfo.removeAttribute

More About
• “About coder.make.ToolchainInfo”

2-245
2 Function Reference

getBuildConfiguration
Class: coder.make.ToolchainInfo
Package: coder.make

Get handle for build configuration object

Syntax
bldcfg_handle = h.getBuildConfiguration(bldcfg_name)

Description
bldcfg_handle = h.getBuildConfiguration(bldcfg_name) returns a handle for
the specified coder.make.BuildConfig object.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldcfg_name — Build configuration name


string

Build configuration name, specified as a string.


Data Types: char

Output Arguments
bldcfg_handle — BuildConfiguration object handle

Handle of coder.make.BuildConfiguration object

2-246
getBuildConfiguration

Examples
bldcfg_handle = h.getBuildConfiguration('Debug')

bldcfg_handle =

##############################################
# Build Configuration : Debug
# Description : Default debug settings for compiling/linking code
##############################################

ARFLAGS = /nologo $(ARDEBUG)


CFLAGS = $(cflags) $(CVARSFLAG) $(CFLAGS_ADDITIONAL) /c /Od $(CDEBUG)
CPPFLAGS = $(cflags) $(CVARSFLAG) $(CPPFLAGS_ADDITIONAL) /c /Od $(CPPDEBUG)
DOWNLOAD_FLAGS =
EXECUTE_FLAGS =
LDFLAGS = $(ldebug) $(conflags) $(LIBS_TOOLCHAIN) $(LDDEBUG)
MEX_CFLAGS =
MEX_LDFLAGS =
MAKE_FLAGS = -f $(MAKEFILE)
SHAREDLIB_LDFLAGS = $(ldebug) $(conflags) $(LIBS_TOOLCHAIN) -dll -def:$(DEF_FILE) $(LDDEBUG)

See Also
coder.make.ToolchainInfo.getBuildConfiguration |
coder.make.ToolchainInfo.removeBuildConfiguration
| coder.make.ToolchainInfo.setBuildConfiguration |
coder.make.ToolchainInfo.setBuildConfigurationOption

More About
• “About coder.make.ToolchainInfo”

2-247
2 Function Reference

getBuildTool
Class: coder.make.ToolchainInfo
Package: coder.make

Get BuildTool object

Syntax
bldtl_handle = h.getBuildTool(bldtl_name)

Description
bldtl_handle = h.getBuildTool(bldtl_name) returns the BuildTool object that
has the specified name.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldtl_name — Build tool name


string

Build tool name, specified as a string.


Data Types: char

Output Arguments
bldtl_handle — BuildTool object handle

Handle of coder.make.BuildTool object.

2-248
getBuildTool

Examples
bldtl_handle = h.getBuildTool('C Compiler')

bldtl_handle =

##############################################
# Build Tool: Intel C Compiler
##############################################

Language : 'C'
OptionsRegistry : {'C Compiler','CFLAGS'}
InputFileExtensions : {'Source'}
OutputFileExtensions : {'Object'}
DerivedFileExtensions : {'|>OBJ_EXT<|'}
SupportedOutputs : {'*'}
CommandPattern : '|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<||>OUTPUT<|'

# ---------
# Command
# ---------
CC = icl
CC_PATH =

# ------------
# Directives
# ------------
Debug = -Zi
Include =
IncludeSearchPath = -I
OutputFlag = -Fo
PreprocessorDefine = -D

# -----------------
# File Extensions
# -----------------
Header = .h
Object = .obj
Source = .c

2-249
2 Function Reference

See Also
coder.make.BuildTool | coder.make.ToolchainInfo.addBuildTool
| coder.make.ToolchainInfo.getBuildTool |
coder.make.ToolchainInfo.removeBuildTool |
coder.make.ToolchainInfo.setBuildTool

More About
• “About coder.make.ToolchainInfo”

2-250
getMacro

getMacro
Class: coder.make.ToolchainInfo
Package: coder.make

Get value of macro

Syntax
value = h.getMacro(macroname)

Description
value = h.getMacro(macroname) returns the value of the specified macro.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

macroname — Name of macro

Name of macro.

Output Arguments
macrovalue — Value of macro
string | cell

Value of the macro, specified as a string or cell array.

If the value contains MATLAB functions or other macros, ToolchainInfo interprets the
value of functions and macros.

2-251
2 Function Reference

Data Types: cell | char

Examples
h.setMacro('CYGWIN','C:\cygwin\');
h.getMacro('CYGWIN')

ans =

C:\cygwin\bin\

h.removeMacro('CYGWIN')

See Also
coder.make.ToolchainInfo.addMacro | coder.make.ToolchainInfo.getMacro
| coder.make.ToolchainInfo.removeMacro
| coder.make.ToolchainInfo.setMacro |
coder.make.ToolchainInfo.addIntrinsicMacros |
coder.make.ToolchainInfo.removeIntrinsicMacros

More About
• “About coder.make.ToolchainInfo”

2-252
getPostbuildTool

getPostbuildTool
Class: coder.make.ToolchainInfo
Package: coder.make

Get postbuild BuildTool object

Syntax
bldtl_handle = h.getPostbuildTool(bldtl_name)

Description
bldtl_handle = h.getPostbuildTool(bldtl_name) gets the named BuildTool
object from PostbuildTool and assigns it to a handle.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldtl_name — Build tool name


string

Build tool name, specified as a string.


Data Types: char

Output Arguments
bldtl_handle — BuildTool object handle

Handle of coder.make.BuildTool object.

2-253
2 Function Reference

Examples
h.getPostbuildTool('Download')

ans =

##############################################
# Build Tool: Download
##############################################

Language : ''
OptionsRegistry : {'Download','DOWNLOAD_FLAGS'}
InputFileExtensions : {}
OutputFileExtensions : {}
DerivedFileExtensions : {}
SupportedOutputs : {coder.make.enum.BuildOutput.EXECUTABLE}
CommandPattern : '|>TOOL<| |>TOOL_OPTIONS<|'

# ---------
# Command
# ---------
DOWNLOAD =
DOWNLOAD_PATH =

# ------------
# Directives
# ------------
(none)

# -----------------
# File Extensions
# -----------------
(none)

See Also
coder.make.ToolchainInfo.addPostbuildTool |
coder.make.ToolchainInfo.getPostbuildTool |
coder.make.ToolchainInfo.removePostbuildTool
| coder.make.ToolchainInfo.setPostbuildTool |
coder.make.ToolchainInfo.addPostDownloadTool |
coder.make.ToolchainInfo.addPostExecuteTool

2-254
getPostbuildTool

More About
• “About coder.make.ToolchainInfo”

2-255
2 Function Reference

getPrebuildTool
Class: coder.make.ToolchainInfo
Package: coder.make

Get prebuild BuildTool object

Syntax
bldtl_handle = tc.getPrebuildTool(bldtl_name)

Description
bldtl_handle = tc.getPrebuildTool(bldtl_name) gets the named BuildTool
object from PrebuildTool and assigns it to a handle.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldtl_name — Build tool name


string

Build tool name, specified as a string.


Data Types: char

Output Arguments
bldtl_handle — BuildTool object handle

Handle of coder.make.BuildTool object.

2-256
getPrebuildTool

Examples
h.getPrebuildTool(‘Copy Tool’)

ans =

##############################################
# Build Tool: Copy Tool
##############################################

Language : ''
OptionsRegistry : {'Copy','COPY_FLAGS'}
InputFileExtensions : {}
OutputFileExtensions : {}
DerivedFileExtensions : {}
SupportedOutputs : {coder.make.enum.BuildOutput.EXECUTABLE}
CommandPattern : '|>TOOL<| |>TOOL_OPTIONS<|'

# ---------
# Command
# ---------
COPY =
COPY_PATH =

# ------------
# Directives
# ------------
(none)

# -----------------
# File Extensions
# -----------------
(none)

See Also
coder.make.ToolchainInfo.addPrebuildTool |
coder.make.ToolchainInfo.getPrebuildTool |
coder.make.ToolchainInfo.removePrebuildTool |
coder.make.ToolchainInfo.setPrebuildTool

2-257
2 Function Reference

More About
• “About coder.make.ToolchainInfo”

2-258
coder.make.ToolchainInfo.getSupportedLanguages

coder.make.ToolchainInfo.getSupportedLanguages
Class: coder.make.ToolchainInfo
Package: coder.make

Get list of supported languages

Syntax
lng_list = h.getSupportedLanguages

Description
lng_list = h.getSupportedLanguages returns the list of supported code generation
languages for the current toolchain.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

Output Arguments
lng_list — List of supported languages
cell

List of supported languages, returned as a cell.

Attributes
Static true

2-259
2 Function Reference

To learn about attributes of methods, see Method Attributes in the MATLAB Object-
Oriented Programming documentation.

Examples
ans = h.getSupportedLanguages

ans =

'Asm/C' 'Asm/C++' 'Asm/C/C++' 'C' 'C++' 'C/C++'

See Also
coder.make.ToolchainInfo

More About
• “About coder.make.ToolchainInfo”

2-260
isAttribute

isAttribute
Class: coder.make.ToolchainInfo
Package: coder.make

Determine if attribute exists

Syntax
truefalse = h.isAttribute(att_name)

Description
truefalse = h.isAttribute(att_name) returns a logical
value that indicates whether the specified attribute is a member of
coder.make.ToolchainInfo.Attributes.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

att_name — Name of attribute


string

Name of attribute, specified as a string of alphanumeric characters.


Data Types: char

Output Arguments
truefalse — Logical value
boolean

2-261
2 Function Reference

Logical value: 0 = false, 1 = true, specified as a logical value.


Data Types: logical

Examples
h.addAttribute('FirstAttribute')
truefalse = h.isAttribute('FirstAttribute')

truefalse =

See Also
coder.make.ToolchainInfo.addAttribute |
coder.make.ToolchainInfo.getAttribute |
coder.make.ToolchainInfo.getAttributes
| coder.make.ToolchainInfo.isAttribute |
coder.make.ToolchainInfo.removeAttribute

More About
• “About coder.make.ToolchainInfo”

2-262
removeAttribute

removeAttribute
Class: coder.make.ToolchainInfo
Package: coder.make

Remove attribute

Syntax
h.removeAttribute(att_name)

Description
h.removeAttribute(att_name) removes the named attribute from
coder.make.ToolchainInfo.Attributes.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

att_name — Name of attribute


string

Name of attribute, specified as a string of alphanumeric characters.


Data Types: char

Examples
h.addAttribute('FirstAttribute')
h.isAttribute('FirstAttribute')

2-263
2 Function Reference

ans =

h.removeAttribute('FirstAttribute')
h.isAttribute('FirstAttribute')

ans =

See Also
coder.make.ToolchainInfo.addAttribute |
coder.make.ToolchainInfo.getAttribute |
coder.make.ToolchainInfo.getAttributes
| coder.make.ToolchainInfo.isAttribute |
coder.make.ToolchainInfo.removeAttribute

More About
• “About coder.make.ToolchainInfo”

2-264
removeBuildConfiguration

removeBuildConfiguration
Class: coder.make.ToolchainInfo
Package: coder.make

Remove build configuration

Syntax
h.removeBuildConfiguration(bldcfg_name)

Description
h.removeBuildConfiguration(bldcfg_name) removes the specified build
configuration object from coder.make.ToolchainInfo.BuildConfiguration.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldcfg_name — Build configuration name


string

Build configuration name, specified as a string.


Data Types: char

Examples
h.BuildConfigurations

ans =

2-265
2 Function Reference

# ----------------------------
# "BuildConfigurations" List
# ----------------------------
Debug = <coder.make.BuildConfiguration>
ExampleName = <coder.make.BuildConfiguration>
Faster Builds = <coder.make.BuildConfiguration>
Faster Runs = <coder.make.BuildConfiguration>

h.removeBuildConfiguration('ExampleName')
h.BuildConfigurations

ans =

# ----------------------------
# "BuildConfigurations" List
# ----------------------------
Debug = <coder.make.BuildConfiguration>
Faster Builds = <coder.make.BuildConfiguration>
Faster Runs = <coder.make.BuildConfiguration>

See Also
coder.make.ToolchainInfo.getBuildConfiguration |
coder.make.ToolchainInfo.removeBuildConfiguration
| coder.make.ToolchainInfo.setBuildConfiguration |
coder.make.ToolchainInfo.setBuildConfigurationOption

More About
• “About coder.make.ToolchainInfo”

2-266
removeBuildTool

removeBuildTool
Class: coder.make.ToolchainInfo
Package: coder.make

Remove BuildTool object from BuildTools

Syntax
h.removeBuildTool(bldtl_name)

Description
h.removeBuildTool(bldtl_name) removes the named build tool from BuildTools.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldtl_name — Build tool name


string

Build tool name, specified as a string.


Data Types: char

Examples
h.addBuildTool('ExampleBuildTool');
h.BuildTools

ans =

2-267
2 Function Reference

# -------------------
# "BuildTools" List
# -------------------
C Compiler = <coder.make.BuildTool>
C++ Compiler = <coder.make.BuildTool>
Archiver = <coder.make.BuildTool>
Linker = <coder.make.BuildTool>
MEX Tool = <coder.make.BuildTool>
ExampleBuildTool = <coder.make.BuildTool>

h.removeBuildTool('ExampleBuildTool')
h.BuildTools

ans =

# -------------------
# "BuildTools" List
# -------------------
C Compiler = <coder.make.BuildTool>
C++ Compiler = <coder.make.BuildTool>
Archiver = <coder.make.BuildTool>
Linker = <coder.make.BuildTool>
MEX Tool = <coder.make.BuildTool>

See Also
coder.make.BuildTool | coder.make.ToolchainInfo.addBuildTool
| coder.make.ToolchainInfo.getBuildTool |
coder.make.ToolchainInfo.removeBuildTool |
coder.make.ToolchainInfo.setBuildTool

More About
• “About coder.make.ToolchainInfo”

2-268
removeIntrinsicMacros

removeIntrinsicMacros
Class: coder.make.ToolchainInfo
Package: coder.make

Remove intrinsic macro

Syntax
h.removeIntrinsicMacros(intrnsc_macronames)

Description
h.removeIntrinsicMacros(intrnsc_macronames) removes the named intrinsic
macro from Macros.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

intrnsc_macronames — Intrinsic macro name or names

Intrinsic macro name or names, specified as a string or cell array of strings.

Examples
h.addIntrinsicMacros('GCCROOT')
h.getMacro('GCCROOT')

ans =

[]

2-269
2 Function Reference

h.removeIntrinsicMacros('GCCROOT')
h.getMacro('GCCROOT')

See Also
coder.make.ToolchainInfo.addMacro | coder.make.ToolchainInfo.getMacro
| coder.make.ToolchainInfo.removeMacro
| coder.make.ToolchainInfo.setMacro |
coder.make.ToolchainInfo.addIntrinsicMacros |
coder.make.ToolchainInfo.removeIntrinsicMacros

More About
• “About coder.make.ToolchainInfo”

2-270
removeMacro

removeMacro
Class: coder.make.ToolchainInfo
Package: coder.make

Remove macro from Macros

Syntax
h.removeMacro(macroname)

Description
h.removeMacro(macroname) removes a macro from
coder.make.ToolchainInfo.Macros.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

macroname — Name of macro

Name of macro.

Examples
h.setMacro('CYGWIN','C:\cygwin\');
h.getMacro('CYGWIN')

ans =

C:\cygwin\bin\

2-271
2 Function Reference

h.removeMacro('CYGWIN')

See Also
coder.make.ToolchainInfo.addMacro | coder.make.ToolchainInfo.getMacro
| coder.make.ToolchainInfo.removeMacro
| coder.make.ToolchainInfo.setMacro |
coder.make.ToolchainInfo.addIntrinsicMacros |
coder.make.ToolchainInfo.removeIntrinsicMacros

More About
• “About coder.make.ToolchainInfo”

2-272
removePostbuildTool

removePostbuildTool
Class: coder.make.ToolchainInfo
Package: coder.make

Remove postbuild build tool

Syntax
h.removePostbuildTool(bldtl_name)

Description
h.removePostbuildTool(bldtl_name) removes the named build tool from
PostbuildTools.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldtl_name — Build tool name


string

Build tool name, specified as a string.


Data Types: char

Examples
h.addPostbuildTool('copier');
h.PostbuildTools

2-273
2 Function Reference

ans =

# -----------------------
# "PostbuildTools" List
# -----------------------
copier = <coder.make.BuildTool>
Download = <coder.make.BuildTool>
Execute = <coder.make.BuildTool>

h.removePostbuildTool('copier')

See Also
coder.make.ToolchainInfo.addPostbuildTool |
coder.make.ToolchainInfo.getPostbuildTool |
coder.make.ToolchainInfo.removePostbuildTool
| coder.make.ToolchainInfo.setPostbuildTool |
coder.make.ToolchainInfo.addPostDownloadTool |
coder.make.ToolchainInfo.addPostExecuteTool

More About
• “About coder.make.ToolchainInfo”

2-274
removePrebuildTool

removePrebuildTool
Class: coder.make.ToolchainInfo
Package: coder.make

Remove prebuild build tool

Syntax
h.removePrebuildTool(bldtl_name)

Description
h.removePrebuildTool(bldtl_name) removes the named build tool from
PrebuildTools.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldtl_name — Build tool name


string

Build tool name, specified as a string.


Data Types: char

Examples
If you have an example coder.make.ToolchainInfo.PrebuildTools object that
contains a BuildTool object such as copyFiles:
h.PrebuildTools

2-275
2 Function Reference

ans =

# ----------------------
# "PrebuildTools" List
# ----------------------
copyFiles = <coder.make.BuildTool>

h.removePrebuildTool('copyFiles')

See Also
coder.make.ToolchainInfo.addPrebuildTool |
coder.make.ToolchainInfo.getPrebuildTool |
coder.make.ToolchainInfo.removePrebuildTool |
coder.make.ToolchainInfo.setPrebuildTool

More About
• “About coder.make.ToolchainInfo”

2-276
setBuildConfiguration

setBuildConfiguration
Class: coder.make.ToolchainInfo
Package: coder.make

Set value of specified build configuration

Syntax
h.setBuildConfiguration(bldcfg_name, bldcfg_handle)

Description
h.setBuildConfiguration(bldcfg_name, bldcfg_handle)
assigns a build configuration object to a build configuration in
coder.make.ToolchainInfo.BuildConfigurations.

Tips
Before you can use this method, add a build configuration to BuildConfigurations
using coder.make.ToolchainInfo.addBuildConfiguration with a bldcfg_name
argument.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldcfg_name — Build configuration name


string

Build configuration name, specified as a string.


Data Types: char

2-277
2 Function Reference

bldcfg_handle — BuildConfiguration object handle


Handle of coder.make.BuildConfiguration object

Examples
h.getBuildConfigurations

ans =

'Faster Builds'
'Faster Runs'
'Debug'

bldcfg_handle = h.getBuildConfiguration('Debug')
bldcfg_handle =

##############################################
# Build Configuration : Debug
# Description : Default debug settings for compiling/linking code
##############################################

ARFLAGS = /nologo $(ARDEBUG)


CFLAGS = $(cflags) $(CVARSFLAG) $(CFLAGS_ADDITIONAL) /c /Od $(CDEBUG)
CPPFLAGS = $(cflags) $(CVARSFLAG) $(CPPFLAGS_ADDITIONAL) /c /Od $(CPPDEBUG)
DOWNLOAD_FLAGS =
EXECUTE_FLAGS =
LDFLAGS = $(ldebug) $(conflags) $(LIBS_TOOLCHAIN) $(LDDEBUG)
MEX_CFLAGS =
MEX_LDFLAGS =
MAKE_FLAGS = -f $(MAKEFILE)
SHAREDLIB_LDFLAGS = $(ldebug) $(conflags) $(LIBS_TOOLCHAIN) -dll -def:$(DEF_FILE) $(LDDEBUG)

h.addBuildConfiguration('Debug2','Variant debugging configuration')


h.setBuildConfiguration('Debug2',bldcfg_handle)
h.getBuildConfigurations

ans =

'Faster Builds'
'Faster Runs'
'Debug'
'Debug2'

See Also
coder.make.ToolchainInfo.getBuildConfiguration |
coder.make.ToolchainInfo.removeBuildConfiguration

2-278
setBuildConfiguration

| coder.make.ToolchainInfo.setBuildConfiguration |
coder.make.ToolchainInfo.setBuildConfigurationOption

More About
• “About coder.make.ToolchainInfo”

2-279
2 Function Reference

setBuildConfigurationOption
Class: coder.make.ToolchainInfo
Package: coder.make

Sets value of build tool options for build configuration

Syntax
h.setBuildConfigurationOption(buildconfignames, options)

Description
h.setBuildConfigurationOption(buildconfignames, options) sets
option values for the named coder.make.BuildConfiguration objects in
coder.make.ToolchainInfo.BuildConfigurations.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

buildconfignames — Build configuration names

Build configuration name or 'all', specified as a string.

buildobjectname — BuildTool object name

BuildTool object name, specified as a string.

options — Build configuration options

Build configuration options, specified as a string.

2-280
setBuildConfigurationOption

Examples
To update a specific BuildConfiguration object or objects:

h = coder.make.ToolchainInfo
h.setBuildConfigurationOption('Faster Runs','C Compiler','-c -g')

To update all BuildConfiguration objects:

h = coder.make.ToolchainInfo
tc.setBuildConfigurationOption(‘all’,‘C Compiler’,‘-c -g’)

See Also
coder.make.ToolchainInfo.getBuildConfiguration |
coder.make.ToolchainInfo.removeBuildConfiguration
| coder.make.ToolchainInfo.setBuildConfiguration |
coder.make.ToolchainInfo.setBuildConfigurationOption

More About
• “About coder.make.ToolchainInfo”

2-281
2 Function Reference

setBuilderApplication
Class: coder.make.ToolchainInfo
Package: coder.make

Update builder application to work on specific platform

Syntax
h.setBuilderApplication(platform)

Description
h.setBuilderApplication(platform) updates
options in the coder.make.BuildTool object in
coder.make.ToolchainInfo.BuilderApplication to work on a specific platform.

Tips
• You must use this method you if you plan to use the custom toolchain on computer
running Windows and the value of coder.make.ToolchainInfo.BuildArtifact
is gmake makefile.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

platform — Host computer platform


string

Host computer platform, specified as a scalar. The values can be:

• WIN32

2-282
setBuilderApplication

• WIN64
• MACI64
• GLNXA64

Data Types: char

Examples
The intel_tc.m file from “Adding a Custom Toolchain”, uses the following lines to
update the BuilderApplication property:

% ------------------------------
% Builder
% ------------------------------

tc.setBuilderApplication(tc.Platform);

2-283
2 Function Reference

setBuildTool
Class: coder.make.ToolchainInfo
Package: coder.make

Assign BuildTool object to named build tool in BuildTools

Syntax
h.setBuildTool(bldtl_name, bldtl_handle)

Description
h.setBuildTool(bldtl_name, bldtl_handle) assigns a BuildTool object to the
named build tool in coder.make.ToolchainInfo.BuildTools.

Tips
Refer to the “Example” on page 3-134 for coder.make.BuildTool for an example of
how to create a BuildTool object.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldtl_name — Build tool name


string

Build tool name, specified as a string.


Data Types: char

2-284
setBuildTool

bldtl_handle — BuildTool object handle

Handle of coder.make.BuildTool object.

Examples
h = coder.make.ToolchainInfo;
bt = coder.make.BuildTool('examplename')
h.setBuildTool('Archiver',bt)

See Also
coder.make.BuildTool | coder.make.ToolchainInfo.addBuildTool
| coder.make.ToolchainInfo.getBuildTool |
coder.make.ToolchainInfo.removeBuildTool |
coder.make.ToolchainInfo.setBuildTool

More About
• “About coder.make.ToolchainInfo”

2-285
2 Function Reference

setMacro
Class: coder.make.ToolchainInfo
Package: coder.make

Set value of macro

Syntax
h.setMacro(macroname, value)

Description
h.setMacro(macroname, value) sets the value of a macro.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

macroname — Name of macro

Name of macro.

macrovalue — Value of macro


string | cell

Value of the macro, specified as a string or cell array.

If the value contains MATLAB functions or other macros, ToolchainInfo interprets the
value of functions and macros.
Data Types: cell | char

2-286
setMacro

Examples
h.setMacro('CYGWIN','C:\cygwin\');
h.getMacro('CYGWIN')

ans =

C:\cygwin\bin\

h.removeMacro('CYGWIN')

See Also
coder.make.ToolchainInfo.addMacro | coder.make.ToolchainInfo.getMacro
| coder.make.ToolchainInfo.removeMacro
| coder.make.ToolchainInfo.setMacro |
coder.make.ToolchainInfo.addIntrinsicMacros |
coder.make.ToolchainInfo.removeIntrinsicMacros

More About
• “About coder.make.ToolchainInfo”

2-287
2 Function Reference

setPostbuildTool
Class: coder.make.ToolchainInfo
Package: coder.make

Assign BuildTool object to PostbuildTool tool in PostbuildTools

Syntax
h.setPostbuildTool(bldtl_name, bldtl_handle)

Description
h.setPostbuildTool(bldtl_name, bldtl_handle) assigns a BuildTool object to
the named build tool in coder.make.ToolchainInfo.PostbuildTools.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldtl_name — Build tool name


string

Build tool name, specified as a string.


Data Types: char

bldtl_handle — BuildTool object handle

Handle of coder.make.BuildTool object.

Examples
h = coder.make.ToolchainInfo;

2-288
setPostbuildTool

bt = coder.make.BuildTool('examplename')
h.addPostbuildTool('toolname')
h.setPostbuildTool('toolname',bt)

See Also
coder.make.ToolchainInfo.addPostbuildTool |
coder.make.ToolchainInfo.getPostbuildTool |
coder.make.ToolchainInfo.removePostbuildTool
| coder.make.ToolchainInfo.setPostbuildTool |
coder.make.ToolchainInfo.addPostDownloadTool |
coder.make.ToolchainInfo.addPostExecuteTool

More About
• “About coder.make.ToolchainInfo”

2-289
2 Function Reference

setPrebuildTool
Class: coder.make.ToolchainInfo
Package: coder.make

Assign BuildTool object to named PrebuildTool in PrebuildTools

Syntax
h.setPrebuildTool(bldtl_name, bldtl_handle)

Description
h.setPrebuildTool(bldtl_name, bldtl_handle) assigns a BuildTool object to
the named build tool in coder.make.ToolchainInfo.PrebuildTools.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

bldtl_name — Build tool name


string

Build tool name, specified as a string.


Data Types: char

Examples
h = coder.make.ToolchainInfo;
bt = coder.make.BuildTool('examplename');
h.addPrebuildTool('toolname');
h.setPrebuildTool('toolname',bt)

2-290
setPrebuildTool

See Also
coder.make.ToolchainInfo.addPrebuildTool |
coder.make.ToolchainInfo.getPrebuildTool |
coder.make.ToolchainInfo.removePrebuildTool |
coder.make.ToolchainInfo.setPrebuildTool

More About
• “About coder.make.ToolchainInfo”

2-291
2 Function Reference

setup
Class: coder.make.ToolchainInfo
Package: coder.make

Invoke toolchain setup commands specified by MATLABSetup and ShellSetup

Syntax
h.setup

Description
h.setup runs setup commands before starting the software build process. First, it runs
the commands specified by coder.make.ToolchainInfo.MATLABSetup, and then it
runs the commands specified by coder.make.ToolchainInfo.ShellSetup.

The commands in MATLABSetup run in your MATLAB software.

The commands in ShellSetup run as system calls to the standard input of the operating
system on your host computer. These commands are similar to what you enter when you
use the command line.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

Output Arguments
success — Response indicating whether setup completed
double

Response indicating whether setup completed (0 = false, 1 = true), returned as a double.

2-292
setup

report — Detailed information generated by setup commands


string

Detailed information generated by the setup commands, returned as a string.

Examples
[success,report] = h.setup

success =

report =

''

See Also
coder.make.ToolchainInfo.cleanup | coder.make.ToolchainInfo.validate

More About
• “About coder.make.ToolchainInfo”

2-293
2 Function Reference

validate
Class: coder.make.ToolchainInfo
Package: coder.make

Validate toolchain

Syntax
h.validate
h.validate('setup','cleanup')
[success, report] = h.validate (___)

Description
h.validate validates the toolchain object and generates errors if any properties are
incorrectly defined.

h.validate('setup','cleanup') evaluates the setup callbacks (ShellSetup


and MATLABSetup) of the toolchain object before validation and evaluates the cleanup
callbacks (ShellCleanup and MATLABCleanup) of the toolchain object after validation.
The Configuration Parameters dialog box executes this version of validate when
validating the toolchain.

[success, report] = h.validate (___) validates the toolchain object, generates


errors if any properties are incorrectly defined, and returns optional output arguments.

Input Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

'setup' — Setup argument for validate operation.

Evaluates coder.make.ToolchainInfo.setup for the toolchain.

2-294
validate

'cleanup' — Cleanup argument for validate operation.

Evaluates coder.make.ToolchainInfo.cleanup for the toolchain.

Output Arguments
success — Response indicating whether validate passed
double

Response indicating whether validate passed, returned as a numeric value. If any of


the property values the method checks are invalid, the method returns 0. Otherwise, it
returns 1.

report — Information about which properties are invalid


string

Information about which properties are invalid. Only available when the method returns
0.

Examples

Validate a toolchain before it has been installed


If you validate a default toolchain before all the build tools are specified, validate
notifies you of the build tools that are not specified.

h = coder.make.ToolchainInfo;
[success,report] = h.validate

success =

report =

Toolchain Validation Result: Passed

Validation report:

2-295
2 Function Reference

### Validation of build tool "C Compiler"


Skipped. No "C Compiler" build tool is specified.

### Validation of build tool "C++ Compiler"


Skipped. No "C++ Compiler" build tool is specified.

### Validation of build tool "Archiver"


Skipped. No "Archiver" build tool is specified.

### Validation of build tool "Linker"


Skipped. No "Linker" build tool is specified.

### Validation of build tool "MEX Tool"


Checking for existence of path: $(MATLAB_BIN)
Passed.
Checking for tool command: mex
Passed.

### Validation of build tool "Download"


Skipped. No "Download" build tool is specified.

### Validation of build tool "Execute"


Skipped. "Execute" build tool "$(PRODUCT)" cannot be validated.

### Validation of build tool "GMAKE Utility"


Checking for existence of path: %MATLAB%\bin\win64
Passed.
Checking for tool command: gmake
Passed.

### Checking for undeclared macros ...


Passed.

Validate a toolchain before it has been installed


[success,report] = tc.validate

Error using ToolchainInfo.validate (line 270)


Validation error(s):
### Validating other build tools ...

Unable to locate build tool "Intel C Compiler": icl


Unable to locate build tool "Intel C++ Compiler": icl

2-296
validate

Unable to locate build tool "Intel C/C++ Archiver": xilib


Unable to locate build tool "Intel C/C++ Linker": xilink
Unable to locate build tool "NMAKE Utility": nmake

See Also
coder.make.ToolchainInfo.cleanup | coder.make.ToolchainInfo.setup

More About
• “About coder.make.ToolchainInfo”

2-297
2 Function Reference

getHardwareImplementation
Class: coder.BuildConfig
Package: coder

Get handle of copy of hardware implementation object

Syntax
hw = bldcfg.getHardwareImplementation()

Description
hw = bldcfg.getHardwareImplementation() returns the handle of a copy of the
hardware implementation object.

Input Arguments
bldcfg

coder.BuildConfig object.

Output Arguments
hw

Handle of copy of hardware implementation object.

See Also
coder.HardwareImplementation

2-298
getStdLibInfo

getStdLibInfo
Class: coder.BuildConfig
Package: coder

Get standard library information

Syntax
[linkLibPath,linkLibExt,execLibExt,libPrefix]=
bldcfg.getStdLibInfo()

Description
[linkLibPath,linkLibExt,execLibExt,libPrefix]=
bldcfg.getStdLibInfo() returns strings representing the:

• Standard MATLAB architecture-specific library path


• Platform-specific library file extension for use at link time
• Platform-specific library file extension for use at run time
• Standard architecture-specific library name prefix

Input Arguments
bldcfg

coder.BuildConfig object.

Output Arguments
linkLibPath

Standard MATLAB architecture-specific library path specified as a string. The string can
be empty.

2-299
2 Function Reference

linkLibExt

Platform-specific library file extension for use at link time, specified as a string. The
value is one of '.lib','.dylib','.so', ''.

execLibExt

Platform-specific library file extension for use at run time, specified as a string. the value
is one of '.dll','.dylib','.so', ''.

linkPrefix

Standard architecture-specific library name prefix, specified as a string. The string can
be empty.

2-300
getTargetLang

getTargetLang
Class: coder.BuildConfig
Package: coder

Get target code generation language

Syntax
lang = bldcfg.getTargetLang()

Description
lang = bldcfg.getTargetLang() returns a string containing the target code
generation language.

Input Arguments
bldcfg

coder.BuildConfig object.

Output Arguments
lang

A string containing the target code generation language. The value is ‘C’ or ‘C++’.

2-301
2 Function Reference

getToolchainInfo
Class: coder.BuildConfig
Package: coder

Returns handle of copy of toolchain information object

Syntax
tc = bldcfg.getToolchainInfo()

Description
tc = bldcfg.getToolchainInfo() returns a handle of a copy of the toolchain
information object.

Input Arguments
bldcfg

coder.BuildConfig object.

Output Arguments
tc

Handle of copy of toolchain information object.

See Also
coder.make.ToolchainInfo

2-302
isCodeGenTarget

isCodeGenTarget
Class: coder.BuildConfig
Package: coder

Determine if build configuration represents specified target

Syntax
tf = bldcfg.isCodeGenTarget(target)

Description
tf = bldcfg.isCodeGenTarget(target) returns true (1) if the code generation
target of the current build configuration represents the code generation target specified
by target. Otherwise, it returns false (0).

Input Arguments
bldcfg

coder.BuildConfig object.

target

Code generation target specified as a string or cell array of strings.

Specify For code generation target


'rtw' C/C++ dynamic Library, C/C++ static library, or C/C
++ executable
'sfun' S-function (Simulation)
'mex' MEX-function

Specify target as a cell array of strings to test if the code generation target of the build
configuration represents one of the targets specified in the cell array.

2-303
2 Function Reference

For example:

...
mytarget = {'sfun','mex'};
tf = bldcfg.isCodeGenTarget(mytarget);
...
tests whether the build context represents an S-function target or a MEX-function target.

Output Arguments
tf

The value is true (1) if the code generation target of the build configuration represents
the code generation target specified by target. Otherwise, the value is false (0).

See Also
coder.target

2-304
isMatlabHostTarget

isMatlabHostTarget
Class: coder.BuildConfig
Package: coder

Determine if hardware implementation object target is MATLAB host computer

Syntax
tf = bldcfg.isMatlabHostTarget()

Description
tf = bldcfg.isMatlabHostTarget() returns true (1) if the current hardware
implementation object targets the MATLAB host computer. Otherwise, it returns false
(0).

Input Arguments
bldcfg

coder.BuildConfig object.

Output Arguments
tf

Value is true (1) if the current hardware implementation object targets the MATLAB
host computer. Otherwise, the value is false (0).

See Also
coder.HardwareImplementation

2-305
2 Function Reference

isHeterogeneous
Class: coder.CellType
Package: coder

Determine whether cell array type represents a heterogeneous cell array

Syntax
tf = isHeterogeneous(t)

Description
tf = isHeterogeneous(t) returns true if the coder.CellType object t is
heterogeneous. Otherwise, it returns false.

Examples
Determine Whether Cell Array Type Is Heterogeneous

Create a coder.CellType object for a cell array whose elements have different classes.

t = coder.typeof({'a', 1})

t =

coder.CellType
1x2 heterogeneous cell
f0: 1x1 char
f1: 1x1 double

Determine whether the coder.CellType object represents a heterogeneous cell array.

isHeterogeneous(t)

ans =

2-306
isHeterogeneous

Test for Heterogeneous Cell Array Type Before Executing Code

Write a function assign_name. If the input type t is heterogeneous, the function returns
a copy of t. The copy specifies the name for the structure type that represents the cell
array type in the generated code.
function ts = assign_name(t, str_name)
assert(isHeterogeneous(t));
ts = coder.cstructname(t, str_name);
disp ts
end

Create a homogeneous type tc.


tc = coder.typeof({1 2 3});

Pass tc to make_varsize.
tc1 = assign_name(tc, 'myname')

The assertions fails because tc is not heterogeneous.

Create a heterogeneous type tc.


tc = coder.typeof({'a' 1});

Pass tc to make_varsize.
tc1 = assign_name(tc, 'myname')

tc1 =

coder.CellType
1x2 heterogeneous cell myname
f0: 1x1 char
f1: 1x1 double

• “Specify Cell Array Inputs at the Command Line”

Tips
• coder.typeof determines whether the cell array type is homogeneous
or heterogeneous. If the cell array elements have the same class and size,

2-307
2 Function Reference

coder.typeof returns a homogeneous cell array type. If the elements have


different classes, coder.typeof returns a heterogeneous cell array type. For
some cell arrays, the classification as homogeneous or heterogeneous is ambiguous.
For example, the type for {1 [2 3]} can be a 1x2 heterogeneous type. The first
element is double and the second element is 1x2 double. The type can also be a
1x3 homogeneous type in which the elements have class double and size 1x:2.
For these ambiguous cases, coder.typeof uses heuristics to classify the type
as homogeneous or heterogeneous. If you want a different classification, use the
makeHomogeneous or makeHeterogeneous methods. The makeHomogeneous
method makes a homogeneous copy of a type. The makeHeterogeneous method
makes a heterogeneous copy of a type.

The makeHomogeneous and makeHeterogeneous methods permanently assign the


classification as homogeneous and heterogeneous, respectively. You cannot later use
one of these methods to create a copy that has a different classification.

See Also
coder.newtype | coder.typeof

More About
• “Homogeneous vs. Heterogeneous Cell Arrays”

Introduced in R2015b

2-308
isHomogeneous

isHomogeneous
Class: coder.CellType
Package: coder

Determine whether cell array type represents a homogeneous cell array

Syntax
tf = isHomogeneous(t)

Description
tf = isHomogeneous(t) returns true if the coder.CellType object t represents a
homogeneous cell array. Otherwise, it returns false.

Examples
Determine Whether Cell Array Type Is Homogeneous.

Create a coder.CellType object for a cell array whose elements have the same class
and size.

t = coder.typeof({1 2 3})

t =

coder.CellType
1x3 homogeneous cell
base: 1x1 double

Determine whether the coder.CellType object represents a homogeneous cell array.

isHomogeneous(t)

ans =

2-309
2 Function Reference

Test for a Homogeneous Cell Array Type Before Executing Code

Write a function make_varsize. If the input type t is homogeneous, the function


returns a variable-size copy of t.

function c = make_varsize(t, n)
assert(isHomogeneous(t));
c = coder.typeof(t, [n n], [1 1]);
end

Create a heterogeneous type tc.

tc = coder.typeof({'a', 1});

Pass tc to make_varsize.

tc1 = make_varsize(tc, 5)

The assertion fails because tc is heterogeneous.

Create a homogeneous type tc.

tc = coder.typeof({1 2 3});

Pass tc to make_varsize.

tc1 = make_varsize(tc, 5)

tc1 =

coder.CellType
:5x:5 homogeneous cell
base: 1x1 double

• “Specify Cell Array Inputs at the Command Line”

Tips
• coder.typeof determines whether the cell array type is homogeneous
or heterogeneous. If the cell array elements have the same class and size,
coder.typeof returns a homogeneous cell array type. If the elements have

2-310
isHomogeneous

different classes, coder.typeof returns a heterogeneous cell array type. For


some cell arrays, the classification as homogeneous or heterogeneous is ambiguous.
For example, the type for {1 [2 3]} can be a 1x2 heterogeneous type. The first
element is double and the second element is 1x2 double. The type can also be a
1x3 homogeneous type in which the elements have class double and size 1x:2.
For these ambiguous cases, coder.typeof uses heuristics to classify the type
as homogeneous or heterogeneous. If you want a different classification, use the
makeHomogeneous or makeHeterogeneous methods. The makeHomogeneous
method makes a homogeneous copy of a type. The makeHeterogeneous method
makes a heterogeneous copy of a type.

The makeHomogeneous and makeHeterogeneous methods permanently assign the


classification as homogeneous and heterogeneous, respectively. You cannot later use
one of these methods to create a copy that has a different classification.

See Also
coder.newtype | coder.typeof

More About
• “Homogeneous vs. Heterogeneous Cell Arrays”

Introduced in R2015b

2-311
2 Function Reference

makeHeterogeneous
Class: coder.CellType
Package: coder

Make a heterogeneous copy of a cell array type

Syntax
newt = makeHeterogeneous(t)
t = makeHeterogeneous(t)

Description
newt = makeHeterogeneous(t) creates a coder.CellType object for a
heterogeneous cell array from the coder.CellType object t. t cannot represent a
variable-size cell array.

The classification as heterogeneous is permanent. You cannot later create a homogeneous


coder.CellType object from newt.

t = makeHeterogeneous(t) creates a heterogeneous coder.CellType object from t


and replaces t with the new object.

Examples
Replace a Homogeneous Cell Array Type with a Heterogeneous Cell Array Type

Create a cell array type t whose elements have the same class and size.

t = coder.typeof({1 2 3})

t =

coder.CellType
1x3 homogeneous cell
base: 1x1 double

2-312
makeHeterogeneous

The cell array type is homogeneous.

Replace t with a cell array type for a heterogeneous cell array.

t = makeHeterogeneous(t)

coder.CellType
1x3 heterogeneous cell
f0: 1x1 double
f1: 1x1 double
f2: 1x1 double

The cell array type is heterogeneous. The elements have the size and class of the original
homogeneous cell array type.

• “Specify Cell Array Inputs at the Command Line”

Tips
• coder.typeof determines whether the cell array type is homogeneous
or heterogeneous. If the cell array elements have the same class and size,
coder.typeof returns a homogeneous cell array type. If the elements have different
classes, coder.typeof returns a heterogeneous cell array type. For some cell arrays,
the classification as homogeneous or heterogeneous is ambiguous. For example,
the type for {1 [2 3]} can be a 1x2 heterogeneous type. The first element is double
and the second element is 1x2 double. The type can also be a 1x3 homogeneous
type in which the elements have class double and size 1x:2. For these ambiguous
cases, coder.typeof uses heuristics to classify the type as homogeneous or
heterogeneous. If you want a different classification, use the makeHomogeneous or
makeHeterogeneous methods.

See Also
coder.newtype | coder.typeof

More About
• “Homogeneous vs. Heterogeneous Cell Arrays”

Introduced in R2015b

2-313
2 Function Reference

makeHomogeneous
Class: coder.CellType
Package: coder

Create a homogeneous copy of a cell array type

Syntax
newt = makeHomogeneous(t)
t = makeHomogeneous(t)

Description
newt = makeHomogeneous(t) creates a coder.CellType object for a homogeneous
cell array newt from the coder.CellType object t.

To create newt, the makeHomogeneous method must determine a size and class that
represent all elements of t:

• If the elements of t have the same class, but different sizes, the elements of newt are
variable size with upper bounds that accommodate the elements of t.
• If the elements of t have different classes, for example, char and double,
the makeHomogeneous method cannot create a coder.CellType object for a
homogeneous cell array.

If you use coder.cstructname to specify a name for the structure type that represents
t in the generated code, you cannot create a homogeneous coder.CellType object from
t.

The classification as homogeneous is permanent. You cannot later create a heterogeneous


coder.CellType object from newt.

t = makeHomogeneous(t) creates a homogeneous coder.CellType object from t and


replaces t with the new object.

2-314
makeHomogeneous

Examples
Replace a Heterogeneous Cell Array Type with a Homogeneous Cell Array Type

Create a cell array type t whose elements have the same class, but different sizes.
t = coder.typeof({1 [2 3]})

t =

coder.CellType
1x2 heterogeneous cell
f0: 1x1 double
f1: 1x2 double

The cell array type is heterogeneous.

Replace t with a cell array type for a homogeneous cell array.


t = makeHomogeneous(t)

t =

coder.CellType
1x2 homogeneous cell
base: 1x:2 double

The new cell array type is homogeneous.

Tips
• coder.typeof determines whether the cell array type is homogeneous
or heterogeneous. If the cell array elements have the same class and size,
coder.typeof returns a homogeneous cell array type. If the elements have different
classes, coder.typeof returns a heterogeneous cell array type. For some cell arrays,
the classification as homogeneous or heterogeneous is ambiguous. For example,
the type for {1 [2 3]} can be a 1x2 heterogeneous type. The first element is double
and the second element is 1x2 double. The type can also be a 1x3 homogeneous
type in which the elements have class double and size 1x:2. For these ambiguous
cases, coder.typeof uses heuristics to classify the type as homogeneous or
heterogeneous. If you want a different classification, use the makeHomogeneous or
makeHeterogeneous methods.

2-315
2 Function Reference

See Also
coder.cstructname | coder.newtype | coder.typeof

More About
• “Homogeneous vs. Heterogeneous Cell Arrays”

Introduced in R2015b

2-316
coder.ExternalDependency.getDescriptiveName

coder.ExternalDependency.getDescriptiveName
Class: coder.ExternalDependency
Package: coder

Return descriptive name for external dependency

Syntax
extname = coder.ExternalDependency.getDescriptiveName(bldcfg)

Description
extname = coder.ExternalDependency.getDescriptiveName(bldcfg) returns
the name that you want to associate with an “external dependency” on page 2-318. The
code generation software uses the external dependency name for error messages.

Input Arguments
bldcfg

coder.BuildConfig object. Use coder.BuildConfig methods to get information


about the “build context” on page 2-318

You can use this information when you want to return different names based on the build
context.

Output Arguments
extname

External dependency name returned as a string.

2-317
2 Function Reference

Definitions

external dependency
External code interface represented by a class derived from a
coder.ExternalDependency class. The external code can be a library, object files, or
C/C++ source.

build context
Information used by the build process including:

• Target language
• Code generation target
• Target hardware
• Build toolchain

Examples
Return external dependency name

Define a method that always returns the same name.


function myextname = getDescriptiveName(~)
myextname = 'MyLibrary'
end

Return external library name based on the code generation target

Define a method that uses the build context to determine the name.
function myextname = getDescriptiveName(context)
if context.isMatlabHostTarget()
myextname = 'MyLibary_MatlabHost';
else
myextname = 'MyLibrary_Local';
end
end

2-318
coder.ExternalDependency.isSupportedContext

coder.ExternalDependency.isSupportedContext
Class: coder.ExternalDependency
Package: coder

Determine if build context supports external dependency

Syntax
tf = coder.ExternalDependency.isSupportedContext(bldcfg)

Description
tf = coder.ExternalDependency.isSupportedContext(bldcfg) returns true (1)
if you can use the “external dependency” on page 2-320 in the current “build context”
on page 2-320 . You must provide this method in the class definition for a class that
derives from coder.ExternalDependency.

If you cannot use the “external dependency” on page 2-320 in the current “build
context” on page 2-320, display an error message and stop code generation. The
error message must describe why you cannot use the external dependency in this
build context. If the method returns false (0), the code generation software uses a
default error message. The default error message uses the name returned by the
getDescriptiveName method of the coder.ExternalDependency class.

Use coder.BuildConfig methods to determine if you can use the external dependency
in the current build context.

Input Arguments
bldcfg

coder.BuildConfig object. Use coder.BuildConfig methods to get information


about the “build context” on page 2-320.

2-319
2 Function Reference

Output Arguments
tf

Value is true (1) if the build context supports the external dependency.

Definitions
external dependency
External code interface represented by a class derived from
coder.ExternalDependency class. The external code can be a library, object file, or C/
C++ source.

build context
Information used by the build process including:

• Target language
• Code generation target
• Target hardware
• Build toolchain

Examples
Report error when build context does not support external library

This method returns true(1) if the code generation target is a MATLAB host target.
Otherwise, the method reports an error and stops code generation.

Write isSupportedContext method.


function tf = isSupportedContext(ctx)
if ctx.isMatlabHostTarget()
tf = true;
else

2-320
coder.ExternalDependency.isSupportedContext

error('adder library not available for this target');


end
end

2-321
2 Function Reference

coder.ExternalDependency.updateBuildInfo
Class: coder.ExternalDependency
Package: coder

Update build information

Syntax
coder.ExternalDependency.updateBuildInfo(buildInfo, bldcfg)

Description
coder.ExternalDependency.updateBuildInfo(buildInfo, bldcfg) updates
the build information object whose handle is buildInfo. After code generation, the
build information object has standard information. Use this method to provide additional
information required to link to external code. Use coder.BuildConfig methods to get
information about the “build context” on page 2-323.

You must provide this method in the class definition for a class that derives from
coder.ExternalDependency.

Input Arguments
buildInfo

Handle of build information object.

bldcfg

coder.BuildConfig object. Use coder.BuildConfig methods to get information


about the “build context” on page 2-323.

2-322
coder.ExternalDependency.updateBuildInfo

Definitions

build context
Information used by the build process including:

• Target language
• Code generation target
• Target hardware
• Build toolchain

More About
• “Build Information Object”
• “Build Information Methods”

2-323
2 Function Reference

addDesignRangeSpecification
Class: coder.FixptConfig
Package: coder

Add design range specification to parameter

Syntax
addDesignRangeSpecification(fcnName,paramName,designMin, designMax)

Description
addDesignRangeSpecification(fcnName,paramName,designMin, designMax)
specifies the minimum and maximum values allowed for the parameter, paramName, in
function, fcnName. The fixed-point conversion process uses this design range information
to derive ranges for downstream variables in the code.

Input Arguments
fcnName — Function name
string

Function name, specified as a string.


Data Types: char

paramName — Parameter name


string

Parameter name, specified as a string.


Data Types: char

designMin — Minimum value allowed for this parameter


scalar

Minimum value allowed for this parameter, specified as a scalar double.

2-324
addDesignRangeSpecification

Data Types: double

designMax — Maximum value allowed for this parameter


scalar

Maximum value allowed for this parameter, specified as a scalar double.


Data Types: double

Examples

Add a Design Range Specification


% Set up the fixed-point configuration object
fixptcfg = coder.config('fixpt');
fixptcfg.TestBenchName = 'dti_test';
fixptcfg.addDesignRangeSpecification('dti', 'u_in', -1.0, 1.0)
fixptcfg.ComputeDerivedRanges = true;

%Set up C code configuration object


cfg = coder.config('lib');
% Derive ranges and generate fixed-point C code
codegen -config cfg -float2fixed fixptcfg dti -report

See Also
coder.FixptConfig | coder.FixptConfig.hasDesignRangeSpecification
| coder.FixptConfig.removeDesignRangeSpecification
| coder.FixptConfig.clearDesignRangeSpecifications |
coder.FixptConfig.getDesignRangeSpecification | codegen

2-325
2 Function Reference

addFunctionReplacement
Class: coder.FixptConfig
Package: coder

Replace floating-point function with fixed-point function during fixed-point conversion

Syntax
addFunctionReplacement(floatFn,fixedFn)

Description
addFunctionReplacement(floatFn,fixedFn) specifies a function replacement
in a coder.FixptConfig object. During floating-point to fixed-point conversion, the
conversion process replaces the specified floating-point function with the specified fixed-
point function. The fixed-point function must be in the same folder as the floating-point
function or on the MATLAB path.

Input Arguments
floatFn — Name of floating-point function
'' (default) | string

Name of floating-point function, specified as a string.

fixedFn — Name of fixed-point function


'' (default) | string

Name of fixed-point function, specified as a string.

Examples
Specify Function Replacement in Fixed-Point Conversion Configuration Object

Suppose that:

2-326
addFunctionReplacement

• The function myfunc calls a local function myadd.


• The test function mytest calls myfunc.
• You want to replace calls to myadd with the fixed-point function fi_myadd.

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 mytest.

fixptcfg.TestBenchName = 'mytest';

Specify that the floating-point function, myadd, should be replaced with the fixed-point
function, fi_myadd.

fixptcfg.addFunctionReplacement('myadd', 'fi_myadd');

Create a code generation configuration object to generate a standalone C static library.


cfg = coder.config('lib');

Convert the floating-point MATLAB function, myfunc, to fixed-point, and generate C


code.
codegen -float2fixed fixptcfg -config cfg myfunc

When you generate code, the code generation software replaces instances of myadd with
fi_myadd during floating-point to fixed-point conversion.

See Also
codegen | coder.config | coder.FixptConfig

2-327
2 Function Reference

clearDesignRangeSpecifications
Class: coder.FixptConfig
Package: coder

Clear all design range specifications

Syntax
clearDesignRangeSpecifications()

Description
clearDesignRangeSpecifications() clears all design range specifications.

Examples

Clear a Design Range Specification


% Set up the fixed-point configuration object
cfg = coder.config('fixpt');
cfg.TestBenchName = 'dti_test';
cfg.addDesignRangeSpecification('dti', 'u_in', -1.0, 1.0)
cfg.ComputeDerivedRanges = true;
% Verify that the 'dti' function parameter 'u_in' has design range
hasDesignRanges = cfg.hasDesignRangeSpecification('dti','u_in')
% Now remove the design range
cfg.clearDesignRangeSpecifications()
hasDesignRanges = cfg.hasDesignRangeSpecification('dti','u_in')

See Also
coder.FixptConfig | coder.FixptConfig.addDesignRangeSpecification
| coder.FixptConfig.removeDesignRangeSpecification
| coder.FixptConfig.hasDesignRangeSpecification |
coder.FixptConfig.getDesignRangeSpecification | codegen

2-328
getDesignRangeSpecification

getDesignRangeSpecification
Class: coder.FixptConfig
Package: coder

Get design range specifications for parameter

Syntax
[designMin, designMax] = getDesignRangeSpecification(fcnName,
paramName)

Description
[designMin, designMax] = getDesignRangeSpecification(fcnName,
paramName) gets the minimum and maximum values specified for the parameter,
paramName, in function, fcnName.

Input Arguments
fcnName — Function name
string

Function name, specified as a string.


Data Types: char

paramName — Parameter name


string

Parameter name, specified as a string.


Data Types: char

Output Arguments
designMin — Minimum value allowed for this parameter
scalar

2-329
2 Function Reference

Minimum value allowed for this parameter, specified as a scalar double.


Data Types: double

designMax — Maximum value allowed for this parameter


scalar

Maximum value allowed for this parameter, specified as a scalar double.


Data Types: double

Examples

Get Design Range Specifications


% Set up the fixed-point configuration object
cfg = coder.config('fixpt');
cfg.TestBenchName = 'dti_test';
cfg.addDesignRangeSpecification('dti', 'u_in', -1.0, 1.0)
cfg.ComputeDerivedRanges = true;
% Get the design range for the 'dti' function parameter 'u_in'
[designMin, designMax] = cfg.getDesignRangeSpecification('dti','u_in')

designMin =

-1

designMax =

See Also
coder.FixptConfig | coder.FixptConfig.addDesignRangeSpecification
| coder.FixptConfig.hasDesignRangeSpecification |
coder.FixptConfig.removeDesignRangeSpecification |
coder.FixptConfig.clearDesignRangeSpecifications | codegen

2-330
hasDesignRangeSpecification

hasDesignRangeSpecification
Class: coder.FixptConfig
Package: coder

Determine whether parameter has design range

Syntax
hasDesignRange = hasDesignRangeSpecification(fcnName,paramName)

Description
hasDesignRange = hasDesignRangeSpecification(fcnName,paramName)
returns true if the parameter, param_name in function, fcn, has a design range
specified.

Input Arguments
fcnName — Name of function
string

Function name, specified as a string.


Example: ‘dti’
Data Types: char

paramName — Parameter name


string

Parameter name, specified as a string.


Example: ‘dti’
Data Types: char

2-331
2 Function Reference

Output Arguments
hasDesignRange — Parameter has design range
true | false

Parameter has design range, returned as a boolean.


Data Types: logical

Examples

Verify That a Parameter Has a Design Range Specification


% Set up the fixed-point configuration object
cfg = coder.config('fixpt');
cfg.TestBenchName = 'dti_test';
cfg.addDesignRangeSpecification('dti', 'u_in', -1.0, 1.0);
cfg.ComputeDerivedRanges = true;
% Verify that the 'dti' function parameter 'u_in' has design range
hasDesignRanges = cfg.hasDesignRangeSpecification('dti','u_in')

hasDesignRanges =

See Also
coder.FixptConfig | coder.FixptConfig.addDesignRangeSpecification
| coder.FixptConfig.removeDesignRangeSpecification
| coder.FixptConfig.clearDesignRangeSpecifications |
coder.FixptConfig.getDesignRangeSpecification | codegen

2-332
removeDesignRangeSpecification

removeDesignRangeSpecification
Class: coder.FixptConfig
Package: coder

Remove design range specification from parameter

Syntax
removeDesignRangeSpecification(fcnName,paramName)

Description
removeDesignRangeSpecification(fcnName,paramName) removes the design
range information specified for parameter, paramName, in function, fcnName.

Input Arguments
fcnName — Name of function
string

Function name, specified as a string.


Data Types: char

paramName — Parameter name


string

Parameter name, specified as a string.


Data Types: char

Examples
Remove Design Range Specifications
% Set up the fixed-point configuration object

2-333
2 Function Reference

cfg = coder.config('fixpt');
cfg.TestBenchName = 'dti_test';
cfg.addDesignRangeSpecification('dti', 'u_in', -1.0, 1.0)
cfg.ComputeDerivedRanges = true;
% Verify that the 'dti' function parameter 'u_in' has design range
hasDesignRanges = cfg.hasDesignRangeSpecification('dti','u_in')
% Now clear the design ranges and verify that
% hasDesignRangeSpecification returns false
cfg.removeDesignRangeSpecification('dti', 'u_in')
hasDesignRanges = cfg.hasDesignRangeSpecification('dti','u_in')

See Also
coder.FixptConfig | coder.FixptConfig.addDesignRangeSpecification
| coder.FixptConfig.clearDesignRangeSpecifications
| coder.FixptConfig.hasDesignRangeSpecification |
coder.FixptConfig.getDesignRangeSpecification | codegen

2-334
addApproximation

addApproximation
Replace floating-point function with lookup table during fixed-point conversion

Syntax
addApproximation(approximationObject)

Description
addApproximation(approximationObject) specifies a lookup table replacement
in a coder.FixptConfig object. During floating-point to fixed-point conversion, the
conversion process generates a lookup table approximation for the function specified in
the approximationObject.

Input Arguments
approximationObject — Function replacement configuration object
coder.mathfcngenerator.LookupTable configuration object

Function replacement configuration object. Use the coder.FixptConfig configuration


object addApproximation method to associate this configuration object with a
coder.FixptConfig object. Then use the codegen function -float2fixed option with
coder.FixptConfig to convert floating-point MATLAB code to fixed-point code.

Examples
Replace log function with an optimized lookup table replacement

Create a function replacement configuration object that specifies to replace the log
function with an optimized lookup table.

logAppx = coder.approximation('Function','log','OptimizeLUTSize',...
true,'InputRange',[0.1,1000],'InterpolationDegree',1,...
'ErrorThreshold',1e-3,...

2-335
2 Function Reference

'FunctionNamePrefix','log_optim_','OptimizeIterations',25);

Create a fixed-point configuration object and associate the function replacement


configuration object with it.
fixptcfg = coder.config('fixpt');
fixptcfg.addApproximation(logAppx);

You can now generate fixed-point code using the codegen function.

• “Replace the exp Function with a Lookup Table”


• “Replace a Custom Function with a Lookup Table”

See Also
codegen | coder.config | coder.FixptConfig

More About
• “Replacing Functions Using Lookup Table Approximations”

2-336
addFunctionReplacement

addFunctionReplacement
Class: coder.SingleConfig
Package: coder

Replace double-precision function with single-precision function during single-precision


conversion

Syntax
addFunctionReplacement(doubleFn,singleFn)

Description
addFunctionReplacement(doubleFn,singleFn) specifies a function replacement in
a coder.SingleConfig object. During double-precision to single-precision conversion,
the conversion process replaces the specified double-precision function with the specified
single-precision function. The single-precision function must be in the same folder as the
double-precision function or on the MATLAB path. It is a best practice to provide unique
names to local functions that a replacement function calls. If a replacement function calls
a local function, do not give that local function the same name as a local function in a
different replacement function file.

Input Arguments
doubleFn — Name of double-precision function
'' (default) | string

Name of double-precision function, specified as a string.

singleFn — Name of single-precision function


'' (default) | string

Name of single-precision function, specified as a string.

2-337
2 Function Reference

Examples
Specify Function Replacement in Single-Precision Conversion Configuration Object

Suppose that:

• The function myfunc calls a local function myadd.


• The test function mytest calls myfunc.
• You want to replace calls to myadd with the single-precision function single_myadd.

Create a coder.SingleConfig object, scfg, with default settings.

scfg = coder.config('single');

Set the test file name. In this example, the test file function name is mytest.

scfg.TestBenchName = 'mytest';

Specify that you want to replace the double-precision function, myadd, with the single-
precision function, single_myadd.

scfg.addFunctionReplacement('myadd', 'single_myadd');

Convert the double-precision MATLAB function, myfunc, to a single-precision MATLAB


function.
codegen -double2single scfg myfunc

The double-precision to single-precision conversion replaces instances of myadd with


single_myadd.

See Also
codegen | coder.config

Introduced in R2015b

2-338
coder.LAPACKCallback.getHeaderFilename

coder.LAPACKCallback.getHeaderFilename
Class: coder.LAPACKCallback
Package: coder

Return file name of LAPACKE header file

Syntax
coder.LAPACKCallback.getHeaderFilename()

Description
coder.LAPACKCallback.getHeaderFilename() returns the file name of the
LAPACKE header file that defines the C interface to a specific LAPACK library.

coder.LAPACKCallback is an abstract class for defining a LAPACK callback class.


A LAPACK callback class specifies the LAPACK library and LAPACKE header file to
use for LAPACK calls in code generated from MATLAB code. At code generation time, if
you specify a LAPACK callback class, for certain linear algebra function calls, the code
generation software generates LAPACK calls in standalone code.

The code generation software uses the LAPACKE header file name to generate a
#include statement.

Examples
Return LAPACKE Header File Name

This example shows how to write a getHeaderFilename method to return the name of
the LAPACKE header file.

In a class that derives from coder.LAPACKCallback, write a method


getHeaderFilename that returns the name of the LAPACKE header file as
a string. For example, in this class definition, getHeaderFilename returns
'mylapacke_custom.h'.

2-339
2 Function Reference

classdef useMyLAPACK < coder.LAPACKCallback


methods (Static)
function hn = getHeaderFilename()
hn = 'mylapacke_custom.h';
end
function updateBuildInfo(buildInfo, buildctx)
buildInfo.addIncludePaths(fullfile(pwd,'include'));
libName = 'mylapack';
libPath = fullfile(pwd,'lib');
[~,linkLibExt] = buildctx.getStdLibInfo();
buildInfo.addLinkObjects([libName linkLibExt], libPath, ...
'', true, true);
buildInfo.addDefines('HAVE_LAPACK_CONFIG_H');
buildInfo.addDefines('LAPACK_COMPLEX_STRUCTURE');
end
end
end

• “Speed Up Linear Algebra in Generated Standalone Code by Using LAPACK Calls”


• “Speed Up Linear Algebra in Code Generated from a MATLAB Function Block”

External Websites
• www.netlib.org/lapack

2-340
coder.LAPACKCallback.updateBuildInfo

coder.LAPACKCallback.updateBuildInfo
Class: coder.LAPACKCallback
Package: coder

Update build information for linking to a specific LAPACK library

Syntax
coder.LAPACKCallback.updateBuildInfo(buildInfo, buildctx)

Description
coder.LAPACKCallback.updateBuildInfo(buildInfo, buildctx) updates the
build information object buildInfo with the information required for the build process
to link to a specific LAPACK library.

coder.LAPACKCallback is an abstract class for defining a LAPACK callback class.


A LAPACK callback class specifies the LAPACK library and LAPACKE header file to
use for LAPACK calls in code generated from MATLAB code. At code generation time, if
you specify a LAPACK callback class, for certain linear algebra function calls, the code
generation software generates LAPACK calls in standalone code.

Input Arguments
buildInfo

Build information object. After code generation, this object contains standard project,
build option, and dependency information. In the updateBuildInfo method, to add the
information for linking to the LAPACK library, use build information methods.

buildctx

coder.BuildConfig object. Use the coder.BuildConfig getStdLibInfo method to


get the platform-specific file extension to use at link time.

2-341
2 Function Reference

Examples
Link to a Specific LAPACK Library

This example shows how to write an updateBuildInfo method to update the build
information object with the information required to link to a specific LAPACK library.

In a class that derives from coder.LAPACKCallback, write a method


updateBuildInfo. Use this example LAPACK callback class as a template.

classdef useMyLAPACK < coder.LAPACKCallback


methods (Static)
function hn = getHeaderFilename()
hn = 'mylapacke_custom.h';
end
function updateBuildInfo(buildInfo, buildctx)
buildInfo.addIncludePaths(fullfile(pwd,'include'));
libName = 'mylapack';
libPath = fullfile(pwd,'lib');
[~,linkLibExt] = buildctx.getStdLibInfo();
buildInfo.addLinkObjects([libName linkLibExt], libPath, ...
'', true, true);
buildInfo.addDefines('HAVE_LAPACK_CONFIG_H');
buildInfo.addDefines('LAPACK_COMPLEX_STRUCTURE');
end
end
end

Replace mylapack with the name of your LAPACK library. Modify the include and
library paths as necessary.

To update the build information with the location of the header files, use the build
information addIncludePaths method.

To access the platform-specific library extension, use the coder.BuildConfig


getStdLibInfo method.

To update the build information with the name and location of your LAPACK library, use
the build information addlinkObjects method.

If your compiler supports only complex data types that are represented as structures,
include these lines.

2-342
coder.LAPACKCallback.updateBuildInfo

buildInfo.addDefines('HAVE_LAPACK_CONFIG_H');
buildInfo.addDefines('LAPACK_COMPLEX_STRUCTURE');

• “Speed Up Linear Algebra in Generated Standalone Code by Using LAPACK Calls”


• “Speed Up Linear Algebra in Code Generated from a MATLAB Function Block”

See Also
coder.ExternalDependency | coder.BuildConfig

More About
• “Build Information Methods”

External Websites
• www.netlib.org/lapack

2-343
3

Class Reference
3 Class Reference

coder.ArrayType class
Package: coder
Superclasses: coder.Type

Represent set of MATLAB arrays

Description
Specifies the set of arrays that the generated code accepts. Use only with the codegen -
args option. Do not pass as an input to a generated MEX function.

Construction
coder.ArrayType is an abstract class. You cannot create instances of it directly.
You can create coder.EnumType, coder.FiType, coder.PrimitiveType, and
coder.StructType objects that derive from this class.

Properties
ClassName

Class of values in this set

SizeVector

The upper-bound size of arrays in this set.

VariableDims

A vector specifying whether each dimension of the array is fixed or variable size. If a
vector element is true, the corresponding dimension is variable size.

Copy Semantics
Value. To learn how value classes affect copy operations, see Copying Objects in the
MATLAB documentation.

3-2
coder.ArrayType class

See Also
coder.EnumType | coder.FiType | coder.PrimitiveType | coder.StructType |
coder.CellType | coder.resize | coder.Type | coder.newtype | coder.typeof |
codegen

Introduced in R2011a

3-3
3 Class Reference

coder.BuildConfig class
Package: coder

Build context during code generation

Description
The code generation software creates an object of this class to facilitate access to the
build context. The build context encapsulates the settings used by the code generation
software including:

• Target language
• Code generation target
• Target hardware
• Build toolchain

Use coder.BuildConfig methods in the methods that you write for the
coder.ExternalDependency class.

Construction
The code generation software creates objects of this class.

Methods

Copy Semantics
Value. To learn how value classes affect copy operations, see Copying Objects in the
MATLAB documentation.

3-4
coder.BuildConfig class

Examples
Use coder.BuildConfig methods to access the build context in
coder.ExternalDependency methods

This example shows how to use coder.BuildConfig methods to access the build
context in coder.ExternalDependency methods. In this example, you use:

• coder.BuildConfig.isMatlabHostTarget to verify that the code generation


target is the MATLAB host. If the host is not MATLAB report an error.
• coder.BuildConfig.getStdLibInfo to get the link-time and run-time library file
extensions. Use this information to update the build information.

Write a class definition file for an external library that contains the function adder.

%================================================================
% This class abstracts the API to an external Adder library.
% It implements static methods for updating the build information
% at compile time and build time.
%================================================================

classdef AdderAPI < coder.ExternalDependency


%#codegen

methods (Static)

function bName = getDescriptiveName(~)


bName = 'AdderAPI';
end

function tf = isSupportedContext(ctx)
if ctx.isMatlabHostTarget()
tf = true;
else
error('adder library not available for this target');
end
end

function updateBuildInfo(buildInfo, ctx)


[~, linkLibExt, execLibExt, ~] = ctx.getStdLibInfo();

% Header files
hdrFilePath = fullfile(pwd, 'codegen', 'dll', 'adder');

3-5
3 Class Reference

buildInfo.addIncludePaths(hdrFilePath);

% Link files
linkFiles = strcat('adder', linkLibExt);
linkPath = hdrFilePath;
linkPriority = '';
linkPrecompiled = true;
linkLinkOnly = true;
group = '';
buildInfo.addLinkObjects(linkFiles, linkPath, ...
linkPriority, linkPrecompiled, linkLinkOnly, group);

% Non-build files
nbFiles = 'adder';
nbFiles = strcat(nbFiles, execLibExt);
buildInfo.addNonBuildFiles(nbFiles,'','');
end

%API for library function 'adder'


function c = adder(a, b)
if coder.target('MATLAB')
% running in MATLAB, use built-in addition
c = a + b;
else
% running in generated code, call library function
coder.cinclude('adder.h');

% Because MATLAB Coder generated adder, use the


% housekeeping functions before and after calling
% adder with coder.ceval.
% Call initialize function before calling adder for the
% first time.

coder.ceval('adder_initialize');
c = 0;
c = coder.ceval('adder', a, b);

% Call the terminate function after


% calling adder for the last time.

coder.ceval('adder_terminate');
end
end

3-6
coder.BuildConfig class

end
end

See Also
coder.ExternalDependency | coder.HardwareImplementation |
coder.make.ToolchainInfo | coder.target

Introduced in R2013b

3-7
3 Class Reference

coder.CellType class
Package: coder
Superclasses: coder.ArrayType

Represent set of MATLAB cell arrays

Description
Specifies the set of cell arrays that the generated code accepts. Use only with the
codegen -args option. Do not pass as an input to a generated MEX function.

Construction
t = coder.typeof(cells) creates a coder.CellType object for a cell array that has
the same cells and cell types as cells. The cells in cells are type objects or example
values.

t = coder.typeof(cells, sz, variable_dims) creates a coder.CellType


object that has upper bounds specified by sz and variable dimensions specified by
variable_dims. If sz specifies inf for a dimension, then the size of the dimension
is unbounded and the dimension is variable size. When sz is [], the upper bounds do
not change. If you do not specify the variable_dims input parameter, except for the
unbounded dimensions, the dimensions of the type are fixed. A scalar variable_dims
applies to the bounded dimensions that are not 1 or 0.

When cells specifies a cell array whose elements have different classes, you cannot use
coder.typeof to create a coder.CellType object for a variable-size cell array.

t = coder.newtype(cells) creates a coder.CellType object for a cell array that


has the cells and cell types specified by cells. The cells in cells must be type objects.

t = coder.newtype(cell_array, sz, variable_dims) creates a


coder.CellType that has upper bounds specified by sz and variable dimensions
specified by variable_dims. If sz specifies inf for a dimension, then the size of the
dimension is unbounded and the dimension is variable size. When sz is [], the upper
bounds do not change. If you do not specify the variable_dims input parameter,

3-8
coder.CellType class

except for the unbounded dimensions, the dimensions of the type are fixed. A scalar
variable_dims applies to the bounded dimensions that are not 1 or 0.

When cells specifies a cell array whose elements have different classes, you cannot use
coder.newtype to create a coder.CellType object for a variable-size cell array.

Input Arguments
cells — Specification of cell types
cell array

Cell array that specifies the cells and cell types for the output coder.CellType
object. For coder.typeof, cells can contain type objects or example values. For
coder.newtype, cells must contain type objects.

sz — Size of cell array


row vector of integer values

Specifies the upper bound for each dimension of the cell array type object. For
coder.newtype, sz cannot change the number of cells for a heterogeneous cell array.

For coder.newtype, the default is [1 1].

variable_dims — Dimensions that are variable size


row vector of logical values

Specifies whether each dimension is variable size (true) or fixed size (false).

For coder.newtype, the default is true for dimensions for which sz specifies an upper
bound of inf and false for all other dimensions.

When cells specifies a cell array whose elements have different classes, you cannot
create a coder.CellType object for a variable-size cell array.

Properties
Alignment — Run-time memory alignment
-1 | power of 2 that is less than or equal to 128

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

3-9
3 Class Reference

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 data to be aligned. By default, the structure is not aligned on a specific boundary,
so it is not matched by CRL functions that require alignment.

Cells — Types of cells


cell array

A cell array that specifies the coder.Type of each cell.

ClassName — Name of class


string

Class of values in this set.

Extern — External definition


logical scalar

Specifies whether the cell array type is externally defined.

HeaderFile — Name of header file


string

If the cell array type is externally defined, the name of the header file that contains
the external definition of the type, for example, 'mytype.h'. If you use the codegen
command to specify the path to the file, use the -I option. If you use the MATLAB Coder
app to specify the path to the file, use the Additional include directories setting in
the Custom Code tab in the project settings dialog box.

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 HeaderFile option, the code
generation software includes the custom header file where it is required.

Must be a nonempty string.

SizeVector — Size of cell array


row vector of integer values

The upper bounds of dimensions of the cell array.

TypeName — Name of generated structure type


string

3-10
coder.CellType class

The name to use in the generated code for the structure type that represents this cell
array type. TypeName applies only to heterogeneous cell arrays types.

VariableDims — Dimensions that are variable size


row vector of logical values

A vector that specifies whether each dimension of the array is fixed or variable size. If a
vector element is true, the corresponding dimension is variable size.

Methods

Copy Semantics
Value. To learn how value classes affect copy operations, see Copying Objects in the
MATLAB documentation.

Examples
Create a Type for a Cell Array Whose Elements Have the Same Class

Create a type for a cell array whose first element has class char and whose second
element has class double.
t = coder.typeof({1 2 3})

t =

coder.CellType
1x3 homogeneous cell
base: 1x1 double

The type is homogeneous.

Create a Heterogeneous Type for a Cell Array Whose Elements Have the Same Class

To create a heterogeneous type when the elements of the example cell array type have
the same class, use the makeHeterogeneous method.
t = makeHeterogeneous(coder.typeof({1 2 3}))

3-11
3 Class Reference

t =

coder.CellType
1x3 heterogeneous cell
f0: 1x1 double
f1: 1x1 double
f2: 1x1 double

The cell array type is heterogeneous. It is represented as a structure in the generated


code.

Create a Cell Array Type for a Cell Array Whose Elements Have Different Classes

Define variables that are example cell values.

a = 'a';
b = 1;

Pass the example cell values to coder.typeof.

t = coder.typeof({a, b})

t =

coder.CellType
1x2 heterogeneous cell
f0: 1x1 char
f1: 1x1 double

Create a Type for a Variable-Size Homogeneous Cell Array from an Example Cell Array Whose
Elements Have Different Classes

Create a type for a cell array that has two strings with different sizes.

t = coder.typeof({'aa', 'bbb'})

t =

coder.CellType
1x2 heterogeneous cell
f0: 1x2 char
f1: 1x3 char

The cell array type is heterogeneous.

3-12
coder.CellType class

Create a type using the same cell array input. This time, specify that the cell array type
has variable-size dimensions.
t = coder.typeof({'aa','bbb'},[1,10],[0,1])

t =

coder.CellType
1x:10 homogeneous cell
base: 1x:3 char

The cell array type is homogeneous. coder.typeof determined that the base type 1x:3
char can represent 'aa', and 'bbb'.

Create a New Cell Array Type from a Cell Array of Types

Create a type for a scalar int8.


ta = coder.newtype('int8',[1 1]);

Create a type for a :1x:2 double row vector.


tb = coder.newtype('double',[1 2],[1 1]);

Create a cell array type whose cells have the types specified by ta and ta.
t = coder.newtype('cell',{ta,tb})

t =

coder.CellType
1x2 heterogeneous cell
f0: 1x1 int8
f1: :1x:2 double

Create a coder.CellType That Uses an Externally Defined Type

Create a cell type for a heterogeneous cell array.


ca = coder.typeof(double(0));
cb = coder.typeof(single(0));
t = coder.typeof({ca cb})

coder.CellType
1x2 heterogeneous cell
f0: 1x1 double

3-13
3 Class Reference

f1: 1x1 single

Use coder.structname to specify the name for the type and that the type is defined in
an external file.
t = coder.cstructname(t,'mytype','extern','HeaderFile','myheader.h')

t =

coder.CellType
1x2 extern heterogeneous cell mytype(myheader.h)
f0: 1x1 double
f1: 1x1 single

Tips
• coder.typeof determines whether the cell array type is homogeneous
or heterogeneous. If the cell array elements have the same class and size,
coder.typeof returns a homogeneous cell array type. If the elements have
different classes, coder.typeof returns a heterogeneous cell array type. For
some cell arrays, the classification as homogeneous or heterogeneous is ambiguous.
For example, the type for {1 [2 3]} can be a 1x2 heterogeneous type. The first
element is double and the second element is 1x2 double. The type can also be a
1x3 homogeneous type in which the elements have class double and size 1x:2.
For these ambiguous cases, coder.typeof uses heuristics to classify the type
as homogeneous or heterogeneous. If you want a different classification, use the
makeHomogeneous or makeHeterogeneous methods. The makeHomogeneous
method makes a homogeneous copy of a type. The makeHeterogeneous method
makes a heterogeneous copy of a type.

The makeHomogeneous and makeHeterogeneous methods permanently assign the


classification as homogeneous and heterogeneous, respectively. You cannot later use
one of these methods to create a copy that has a different classification.

See Also
coder.ArrayType | coder.Constant | coder.EnumType | coder.FiType |
coder.PrimitiveType | coder.StructType | coder.Type | codegen | coder.newtype |
coder.resize | coder.typeof

Introduced in R2015b

3-14
coder.CodeConfig class

coder.CodeConfig class
Package: coder

codegen configuration object

Description
A coder.CodeConfig object contains the configuration parameters that the codegen
function requires to generate standalone C/C++ libraries and executables. Use the -
config option to pass this object to the codegen function.

Construction
cfg = coder.config('lib') creates a code generation configuration object for C/C
++ static library generation. If the Embedded Coder product is not installed, it creates
a coder.CodeConfig object. Otherwise, it creates a coder.EmbeddedCodeConfig
object.

cfg = coder.config('dll') creates a code generation configuration object for C/C+


+ dynamic library generation. If the Embedded Coder product is not installed, it creates
a coder.CodeConfig object. Otherwise, it creates a coder.EmbeddedCodeConfig
object.

cfg = coder.config('exe') creates a code generation configuration object for C/


C++ executable generation. If the Embedded Coder product is not installed, it creates
a coder.CodeConfig object. Otherwise, it creates a coder.EmbeddedCodeConfig
object.

cfg = coder.config(output_type, 'ecoder', false) creates a


coder.CodeConfig object for the specified output type even if the Embedded Coder
product is installed.

cfg = coder.config(output_type, 'ecoder', true) creates a


coder.EmbeddedCodeConfig object for the specified output type even if the
Embedded Coder product is not installed. However, you cannot generate code using a
coder.EmbeddedCodeConfig object unless an Embedded Coder license is available.

3-15
3 Class Reference

Properties
BuildConfiguration

Specify build configuration. 'Faster Builds', 'Faster Runs', 'Debug', 'Specify'.

Default: string, 'Faster Builds'

CodeReplacementLibrary

Specify a code replacement library for the generated code.

Value Description
'None' Does not use a code replacement library.
'GNU C99 extensions' Generates calls to the GNU® gcc math
library, which provides C99 extensions as
defined by compiler option -std=gnu99.
'Intel IPP for x86-64 (Windows)' Generates calls to the Intel Performance
Primitives (IPP) library for the x86-64
Windows platform.
'Intel IPP/SSE for x86-64 Generates calls to the IPP and Streaming
(Windows)' SIMD Extensions (SSE) libraries for the
x86-64 Windows platform.
'Intel IPP for x86-64 (Windows Generates calls to the IPP library for the
using MinGW compiler)' x86-64 Windows platform and MinGW
compiler.
'Intel IPP/SSE for x86-64 Generates calls to the IPP and SSE
(Windows using MinGW compiler)' libraries for the x86-64 Windows platform
and MinGW compiler.
'Intel IPP for x86/Pentium Generates calls to the IPP library for the
(Windows)' x86/Pentium Windows platform.
'Intel IPP/SSE x86/Pentium Generates calls to the IPP and SSE
(Windows)' libraries for the x86/Pentium Windows
platform.
'Intel IPP for x86-64 (Linux)' Generates calls to the IPP library for the
x86-64 Linux platform.

3-16
coder.CodeConfig class

Value Description
'Intel IPP/SSE with GNU99 Generates calls to the GNU libraries for
extensions for x86-64 (Linux)' IPP and SSE, with GNU C99 extensions,
for the x86-64 Linux platform.

Compatible libraries depend on these parameters:

• TargetLang
• TargetLangStandard
• ProdHWDeviceType in the hardware implementation configuration object.

Embedded Coder offers more libraries and the ability to create and use custom code
replacement libraries.

MATLAB Coder generates the minimal set of #include statements for header files
required by the selected code replacement library.

Before setting this parameter, verify that your compiler supports the library that
you want to use. If you select a parameter value that your compiler does not support,
compiler errors can occur.

Note: MATLAB Coder software does not support TLC callbacks.

Default: string, 'None'

ConstantFoldingTimeout

Specify the maximum number of instructions that the constant folder will execute before
stopping. In some situations, code generation might require specific instructions to be
constant. Increase this value if code generation is failing.

Default: integer, 10000

CustomHeaderCode

Specify code to appear near the top of each C/C++ header file generated from your
MATLAB algorithm code.

Default: string, ''

3-17
3 Class Reference

CustomInclude

Specify a space-separated list of include folders to add to the include path when
compiling the generated code.

If your list includes Windows path strings that contain spaces, enclose each instance in
double quotes within the argument string, for example:

'C:\Project "C:\Custom Files"'

Default: string, ''

CustomInitializer

Specify code to appear in the initialize function of the generated .c or .cpp file.

Default: string, ''

CustomLAPACKCallback

Specify the name of a LAPACK callback class that derives from coder.LAPACKCallback.
If you specify a LAPACK callback class, for certain linear algebra functions, the code
generation software generates LAPACK calls by using the LAPACKE C interface to your
LAPACK library. The callback class provides the name of your LAPACKE header file
and the information required to link to your LAPACK library. If this parameter is empty,
the code generation software generates code for linear algebra functions instead of a
LAPACK call.

Default: string, ''

CustomLibrary

Specify a space-separated list of static library or object files to link with the generated
code.

Default: string, ''

CustomSource

Specify a space-separated list of source files to compile and link with the generated code.

Default: string, ''

3-18
coder.CodeConfig class

CustomSourceCode

Specify code to appear near the top of the generated .c or .cpp file, outside of a function.

Default: string, ''

CustomTerminator

Specify code to appear in the terminate function of the generated .c or .cpp file.

Default: string, ''

CustomToolchainOptions

Specify custom settings for each tool in the selected toolchain, as a cell array.

Dependencies:

• Toolchain determines which tools and options appear in the cell.


• Setting BuildConfiguration to Specify enables the options specified by
CustomToolchainOptions.

Start by getting the current options and values. For example:


rtwdemo_sil_topmodel;
set_param(gcs, 'BuildConfiguration', 'Specify')
opt = get_param(gcs, 'CustomToolchainOptions')

Then edit the values in opt.

These values derive from the toolchain definition file and the third-party compiler
options. See “Custom Toolchain Registration”.

Default: cell array

DataTypeReplacement

Specify whether to use built-in C data types or pre-defined types from rtwtypes.h in
generated code.

Set to 'CoderTypeDefs' to use the data types from rtwtypes.h. Otherwise, to use
built-in C data types, retain default value or set to 'CBuiltIn'.

Default: string, 'CBuiltIn'

3-19
3 Class Reference

Description

Description of the coder.CodeConfig object.

Default: string, 'class CodeConfig: C code generation configuration.'

DynamicMemoryAllocation

Control use of dynamic memory allocation for variable-size data.

By default, dynamic memory allocation is enabled for variable-size arrays whose size (in
bytes) is greater than or equal to DynamicMemoryAllocationThreshold. codegen
allocates memory for this variable-size data dynamically on the heap.

Set this property to 'Off' to allocate memory statically on the stack. Set it to
'AllVariableSizeArrays' to allocate memory for all variable-size arrays dynamically
on the heap. You must use dynamic memory allocation for unbounded variable-size data.

Dependencies:

• EnableVariableSizing enables this parameter.


• Setting this parameter to 'Threshold' enables the
DynamicMemoryAllocationThreshold parameter.

Default: string, 'Threshold'

DynamicMemoryAllocationThreshold

Specify the size threshold in bytes.codegen allocates memory on the heap for variable-
size arrays whose size is greater than or equal to this threshold.

Dependency:

• Setting DynamicMemoryAllocation to 'Threshold' enables this parameter.

Default: integer, 65536

EnableAutoExtrinsicCalls

Specify whether MATLAB Coder must treat common visualization functions as


extrinsic functions. When this option is enabled, MATLAB Coder detects calls to many
common visualization functions, such as plot, disp, and figure. For MEX code

3-20
coder.CodeConfig class

generation, MATLAB Coder calls out to MATLAB for these functions. For standalone
code generation, MATLAB Coder does not generate code for these visualization functions.
This capability reduces the amount of time that you spend making your code suitable
for code generation. It also removes the requirement to declare these functions extrinsic
using the coder.extrinsic function.

Default: true

EnableMemcpy

Enable the memcpy optimization. To optimize code that copies consecutive array
elements, the memcpy optimization replaces the code with a memcpy call. A memcpy call
can be more efficient than code, such as a for-loop or multiple, consecutive element
assignments. The code generation software invokes the memcpy optimization when the
following conditions are true:

• EnableMemcpy is true.
• The number of bytes to copy is greater than or equal to MemcpyThreshold. The
number of bytes to copy is the number of array elements multiplied by the number of
bytes required for the C/C++ data type.

See “memcpy Optimization”.

Default: true

EnableOpenMP

If possible, enable OpenMP. Using the OpenMP library, the C/C++ code that MATLAB
Coder generates for parfor-loops can run on multiple threads. With OpenMP disabled,
MATLAB Coder treats parfor-loops as for-loops and generates C/C++ code that runs on
a single thread.

Default: true

EnableVariableSizing

Enable support for variable-size arrays.

Dependency:

• This parameter enables the parameter DynamicMemoryAllocation.

Default: true

3-21
3 Class Reference

FilePartitionMethod

Specify whether to generate one C/C++ file for each MATLAB language file
('MapMFileToCFile') or generate all C/C++ functions into a single file
('SingleFile').

Default: string, 'MapMFileToCFile'

GenCodeOnly

Specify code generation versus an executable or static library build.

Default: false

GenerateComments

Place comments in the generated files.

Dependency:

• Enables MATLABSourceComments.

Default: true

GenerateExampleMain

Specify whether to generate an example C/C++ main function. If example main


generation is enabled, MATLAB Coder generates source and header files for the
main function in the examples subfolder of the build folder. For C code generation, it
generates the files main.c and main.h. For C++ code generation, it generates the files
main.cpp and main.h.

The example main function declares and initializes data. It calls entry-point functions
but does not use values returned from the entry-point functions.

Before you use the example main files, copy them to another location and modify them to
meet the requirements of your application.

Value Description
'DoNotGenerate' Does not generate an example C/C++ main
function.
'GenerateCodeOnly' Generates an example C/C++ main
function but does not compile it.

3-22
coder.CodeConfig class

Value Description
'GenerateCodeAndCompile' Generates an example C/C++ main
function and compiles it to create a test
executable. This executable does not return
output.

If the GenCodeOnly parameter is true,


MATLAB Coder does not compile the C/C+
+ main function.

Default: string, 'GenerateCodeOnly'

GenerateMakefile

Specify whether to generate a makefile during the build process.

Default: true

GenerateReport

Document generated code in an HTML report.

Default: false

HardwareImplementation

Handle to coder.HardwareImplementation object that specifies hardware-


specific configuration parameters for C/C++ code generation. Defaults to a
coder.HardwareImplementation object with properties that are set for the MATLAB
host computer.

InitFltsAndDblsToZero

Enable the memset optimization for assignment of float or double 0 to consecutive


array elements. To optimize code that assigns a constant value to consecutive array
elements, the memset optimization replaces the code with a memset call. A memset call
can be more efficient than code, such as a for-loop or multiple, consecutive element
assignments. To assign float or double 0 to consecutive array elements, the code
generation software invokes the memset optimization when the following conditions are
true:

• InitFltsAndDblsToZero is true.

3-23
3 Class Reference

• The number of bytes to assign is greater than or equal to MemcpyThreshold. The


number of bytes to assign is the number of array elements multiplied by the number
of bytes required for the C/C++ data type.

See “memset Optimization”.

Default: true

InlineStackLimit

Specify the stack size limit on inlined functions. This specification determines the
amount of stack space allocated for local variables of the inlined function.

Specifying a limit on the stack space constrains the amount of inlining allowed. For out-
of-line functions, stack space for variables local to the function is released when the
function returns. However, for inlined functions, stack space remains occupied by the
local variables even when the function returns.

This feature is especially important for embedded processors, where stack size can be
limited.

Default: integer, 4000

InlineThreshold

Specify function size for inline threshold. Unless there are conflicts with other inlining
conditions, MATLAB Coder inlines functions that are smaller than this size.

The function size is measured in terms of an abstract number of instructions, not actual
MATLAB instructions or instructions in the target processor. You must experiment
with this parameter to obtain the inlining behavior that you want. For instance, if the
default setting for this parameter is leading to large functions being inlined and in turn
generating large C code, you can tune the parameter in steps until you are satisfied with
the size of generated code.

Default: integer, 10

InlineThresholdMax

Specify the maximum size of functions after inlining. If the size of the calling function
after inlining exceeds InlineThresholdMax,MATLAB Coder does not inline the called
function.

3-24
coder.CodeConfig class

The function size is measured in terms of an abstract number of instructions, not actual
MATLAB instructions or instructions in the target processor. You must experiment
with this parameter to obtain the inlining behavior that you want. For instance, if the
default setting for this parameter is leading to large functions being inlined and in turn
generating large C code, you can tune the parameter in steps until you are satisfied with
the size of generated code.

Default: integer, 200

LaunchReport

Specify whether to display a report after code generation is complete or an error occurs.

Default: true

MATLABSourceComments

Include MATLAB source code as comments in the generated code.

Dependency:

• GenerateComments enables this parameter.

Default: false

MaxIdLength

Specify maximum number of characters in generated function, type definition, and


variable names. To avoid truncation of identifiers by the target C compiler, specify a
value that matches the maximum identifier length of the target C compiler.

This parameter does not apply to exported identifiers, such as the generated names for
entry-point functions or emxArray API functions. If the length of an exported identifier
exceeds the maximum identifier length of the target C compiler, the target C compiler
truncates the exported identifier.

Minimum is 31. Maximum is 256.

Default: integer, 31

MemcpyThreshold

Specify the minimum number of bytes for the code generation software to invoke the
memcpy optimization or the memset optimization. To optimize generated code that copies

3-25
3 Class Reference

consecutive array elements, the code generation software tries to replace the code with
a memcpy call. To optimize generated code that assigns a literal constant to consecutive
array elements, the code generation software tries to replace the code with a memset call.
A memcpy or memset call can be more efficient than code, such as a for-loop or multiple,
consecutive element assignments.

The number of bytes is the number of array elements to copy or assign multiplied by the
number of bytes required for the C/C++ data type.

See “memcpy Optimization” and “memset Optimization”.

Default: integer, 64

MultiInstanceCode

Generate reusable, multi-instance code that is reentrant.

Default: false

Name

Name of the configuration object.

Default: string, 'CodeConfig'

OutputType

Specify whether to generate a standalone C/C++ static library, dynamic library, or


executable. Set to 'LIB' to generate a static library, 'DLL' to generate a dynamic
library, or 'EXE' to generate an executable.

Default: string, 'LIB'

PassStructByReference

Specify whether to pass structures by reference to entry-point functions. Set to true


to pass structures by reference, which reduces memory usage and execution time by
minimizing the number of copies of parameters at entry-point function boundaries. Set to
false to pass structures by value.

This parameter applies only to entry-point functions.

If you set this parameter to true, an entry-point function that writes to a field of a
structure parameter overwrites the input value.

3-26
coder.CodeConfig class

Default: true

PostCodeGenCommand

Specify command to customize build processing after code generation using codegen.

Default: string, ''

PreserveVariableNames

Specify the variable names that the variable reuse optimization must preserve.

Value Description
'UserNames' Preserve names that correspond to user-
defined variables in the MATLAB code. For
this option, the variable reuse optimization
does not replace your variable name with
another name and does not use your name
for another variable. Use this option for
readability. You can more easily trace the
variables in the generated code back to the
variables in your MATLAB code.

The variable reuse optimization preserves


your variable names, however, other
optimizations can remove them from the
generated code. MATLAB Coder does not
reuse your variables in the generated C/
C++ code, however, the C/C++ compiler
can reuse these variables in the generated
binary code.
'None' The variable reuse optimization does not
have to preserve any variable names. It
can reuse any variables that meet the
requirements for variable reuse. If your
code uses large data structures or arrays,
in some cases, the extra memory required
to preserve your variable names can affect
performance. In these cases, use this
option to reduce memory usage or improve
execution speed.

3-27
3 Class Reference

Value Description
'All' Preserve all variable names. This option
disables variable reuse. Use this option
only for testing or debugging. Do not use
this option for production code.

Default: string, 'UserNames'

ReservedNameArray

Enter a space-separated list of names that MATLAB Coder is not to use for naming
functions or variables.

Default: string, ''

RuntimeChecks

Enable run-time error detection and reporting in the generated C/C++ code. If you select
this option, the generated code checks for errors such as out-of-bounds array indexing.

The error reporting software uses fprintf to write error messages to stderr. It uses
abort to terminate the application. If fprintf and abort are not available, you must
provide them. The abort function abruptly terminates the program. If your system
supports signals, you can catch the abort signal (SIGABRT) so that you can control the
program termination.

Error messages are in English.

Default: false

SaturateOnIntegerOverflow

Overflows saturate to either the minimum or maximum value that the data type can
represent. Otherwise, the overflow behavior depends on your target C compiler. Most C
compilers wrap on overflow.

This parameter applies only to MATLAB built-in integer types. It does not apply to
doubles, singles, or fixed-point data types.

Default: true

3-28
coder.CodeConfig class

StackUsageMax

Specify the maximum stack usage per application in bytes. Set a limit that is lower than
the available stack size. Otherwise, a run-time stack overflow can occur. The C compiler
detects and reports overflows.

Default: integer, 200000

SupportNonFinite

Specify whether to generate nonfinite data and operations.

Default: true

TargetLang

Specify the target language. Set to 'C' to generate C code. Set to C++ to generate C++
code. If you specify C++, MATLAB Coder wraps the C code into .cpp files so that you can
use a C++ compiler and interface with external C++ applications. It does not generate C+
+ classes.

Default: string, 'C'

TargetLangStandard

Specify a standard math library for the generated code. Options include 'C89/C90
(ANSI)', 'C99 (ISO)', and 'C++03 (ISO)'.

Before setting this parameter, verify that your compiler supports the library that
you want to use. If you select a parameter value that your compiler does not support,
compiler errors can occur.

Default: string, 'C89/C90 (ANSI)'

Toolchain

Specify the toolchain to use. If you do not specify a toolchain, MATLAB Coder
automatically locates an installed toolchain.

Default: string, 'Automatically locate an installed toolchain'

Verbose

Display code generation progress.

3-29
3 Class Reference

Default: false

Copy Semantics
Handle. To learn how handle classes affect copy operations, see Copying Objects in the
MATLAB documentation.

Examples
Generate a standalone C/C++ static library from a MATLAB function that is suitable for
code generation:

1 Write a MATLAB function, coderand, that generates a random scalar value from
the standard uniform distribution on the open interval (0,1).

function r = coderand() %#codegen


% The directive %#codegen declares that the function
% is intended for code generation
r = rand();
2 Create a code generation configuration object to generate a static library.

cfg = coder.config('lib')
3 Generate the C library files in the default folder (codegen/lib/coderand). Use the -
config option to specify the configuration object.

codegen -config cfg coderand

Generate a C executable file from a MATLAB function that is suitable for code
generation. Specify the main C function as a configuration parameter.

1 Write a MATLAB function, coderand, that generates a random scalar value from
the standard uniform distribution on the open interval (0,1).

function r = coderand() %#codegen


r = rand();
2 Write a main C function, c:\myfiles\main.c, that calls coderand.

/*
** main.c

3-30
coder.CodeConfig class

*/
#include <stdio.h>
#include <stdlib.h>
#include "coderand.h"

int main()
{
coderand_initialize();

printf("coderand=%g\n", coderand());

coderand_terminate();

return 0;
}
3 Configure your code generation parameters to include the main C function, then
generate the C executable.
cfg = coder.config('exe');
cfg.CustomSource = 'main.c';
cfg.CustomInclude = 'c:\myfiles';
codegen -config cfg coderand

codegen generates C executables and supporting files in the default folder


codegen/exe/coderand.

This example shows how to specify a main function as a parameter in the


configuration object coder.CodeConfig. Alternatively, you can specify the file
containing main() separately on the command line. You can use a source, object, or
library file.

Alternatives
Use the coder function to create a MATLAB Coder project. The project provides a
user interface that facilitates adding MATLAB files, defining input parameters, and
specifying build parameters.

See Also
codegen | coder | coder.EmbeddedCodeConfig

3-31
3 Class Reference

coder.Constant class
Package: coder
Superclasses: coder.Type

Represent set containing one MATLAB value

Description
Use a coder.Constant object to define values that are constant during code generation.
Use only with the codegen -args options. Do not pass as an input to a generated MEX
function.

Construction
const_type=coder.Constant(v) creates a coder.Constant type from the value v.

codegen -globals {'g', coder.Constant(v)} creates a constant global variable g


with the value v.

const_type=coder.newtype('constant', v) creates a coder.Constant type from


the value v.

Input Arguments
v

Constant value used to construct the type.

Properties
Value

The actual value of the constant.

3-32
coder.Constant class

Copy Semantics
Value. To learn how value classes affect copy operations, see Copying Objects in the
MATLAB documentation.

Examples
Generate MEX code for a MATLAB function with a constant input

This example shows how to generate MEX code for a MATLAB function that has a
constant input. It shows how to use the ConstantInputs configuration parameter to
control whether the MEX function signature includes constant inputs and whether the
constant input values must match the compile-time values.

Write a function identity that copies its input to its output.

function y = identity(u) %#codegen


y = u;

Create a code configuration object for MEX code generation.

cfg = coder.config('mex');

Generate a MEX function identity_mex with the constant input 42.

codegen identity -config cfg -args {coder.Constant(42)}

Call identity_mex. You must provide the input 42.

identity_mex(42)

ans =

42

Configure ConstantInputs so that the MEX function does not check that the input
value matches the compile-time value.

cfg.ConstantInputs = 'IgnoreValues';

Generate identity_mex with the new configuration.

3-33
3 Class Reference

codegen identity -config cfg -args {coder.Constant(42)}

Call identity_mex with a constant input value other than 42 .


identity_mex(50)

ans =

42

The MEX function ignored the input value 50.

Configure ConstantInputs so that the MEX function does not include the constant
input.
cfg.ConstantInputs = 'Remove';

Generate identity_mex with the new configuration.


codegen identity -config cfg -args {coder.Constant(42)}

Call identity_mex. Do not provide the input value .


identity_mex()

ans =

42

Generate C code for a function that has constant input

This example shows how to generate C code for a function specialized to the case where
an input has a constant value.

Write a function identity that copies its input to its output.


function y = identity(u) %#codegen
y = u;

Create a code configuration object for C code generation.


cfg = coder.config('lib');

Generate C code for identity with the constant input 42 and generate a report.
codegen identity -config cfg -args {coder.Constant(42)} -report

3-34
coder.Constant class

In the report, on the C code tab, click identity.c.

The function signature for identity is

double identity(void)

Generate MEX code for a function that uses constant global data

This example shows how to specify a constant value for a global variable at compile time.

Write a function myfunction that returns the value of the global constant g.

function y = myfunction() %#codegen


global g;

y = g;

end

Create a configuration object for MEX code generation.

cfg = coder.config('mex');

Define a cell array globals that declares that g is a constant global variable with value
5.

globals = {'g', coder.Constant(5)};

Generate a MEX function for myfunction using the -globals option to specify the
global data.

codegen -config cfg -globals globals myfunction

Run the generated MEX function.

myfunction_mex

ans =

See Also
codegen | coder.newtype | coder.Type

3-35
3 Class Reference

More About
• “Specify Constant Inputs at the Command Line”
• “Control Constant Inputs in MEX Function Signatures”
• “Define Constant Global Data”

Introduced in R2011a

3-36
coder.EmbeddedCodeConfig class

coder.EmbeddedCodeConfig class
Package: coder
Superclasses: coder.CodeConfig

codegen configuration object that specifies code generation parameters for code
generation with an Embedded Coder license

Description
A coder.EmbeddedCodeConfig object contains the configuration parameters that the
codegen function requires to generate standalone C/C++ libraries and executables for an
embedded target. Use the -config option to pass this object to the codegen function.

Construction
cfg = coder.config('lib') creates a code generation configuration object for C/
C++ static library generation. If the Embedded Coder product is installed, it creates
a coder.EmbeddedCodeConfig object. Otherwise, it creates a coder.CodeConfig
object.

cfg = coder.config('dll') creates a code generation configuration object for C/C


++ dynamic library generation. If the Embedded Coder product is installed, it creates
a coder.EmbeddedCodeConfig object. Otherwise, it creates a coder.CodeConfig
object.

cfg = coder.config('exe') creates a code generation configuration object for C/


C++ executable generation. If the Embedded Coder product is installed, it creates a
coder.EmbeddedCodeConfig object. Otherwise, it creates a coder.CodeConfig
object.

cfg = coder.config(output_type, 'ecoder', false) creates a


coder.CodeConfig object for the specified output type even if the Embedded Coder
product is installed.

cfg = coder.config(output_type, 'ecoder', true) creates a


coder.EmbeddedCodeConfig object for the specified output type even if the

3-37
3 Class Reference

Embedded Coder product is not installed. However, you cannot generate code using a
coder.EmbeddedCodeConfig object unless an Embedded Coder license is available.

Properties
BuildConfiguration

Specify build configuration. 'Faster Builds', 'Faster Runs', 'Debug', 'Specify'.

Default: string, 'Faster Builds'

CastingMode

Specify data type casting level for variables in the generated C/C++ code.

Value Description
'Nominal' Generate C/C++ code that uses default C
compiler data type casting. For example:
short addone(short x)
{
int i0;
i0 = x + 1;
if (i0 > 32767) {
i0 = 32767;
}

return (short)i0;
}
'Standards' Generate C/C++ code that casts data types
to conform to MISRA® standards. For
example:
short addone(short x)
{
int i0;
i0 = (int)x + (int)1;
if (i0 > (int)32767) {
i0 = (int)32767;

3-38
coder.EmbeddedCodeConfig class

Value Description
}

return (short)i0;
}
'Explicit' Generate C/C++ code that casts data type
values explicitly. For example:
short addone(short x)
{
int i0;
i0 = (int)x + 1;
if (i0 > 32767) {
i0 = 32767;
}

return (short)i0;
}

Default: string, 'Nominal'

CodeExecutionProfiling

Enable execution-time profiling during a software-in-the-loop (SIL) or processor-in-the-


loop (PIL) execution.

Default: false

CodeTemplate

Specify a code generation template for file and function banners in the generated code.
This parameter is a handle to a coder.MATLABCodeTemplate object constructed from a
code generation template (CGT) file.

This parameter is empty by default. If you do not set this parameter to a


coder.MATLABCodeTemplate object, the code generation software generates default
banners.

CodeReplacementLibrary

Specify a code replacement library for the generated code.

3-39
3 Class Reference

Value Description
'None' Does not use a code replacement library.
'GNU C99 extensions' Generates calls to the GNU gcc math
library, which provides C99 extensions as
defined by compiler option -std=gnu99.
'Intel IPP for x86-64 (Windows)' Generates calls to the Intel Performance
Primitives (IPP) library for the x86-64
Windows platform.
'Intel IPP/SSE for x86-64 Generates calls to the IPP and Streaming
(Windows)' SIMD Extensions (SSE) libraries for the
x86-64 Windows platform.
'Intel IPP for x86-64 (Windows Generates calls to the IPP library for the
using MinGW compiler)' x86-64 Windows platform and MinGW
compiler.
'Intel IPP/SSE for x86-64 Generates calls to the IPP and SSE
(Windows using MinGW compiler)' libraries for the x86-64 Windows platform
and MinGW compiler.
'Intel IPP for x86/Pentium Generates calls to the IPP library for the
(Windows)' x86/Pentium Windows platform.
'Intel IPP/SSE x86/Pentium Generates calls to the IPP and SSE
(Windows)' libraries for the x86/Pentium Windows
platform.
'Intel IPP for x86-64 (Linux)' Generates calls to the IPP library for the
x86-64 Linux platform.
'Intel IPP/SSE with GNU99 Generates calls to the GNU libraries for
extensions for x86-64 (Linux)' IPP and SSE, with GNU C99 extensions,
for the x86-64 Linux platform.

Compatible libraries depend on these parameters:

• TargetLang
• TargetLangStandard
• ProdHWDeviceType in the hardware implementation configuration object.

Embedded Coder offers more libraries and the ability to create and use custom code
replacement libraries.

3-40
coder.EmbeddedCodeConfig class

MATLAB Coder generates the minimal set of #include statements for header files
required by the selected code replacement library.

Before setting this parameter, verify that your compiler supports the library that
you want to use. If you select a parameter value that your compiler does not support,
compiler errors can occur.

Note: MATLAB Coder software does not support TLC callbacks.

Default: string, 'None'

CommentStyle

Specify comment style in the generated C or C++ code.

Value Description
'Auto' For C, generate multiline comments. For C++, generate single-
line comments.
'Single-line' Generate single-line comments preceded by //.
'Multi-line' Generate single or multiline comments delimited by /* and */.

For C code generation, specify the single-line comment style only if your compiler
supports it.

Dependency: GenerateComments enables this parameter.

Default: string, 'Auto'

ConvertIfToSwitch

Select whether to convert if-elseif-else patterns to switch-case statements. This


optimization works only for integer and enumerated type inputs.

Default: false

ConstantFoldingTimeout

Specify the maximum number of instructions that the constant folder executes before
stopping. In some situations, code generation requires specific instructions to be
constant. If code generation is failing, increase this value.

3-41
3 Class Reference

Default: integer, 10000

CustomHeaderCode

Specify code to appear near the top of each C/C++ header file generated from your
MATLAB algorithm code.

Default: string, ''

CustomInclude

Specify a space-separated list of include folders to add to the include path when
compiling the generated code.

If your list includes Windows path strings that contain spaces, enclose each instance in
double quotes within the argument string, for example:

'C:\Project "C:\Custom Files"'

Default: string, ''

CustomInitializer

Specify code to appear in the initialize function of the generated .c or .cpp file.

Default: string, ''

CustomLAPACKCallback

Specify the name of a LAPACK callback class that derives from coder.LAPACKCallback.
If you specify a LAPACK callback class, for certain linear algebra functions, the code
generation software generates LAPACK calls by using the LAPACKE C interface to your
LAPACK library. The callback class provides the name of your LAPACKE header file
and the information required to link to your LAPACK library. If this parameter is empty,
the code generation software generates code for linear algebra functions instead of a
LAPACK call.

Default: string, ''

CustomLibrary

Specify a space-separated list of static library files to link with the generated code.

3-42
coder.EmbeddedCodeConfig class

Default: string, ''

CustomSource

Specify a space-separated list of source files to compile and link with the generated code.

Default: string, ''

CustomSourceCode

Specify code to appear near the top of the generated .c or .cpp file, outside of a function.

Default: string, ''

CustomSymbolStrEMXArray

Customize generated identifiers for EMX Array types (Embeddable mxArray types). See
“Settings” on page 3-60.

Default: string, 'emxArray_$M$N'

CustomSymbolStrEMXArrayFcn

Customize generated identifiers for EMX Array (Embeddable mxArrays) utility


functions. See “Settings” on page 3-60.

Default: string, 'emx$M$N'

CustomSymbolStrFcn

Customize generated local function identifiers. See “Settings” on page 3-60.

Default: string, 'm_$M$N'

CustomSymbolStrField

Customize generated field names in global type identifiers. See “Settings” on page
3-60.

Default: string, '$M$N'

CustomSymbolStrGlobalVar

Customize generated global variable identifiers. See “Settings” on page 3-60.

3-43
3 Class Reference

Default: string, '$M$N'

CustomSymbolStrMacro

Customize generated constant macro identifiers. See “Settings” on page 3-60.

Default: string, '$M$N'

CustomSymbolStrTmpVar

Customize generated local temporary variable identifiers. See “Settings” on page


3-60.

Default: string, '$M$N'

CustomSymbolStrType

Customize generated global type identifiers. See “Settings” on page 3-60.

Default: string, '$M$N'

CustomTerminator

Specify code to appear in the terminate function of the generated .c or .cpp file.

Default: string, ''

CustomToolchainOptions

Specify custom settings for each tool in the selected toolchain, as a cell array.

Dependencies:

• Toolchain determines which tools and options appear in the cell.


• Setting BuildConfiguration to Specify enables the options specified by
CustomToolchainOptions.

Start by getting the current options and values. For example:

rtwdemo_sil_topmodel;
set_param(gcs, 'BuildConfiguration', 'Specify')
opt = get_param(gcs, 'CustomToolchainOptions')

3-44
coder.EmbeddedCodeConfig class

Then edit the values in opt.

These values derive from the toolchain definition file and the third-party compiler
options. See “Custom Toolchain Registration”.

Default: cell array

DataTypeReplacement

Specify whether to use built-in C data types or pre-defined types from rtwtypes.h in
generated code.

Set to 'CoderTypeDefs' to use the data types from rtwtypes.h. Otherwise, to use
built-in C data types, retain default value or set to 'CBuiltIn'.

Default: string, 'CBuiltIn'

Description

Description of the coder.EmbeddedCodeConfig object.

Default: string, 'class EmbeddedCodeConfig: C code generation Ecoder


configuration objects'

DynamicMemoryAllocation

Control use of dynamic memory allocation for variable-size data.

By default, dynamic memory allocation is enabled for variable-size arrays whose size (in
bytes) is greater than or equal to DynamicMemoryAllocationThreshold. codegen
allocates memory for this variable-size data dynamically on the heap.

Set this property to 'Off' to allocate memory statically on the stack. Set it to
'AllVariableSizeArrays' to allocate memory for all variable-size arrays dynamically
on the heap. You must use dynamic memory allocation for unbounded, variable-size
data.

Dependencies:

• EnableVariableSizing enables this parameter.


• Setting this parameter to 'Threshold' enables the
DynamicMemoryAllocationThreshold parameter.

3-45
3 Class Reference

Default: string, 'Threshold'

DynamicMemoryAllocationThreshold

Specify the size threshold in bytes.codegen allocates memory on the heap for variable-
size arrays whose size is greater than or equal to this threshold.

Dependency:

• Setting DynamicMemoryAllocation to 'Threshold' enables this parameter.

Default: integer, 65536

EnableAutoExtrinsicCalls

Specify whether MATLAB Coder must treat common visualization functions as


extrinsic functions. When this option is enabled, MATLAB Coder detects calls to many
common visualization functions, such as plot, disp, and figure. For MEX code
generation, MATLAB Coder calls out to MATLAB for these functions. For standalone
code generation, MATLAB Coder does not generate code for these visualization functions.
This capability reduces the amount of time that you spend making your code suitable
for code generation. It also removes the requirement to declare these functions extrinsic
using the coder.extrinsic function.

Default: true

EnableMemcpy

Enable the memcpy optimization. To optimize code that copies consecutive array
elements, the memcpy optimization replaces the code with a memcpy call. A memcpy call
can be more efficient than code, such as a for-loop or multiple, consecutive element
assignments. The code generation software invokes the memcpy optimization when the
following conditions are true:

• EnableMemcpy is true.
• The number of bytes to copy is greater than or equal to MemcpyThreshold. The
number of bytes to copy is the number of array elements multiplied by the number of
bytes required for the C/C++ data type.

See “memcpy Optimization”.

Default: true

3-46
coder.EmbeddedCodeConfig class

EnableOpenMP

If possible, enable OpenMP. Using the OpenMP library, the C/C++ code that MATLAB
Coder generates for parfor-loops can run on multiple threads. With OpenMP disabled,
MATLAB Coder treats parfor-loops as for-loops and generates C/C++ code that runs on
a single thread.

Default: true

EnableSignedLeftShifts

Specify whether to replace multiplications by powers of two with signed left bitwise
shifts in the generated C/C++ code. Some coding standards, such as MISRA, do not allow
bitwise operations on signed integers. To increase the likelihood of generating MISRA C®
compliant code, set this option to false.

When this option is true, MATLAB Coder uses signed left shifts for multiplication by
powers of two. Here is an example of generated C code that uses signed left shift for
multiplication by eight:
i <<= 3;

When this option is false, MATLAB Coder does not use signed left shifts for
multiplication by powers of two. Here is an example of generated C code that does not
use signed left shift for multiplication by eight:
i = i * 8;

Default: true

EnableSignedRightShifts

Specify whether to allow signed right bitwise shifts in the generated C/C++ code. Some
coding standards, such as MISRA, do not allow bitwise operations on signed integers. To
increase the likelihood of generating MISRA-C:2004 compliant code, set this option to
false.

When this option is true, MATLAB Coder uses signed right shifts. Here is an example of
generated C code that uses a signed right shift:
i >>= 3

When this option is false, MATLAB Coder replaces right shifts on signed integers with
a function call in the generated code.

3-47
3 Class Reference

i = asr_s32(i, 3U);

Default: true

EnableVariableSizing

Enable support for variable-size arrays.

Dependency:

• This parameter enables the parameter DynamicMemoryAllocation.

Default: true

FilePartitionMethod

Specify whether to generate one C/C++ file for each MATLAB language file
('MapMFileToCFile') or generate all C/C++ functions into a single file
('SingleFile').

Default: string, 'MapMFileToCFile'

GenerateCodeMetricsReport

Generate a static code metrics report including generated file information, number of
lines, and memory usage.

Default: false

GenCodeOnly

Specify code generation versus an executable or library build.

Default: false

GenerateCodeReplacementReport

Generate a code replacements report that summarizes the replacements used from the
selected code replacement library. The report provides a mapping between each code
replacement instance and the line of MATLAB code that triggered the replacement.

Default: false

3-48
coder.EmbeddedCodeConfig class

GenerateComments

Place comments in the generated files.

Dependencies:

• Enables CommentStyle.
• Enables MATLABFcnDesc.
• Enables MATLABSourceComments.

Default: true

GenerateExampleMain

Specify whether to generate an example C/C++ main function. If example main


generation is enabled, MATLAB Coder generates source and header files for the
main function in the examples subfolder of the build folder. For C code generation, it
generates the files main.c and main.h. For C++ code generation, it generates the files
main.cpp and main.h.

The example main function declares and initializes data. It calls entry-point functions
but does not use values returned from the entry-point functions.

Before you use the example main files, copy them to another location and modify them to
meet the requirements of your application.

Value Description
'DoNotGenerate' Does not generate an example C/C++ main
function.
'GenerateCodeOnly' Generates an example C/C++ main
function but does not compile it.
'GenerateCodeAndCompile' Generates an example C/C++ main
function and compiles it to create a test
executable. This executable does not return
output.

If the GenCodeOnly parameter is true,


MATLAB Coder does not compile the C/C+
+ main function.

3-49
3 Class Reference

Default: string, 'GenerateCodeOnly'

GenerateMakefile

Specify whether to generate a makefile during the build process.

Default: true

GenerateReport

Default: false

Hardware

Handle to coder.Hardware object that specifies the hardware board for processor-in-
the-loop (PIL) execution. Use coder.hardware to create the coder.Hardware object.
For example:

cfg = coder.config('lib','ecoder',true);
hw = coder.hardware('BeagleBone Black');
cfg.Hardware = hw;

Dependencies:

• Setting Hardware sets HardwareImplementation to a


coder.HardwareImplementation object customized for the hardware specified by
Hardware.

HardwareImplementation

Handle to coder.HardwareImplementation object that specifies hardware-specific


configuration parameters for C/C++ code generation.

If you set the Hardware property, HardwareImplementation is set to a


coder.HardwareImplementation object customized for the hardware that is specified
by Hardware. If you do not set the Hardware property, HardwareImplementation
defaults to a coder.HardwareImplementation object with properties that are set for
the MATLAB host computer.

Dependency:

3-50
coder.EmbeddedCodeConfig class

Setting Hardware sets HardwareImplementation to a


coder.HardwareImplementation object customized for the hardware that is specified
by Hardware.

HighlightPotentialDataTypeIssues

Highlight potential data type issues in the code generation report. If this option is
enabled, the code generation report highlights MATLAB code that results in single-
precision or double-precision operations in the generated C/C++ code. If you have a
Fixed-Point Designer™ license, the report also highlights expressions in the MATLAB
code that result in expensive fixed-point operations in the generated code.

IncludeTerminateFcn

Generate a terminate function.

If you set this property to false but a terminate function is required, for example, to free
memory, MATLAB Coder issues a warning.

Default: true

IndentSize

Specify the number of characters per indentation level. Specify an integer from 2 to 8.

Default: 2

IndentStyle

Specify the style for the placement of braces in the generated C/C++ code.

Value Description
'K&R' For blocks within a function, an opening brace is on the same line
as its control statement. For example:
void addone(const double x[6], double z[6])
{
int i0;
for (i0 = 0; i0 < 6; i0++) {
z[i0] = x[i0] + 1.0;
}
}

3-51
3 Class Reference

Value Description
'Allman' For blocks within a function, an opening brace is on its own line at
the same indentation level as its control statement. For example:
void addone(const double x[6], double z[6])
{
int i0;
for (i0 = 0; i0 < 6; i0++)
{
z[i0] = x[i0] + 1.0;
}
}

Default: 'K&R'

InitFltsAndDblsToZero

Enable the memset optimization for assignment of float or double 0 to consecutive


array elements. To optimize code that assigns a constant value to consecutive array
elements, the memset optimization replaces the code with a memset call. A memset call
can be more efficient than code, such as a for-loop or multiple, consecutive element
assignments. To assign float or double 0 to consecutive array elements, the code
generation software invokes the memset optimization when the following conditions are
true:

• InitFltsAndDblsToZero is true.
• The number of bytes to assign is greater than or equal to MemcpyThreshold. The
number of bytes to assign is the number of array elements multiplied by the number
of bytes required for the C/C++ data type.

See “memset Optimization”.

Default: true

InlineStackLimit

Specify the stack size limit on inlined functions. This specification determines the
amount of stack space allocated for local variables of the inlined function.

Specifying a limit on the stack space constrains the amount of inlining allowed. For out-
of-line functions, stack space for variables local to the function is released when the
function returns. However, for inlined functions, stack space remains occupied by the
local variables even when the function returns.

3-52
coder.EmbeddedCodeConfig class

This feature is especially important for embedded processors, where stack size can be
limited.

Default: integer, 4000

InlineThreshold

Specify function size for inline threshold. Unless there are conflicts with other inlining
conditions, MATLAB Coder inlines functions that are smaller than this size.

The function size is measured in terms of an abstract number of instructions, not actual
MATLAB instructions or instructions in the target processor. You must experiment with
this parameter to obtain the inlining behavior that you want. For instance, if the default
setting for this parameter is leading to large functions being inlined, you can tune the
parameter in steps until you are satisfied with the inlining behavior.

Default: integer, 10

InlineThresholdMax

Specify the maximum size of functions after inlining. If the size of the calling function
after inlining exceeds InlineThresholdMax, MATLAB Coder does not inline the called
function.

The function size is measured in terms of an abstract number of instructions, not actual
MATLAB instructions or instructions in the target processor. You must experiment with
this parameter to obtain the inlining behavior that you want. For instance, if the default
setting for this parameter is leading to the inlining of large functions, you can tune the
parameter in steps until you are satisfied with the inlining behavior.

Default: integer, 200

LaunchReport

Specify whether to display a report after code generation is complete or an error occurs.

Default: true

MATLABFcnDesc

Include MATLAB function help text in a function banner in generated code. If not
selected, MATLAB Coder treats the help text as a user comment.

3-53
3 Class Reference

Dependencies:

• GenerateComments enables this parameter.

Default: true

MATLABSourceComments

Include MATLAB source code as comments in the generated code.

Dependencies:

• GenerateComments enables this parameter.

Default: false

MaxIdLength

Specify maximum number of characters in generated function, type definition, and


variable names. To avoid truncation of identifiers by the target C compiler, specify a
value that matches the maximum identifier length of the target C compiler.

This parameter does not apply to exported identifiers, such as the generated names for
entry-point functions or emxArray API functions. If the length of an exported identifier
exceeds the maximum identifier length of the target C compiler, the target C compiler
truncates the exported identifier.

Minimum is 31. Maximum is 256.

Default: integer, 31

MemcpyThreshold

Specify the minimum number of bytes for the code generation software to invoke the
memcpy optimization or the memset optimization. To optimize generated code that copies
consecutive array elements, the code generation software tries to replace the code with
a memcpy call. To optimize generated code that assigns a literal constant to consecutive
array elements, the code generation software tries to replace the code with a memset call.
A memcpy or memset call can be more efficient than code, such as a for-loop or multiple,
consecutive element assignments.

The number of bytes is the number of array elements to copy or assign multiplied by the
number of bytes required for the C/C++ data type.

3-54
coder.EmbeddedCodeConfig class

See “memcpy Optimization” and “memset Optimization”.

Default: integer, 64

MultiInstanceCode

Generate reusable, multi-instance code that is reentrant.

Default: false

Name

Name of the configuration object.

Default: string, 'EmbeddedCodeConfig'

OutputType

Specify whether to generate a standalone C/C++ static library, dynamic library, or


executable. Set to 'LIB' to generate a static library, 'DLL' to generate a dynamic
library or 'EXE' to generate an executable.

Default: string, 'LIB'

ParenthesesLevel

Specify the parenthesization level in the generated C/C++ code.

Value Description
'Minimum' Inserts parentheses where required by
ANSI® C or C++, or to override default
precedence. For example:
Out = In2 - In1 > 1.0 && In2 > 2.0;

If you generate C/C++ code using the


minimum level, for certain settings in
some compilers, you can receive compiler
warnings. To eliminate these warnings, try
the nominal level.

3-55
3 Class Reference

Value Description
'Nominal' Inserts parentheses to balance readability
and visual complexity. For example:
Out = ((In2 - In1 > 1.0) && (In2 > 2.0));

'Maximum' Includes parentheses to specify meaning


without relying on operator precedence.
Code generated with this setting conforms
to MISRA requirements. For example:
Out = (((In2 - In1) > 1.0) && (In2 > 2.0));

Default: string, 'Nominal'

PassStructByReference

Specify whether to pass structures by reference to entry-point functions. Set to true to


pass structures by reference. You thereby reduce memory usage and execution time by
minimizing the number of copies of parameters at entry-point function boundaries. Set to
false to pass structures by value.

This parameter applies only to entry-point functions.

If you set this parameter to true, an entry-point function that writes to a field of a
structure parameter overwrites the input value.

Default: true

PostCodeGenCommand

Specify command to customize build processing after code generation using codegen.

Default: string, ''

PreserveExternInFcnDecls

Specify whether the declarations of external functions generated by codegen include the
extern keyword.

Default: true

PreserveVariableNames

Specify the variable names that the variable reuse optimization must preserve.

3-56
coder.EmbeddedCodeConfig class

Value Description
'UserNames' Preserve names that correspond to user-
defined variables in the MATLAB code. For
this option, the variable reuse optimization
does not replace your variable name with
another name and does not use your name
for another variable. Use this option for
readability. You can more easily trace the
variables in the generated code back to the
variables in your MATLAB code.

The variable reuse optimization preserves


your variable names, however, other
optimizations can remove them from the
generated code. MATLAB Coder does not
reuse your variables in the generated C/
C++ code, however, the C/C++ compiler
can reuse these variables in the generated
binary code.
'None' The variable reuse optimization does not
have to preserve any variable names. It
can reuse any variables that meet the
requirements for variable reuse. If your
code uses large data structures or arrays,
in some cases, the extra memory required
to preserve your variable names can affect
performance. In these cases, use this
option to reduce memory usage or improve
execution speed.
'All' Preserve all variable names. This option
disables variable reuse. Use this option
only for testing or debugging. Do not use
this option for production code.

Default: string, 'UserNames'

PurelyIntegerCode

Specify whether to generate floating-point data and operations.

3-57
3 Class Reference

Default: false

ReservedNameArray

Enter a space-separated list of names that MATLAB Coder is not to use for naming
functions or variables.

Default: string, ''

RuntimeChecks

Enable run-time error detection and reporting in the generated C/C++ code. If you select
this option, the generated code checks for errors such as out-of-bounds array indexing.

The error reporting software uses fprintf to write error messages to stderr. It uses
abort to terminate the application. If fprintf and abort are not available, you must
provide them. The abort function abruptly terminates the program. If your system
supports signals, you can catch the abort signal (SIGABRT) so that you can control the
program termination.

Error messages are in English.

Default: false

SaturateOnIntegerOverflow

Overflows saturate to either the minimum or maximum value that the data type can
represent. Otherwise, the overflow behavior depends on your target C compiler. Most C
compilers wrap on overflow.

This parameter applies only to MATLAB built-in integer types. It does not apply to
doubles, singles, or fixed-point data types.

Default: true

SILDebugging

Enable debugger to observe code behavior during a software-in-the-loop (SIL) execution.

The software supports the following debuggers:

• On Windows, Microsoft Visual C++® debugger.


• On Linux, GNU Data Display Debugger (DDD).

3-58
coder.EmbeddedCodeConfig class

Default: false

StackUsageMax

Specify the maximum stack usage per application in bytes. Set a limit that is lower than
the available stack size. Otherwise, a run-time stack overflow can occur. The C compiler
detects and reports overflows.

Default: integer, 200000

SupportNonFinite

Specify whether to generate nonfinite data and operations.

Default: true

TargetLang

Specify the target language. Set to 'C' to generate C code. Set to C++ to generate C++
code. If you specify C++, MATLAB Coder wraps the C code into .cpp files so that you can
use a C++ compiler and interface with external C++ applications. It does not generate C+
+ classes.

Default: string, 'C'

TargetLangStandard

Specify a standard math library for the generated code. Options include 'C89/C90
(ANSI)', 'C99 (ISO)', and 'C++03 (ISO)'.

Before setting this parameter, verify that your compiler supports the library that
you want to use. If you select a parameter value that your compiler does not support,
compiler errors can occur.

Default: string, 'C89/C90 (ANSI)'

Toolchain

Specify the toolchain to use. If you do not specify a toolchain, MATLAB Coder
automatically locates an installed toolchain.

Default: string, 'Automatically locate an installed toolchain'

3-59
3 Class Reference

Verbose

Display code generation progress.

Default: false

VerificationMode

Specify code verification mode.

• 'None' — Normal execution


• 'SIL' — Software-in-the-loop (SIL) execution
• 'PIL' — Processor-in-the-loop (PIL) execution

Default: string, 'None'

Settings
Enter a macro string that specifies whether, and in what order, certain substrings appear
in the generated identifier. The macro string can include valid C-identifier characters
and a combination of the following format tokens:

Token Description
$M Insert name mangling string to avoid naming collisions.

Required.
$N Insert name of parameter (global variable, global type, local function,
local temporary variable, or constant macro) for which identifier is
generated.

Improves readability of generated code.


$R Insert root project name into identifier, replacing unsupported
characters with the underscore (_) character.

Copy Semantics
Handle. To learn how handle classes affect copy operations, see Copying Objects in the
MATLAB documentation.

3-60
coder.EmbeddedCodeConfig class

Examples
Generate a standalone C/C++ static library from a MATLAB function that is suitable for
code generation.

Note: To generate code for this example, you must have an Embedded Coder license.

1 Write a MATLAB function, coderand, that generates a random scalar value from
the standard uniform distribution on the open interval (0,1).
function r = coderand() %#codegen
% The directive %#codegen declares that the function
% is intended for code generation
r = rand();
2 Create a code generation configuration object to generate a static library.
cfg = coder.config('lib')
This command creates a coder.EmbeddedCodeConfig object.
3 Set the PurelyIntegerCode parameter to true to enable generation of integer-
only code.
cfg.PurelyIntegerCode = true;
4 Generate the C library files in the default folder (codegen/lib/coderand). Use the -
config option to specify the configuration object.

codegen -config cfg coderand

Alternatives
Use the coder function to create a MATLAB Coder project. The project provides a
user interface that facilitates adding MATLAB files, defining input parameters, and
specifying build parameters.

See Also
codegen | coder | coder.config

3-61
3 Class Reference

coder.EnumType class
Package: coder
Superclasses: coder.ArrayType

Represent set of MATLAB enumerations

Description
Specifies the set of MATLAB enumerations that the generated code should accept. Use
only with the codegen -args options. Do not pass as an input to a generated MEX
function.

Construction
enum_type = coder.typeof(enum_value) creates a coder.EnumType object
representing a set of enumeration values of class (enum_value).

enum_type = coder.typeof(enum_value, sz, variable_dims) returns a


modified copy of coder.typeof(enum_value) with (upper bound) size specified by sz
and variable dimensions variable_dims. If sz specifies inf for a dimension, then the
size of the dimension is unbounded and the dimension is variable size. When sz is [],
the (upper bound) sizes of v do not change. If you do not specify variable_dims, the
bounded dimensions of the type are fixed; the unbounded dimensions are variable size.
When variable_dims is a scalar, it applies to bounded dimensions that are not 1 or 0
(which are fixed).

enum_type = coder.newtype(enum_name,sz,variable_dims) creates a


coder.EnumType object that has variable size with (upper bound) sizes sz and variable
dimensions variable_dims. If sz specifies inf for a dimension, then the size of
the dimension is unbounded and the dimension is variable size. If you do not specify
variable_dims, the bounded dimensions of the type are fixed. When variable_dims
is a scalar, it applies to bounded dimensions that are not 1 or 0 (which are fixed).

Input Arguments
enum_value
Enumeration value defined in a file on the MATLAB path.

3-62
coder.EnumType class

sz

Size vector specifying each dimension of type object.

Default: [1 1] for coder.newtype

variable_dims

Logical vector that specifies whether each dimension is variable size (true) or fixed size
(false).

Default: false(size(sz)) | sz==Inf for coder.newtype

enum_name

Name of a numeration defined in a file on the MATLAB path.

Properties
ClassName

Class of values in the set.

SizeVector

The upper-bound size of arrays in the set.

VariableDims

A vector specifying whether each dimension of the array is fixed or variable size. If a
vector element is true, the corresponding dimension is variable size.

Copy Semantics
Value. To learn how value classes affect copy operations, see Copying Objects in the
MATLAB documentation.

Examples
Create a coder.EnumType object using a value from an existing MATLAB enumeration.

3-63
3 Class Reference

1 Define an enumeration MyColors. On the MATLAB path, create a file named


'MyColors' containing:
classdef MyColors < int32
enumeration
green(1),
red(2),
end
end
2 Create a coder.EnumType object from this enumeration.

t = coder.typeof(MyColors.red);

Create a coder.EnumType object using the name of an existing MATLAB enumeration.

1 Define an enumeration MyColors. On the MATLAB path, create a file named


'MyColors' containing:
classdef MyColors < int32
enumeration
green(1),
red(2),
end
end
2 Create a coder.EnumType object from this enumeration.

t = coder.newtype('MyColors');

See Also
coder.ArrayType | coder.newtype | coder.Type | coder.typeof | coder.resize |
codegen

How To
• “Enumerated Data”

Introduced in R2011a

3-64
coder.ExternalDependency class

coder.ExternalDependency class
Package: coder

Interface to external code

Description
coder.ExternalDependency is an abstract class for encapsulating the interface
between external code and MATLAB code intended for code generation. You define
classes that derive from coder.ExternalDependency to encapsulate the interface to
external libraries, object files, and C/C++ source code. This encapsulation allows you to
separate the details of the interface from your MATLAB code. The derived class contains
information about external file locations, build information, and the programming
interface to external functions.

To define a class, myclass, make the following line the first line of your class definition
file:

classdef myclass < coder.ExternalDependency

You must define all of the methods listed in “Methods” on page 3-66. These
methods are static and are not compiled. When you write these methods, use
coder.BuildConfig methods to access build information.

You also define methods that call the external code. These methods are compiled. For
each external function that you want to call, write a method to define the programming
interface to the function. In the method, use coder.ceval to call the external function.
Suppose you define the following method for a class named AdderAPI:

function c = adder(a, b)
coder.cinclude('adder.h');
c = 0;
c = coder.ceval('adder', a, b);
end
This method defines the interface to a function adder which has two inputs a and b. In
your MATLAB code, call adder this way:

y = AdderAPI.adder(x1, x2);

3-65
3 Class Reference

Methods

Examples
Encapsulate the interface to an external C dynamic linked library

This example shows how to encapsulate the interface to an external C dynamic linked
library using coder.ExternalDependency.

Write a function adder that returns the sum of its inputs.


function c = adder(a,b)
%#codegen
c = a + b;
end

Generate a library that contains adder.


codegen('adder','-args', {-2,5}, '-config:dll', '-report');

Write the class definition file AdderAPI.m to encapsulate the library interface.
%================================================================
% This class abstracts the API to an external Adder library.
% It implements static methods for updating the build information
% at compile time and build time.
%================================================================

classdef AdderAPI < coder.ExternalDependency


%#codegen

methods (Static)

function bName = getDescriptiveName(~)


bName = 'AdderAPI';
end

function tf = isSupportedContext(ctx)
if ctx.isMatlabHostTarget()
tf = true;
else
error('adder library not available for this target');
end

3-66
coder.ExternalDependency class

end

function updateBuildInfo(buildInfo, ctx)


[~, linkLibExt, execLibExt, ~] = ctx.getStdLibInfo();

% Header files
hdrFilePath = fullfile(pwd, 'codegen', 'dll', 'adder');
buildInfo.addIncludePaths(hdrFilePath);

% Link files
linkFiles = strcat('adder', linkLibExt);
linkPath = hdrFilePath;
linkPriority = '';
linkPrecompiled = true;
linkLinkOnly = true;
group = '';
buildInfo.addLinkObjects(linkFiles, linkPath, ...
linkPriority, linkPrecompiled, linkLinkOnly, group);

% Non-build files
nbFiles = 'adder';
nbFiles = strcat(nbFiles, execLibExt);
buildInfo.addNonBuildFiles(nbFiles,'','');
end

%API for library function 'adder'


function c = adder(a, b)
if coder.target('MATLAB')
% running in MATLAB, use built-in addition
c = a + b;
else
% running in generated code, call library function
coder.cinclude('adder.h');

% Because MATLAB Coder generated adder, use the


% housekeeping functions before and after calling
% adder with coder.ceval.
% Call initialize function before calling adder for the
% first time.

coder.ceval('adder_initialize');
c = 0;
c = coder.ceval('adder', a, b);

3-67
3 Class Reference

% Call the terminate function after


% calling adder for the last time.

coder.ceval('adder_terminate');
end
end
end
end

Write a function adder_main that calls the external library function adder.

function y = adder_main(x1, x2)


%#codegen
y = AdderAPI.adder(x1, x2);
end

Generate a MEX function for adder_main. The MEX Function exercises the
coder.ExternalDependency methods.

codegen('adder_main', '-args', {7,9}, '-report')

Copy the library to the current folder using the file extension for your platform.

For Windows, use:

copyfile(fullfile(pwd, 'codegen', 'dll', 'adder', 'adder.dll'));

For Linux, use:

copyfile(fullfile(pwd, 'codegen', 'dll', 'adder', 'adder.so'));

Run the MEX function and verify the result.

adder_main_mex(2,3)

See Also
coder.BuildConfig | coder.ceval | coder.cinclude | coder.updateBuildInfo

More About
• “Encapsulating the Interface to External Code”
• “Best Practices for Using coder.ExternalDependency”

3-68
coder.ExternalDependency class

• “Build Information Object”


• “Build Information Methods”

Introduced in R2013b

3-69
3 Class Reference

coder.FiType class
Package: coder
Superclasses: coder.ArrayType

Represent set of MATLAB fixed-point arrays

Description
Specifies the set of fixed-point array values that the generated code should accept. Use
only with the codegen -args options. Do not pass as an input to the generated MEX
function.

Construction
t=coder.typeof(v) creates a coder.FiType object representing a set of fixed-point
values whose properties are based on the fixed-point input v.

t=coder.typeof(v, sz, variable_dims) returns a modified copy of


coder.typeof(v) with (upper bound) size specified by sz and variable dimensions
variable_dims. If sz specifies inf for a dimension, then the size of the dimension is
unbounded and the dimension is variable size. When sz is [], the (upper bound) sizes of
v do not change. If you do not specify the variable_dims input parameter, the bounded
dimensions of the type are fixed. When variable_dims is a scalar, it applies to the
bounded dimensions that are not 1 or 0 (which are fixed).

t=coder.newtype('embedded.fi', numerictype, sz, variable_dims) creates


a coder.Type object representing a set of fixed-point values with numerictype and
(upper bound) sizes sz and variable dimensions variable_dims. If sz specifies inf for
a dimension, then the size of the dimension is unbounded and the dimension is variable
size. When you do not specify variable_dims, the bounded dimensions of the type are
fixed. When variable_dims is a scalar, it applies to the bounded dimensions that are
not 1 or 0 (which are fixed).

t=coder.newtype('embedded.fi', numerictype, sz, variable_dims,


Name, Value) creates a coder.Type object representing a set of fixed-point values
with numerictype and additional options specified by one or more Name, Value pair

3-70
coder.FiType class

arguments. Name can also be a property name and Value is the corresponding value.
Name must appear inside single quotes (''). You can specify several name-value pair
arguments in any order as Name1,Value1,…,NameN,ValueN.

Input Arguments
v

Fixed-point value used to create new coder.FiType object.

sz

Size vector specifying each dimension of type object.

Default: [1 1] for coder.newtype

variable_dims

Logical vector that specifies whether each dimension is variable size (true) or fixed size
(false).

Default: false(size(sz)) | sz ==Inf for coder.newtype

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the


argument name and Value is the corresponding value. Name must appear inside single
quotes (' '). You can specify several name and value pair arguments in any order as
Name1,Value1,...,NameN,ValueN.

'complex'

Set complex to true to create a coder.Type object that can represent complex values.
The type must support complex data.

Default: false

'fimath'

Specify local fimath. If not, uses default fimath.

3-71
3 Class Reference

Properties
ClassName

Class of values in the set.

Complex

Indicates whether fixed-point arrays in the set are real (false) or complex (true).

Fimath

Local fimath that the fixed-point arrays in the set use.

NumericType

numerictype that the fixed-point arrays in the set use.

SizeVector

The upper-bound size of arrays in the set.

VariableDims

A vector specifying whether each dimension of the array is fixed or variable size. If a
vector element is true, the corresponding dimension is variable size.

Copy Semantics
Value. To learn how value classes affect copy operations, see Copying Objects in the
MATLAB documentation.

Examples
Create a new fixed-point type t.
t = coder.typeof(fi(1));
% Returns
% coder.FiType

3-72
coder.FiType class

% 1x1 embedded.fi
% DataTypeMode:Fixed-point: binary point scaling
% Signedness:Signed
% WordLength:16
% FractionLength:14

Create a new fixed-point type for use in code generation. The fixed-point type uses the
default fimath.

t = coder.newtype('embedded.fi',numerictype(1, 16, 15), [1 2])

t =
% Returns
% coder.FiType
% 1x2 embedded.fi
% DataTypeMode: Fixed-point: binary point scaling
% Signedness: Signed
% WordLength: 16
% FractionLength: 15

This new type uses the default fimath.

See Also
coder.ArrayType | coder.resize | coder.Type | coder.typeof | coder.newtype |
codegen

Introduced in R2011a

3-73
3 Class Reference

coder.FixptConfig class
Package: coder

Floating-point to fixed-point conversion configuration object

Description
A coder.FixptConfig object contains the configuration parameters that the MATLAB
Coder codegen function requires to convert floating-point MATLAB code to fixed-point
MATLAB code during code generation. Use the -float2fixed option to pass this object
to the codegen function.

Construction
fixptcfg = coder.config('fixpt') creates a coder.FixptConfig object for
floating-point to fixed-point conversion.

Properties
ComputeDerivedRanges

Enable derived range analysis.

Values: true|false (default)

ComputeSimulationRanges

Enable collection and reporting of simulation range data. If you need to run a long
simulation to cover the complete dynamic range of your design, consider disabling
simulation range collection and running derived range analysis instead.

Values: true (default)|false

DefaultFractionLength

Default fixed-point fraction length.

3-74
coder.FixptConfig class

Values: 4 (default) | positive integer

DefaultSignedness

Default signedness of variables in the generated code.

Values: 'Automatic' (default) | 'Signed' | 'Unsigned'

DefaultWordLength

Default fixed-point word length.

Values: 14 (default) | positive integer

DetectFixptOverflows

Enable detection of overflows using scaled doubles.

Values: true| false (default)

fimath

fimath properties to use for conversion.

Values: fimath('RoundingMethod', 'Floor', 'OverflowAction', 'Wrap',


'ProductMode', 'FullPrecision', 'SumMode', 'FullPrecision') (default) |
string

FixPtFileNameSuffix

Suffix for fixed-point file names.

Values: '_fixpt' | string

LaunchNumericTypesReport

View the numeric types report after the software has proposed fixed-point types.

Values: true (default) | false

LogIOForComparisonPlotting

Enable simulation data logging to plot the data differences introduced by fixed-point
conversion.

3-75
3 Class Reference

Values: true (default) | false

OptimizeWholeNumber

Optimize the word lengths of variables whose simulation min/max logs indicate that they
are always whole numbers.

Values: true (default) | false

PlotFunction

Name of function to use for comparison plots.

LogIOForComparisonPlotting must be set to true to enable comparison plotting. This


option takes precedence over PlotWithSimulationDataInspector.

The plot function should accept three inputs:

• A structure that holds the name of the variable and the function that uses it.
• A cell array to hold the logged floating-point values for the variable.
• A cell array to hold the logged values for the variable after fixed-point conversion.

Values: '' (default) | string

PlotWithSimulationDataInspector

Use Simulation Data Inspector for comparison plots.

LogIOForComparisonPlotting must be set to true to enable comparison plotting. The


PlotFunction option takes precedence over PlotWithSimulationDataInspector.

Values: true| false (default)

ProposeFractionLengthsForDefaultWordLength

Propose fixed-point types based on DefaultWordLength.

Values: true (default) | false

ProposeTargetContainerTypes

By default (false), propose data types with the minimum word length needed to represent
the value. When set to true, propose data type with the smallest word length that can

3-76
coder.FixptConfig class

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.

Values: true| false (default)

ProposeWordLengthsForDefaultFractionLength

Propose fixed-point types based on DefaultFractionLength.

Values: false (default) | true

ProposeTypesUsing

Propose data types based on simulation range data, derived ranges, or both.

Values: 'BothSimulationAndDerivedRanges' (default) |


'SimulationRanges'|'DerivedRanges'

SafetyMargin

Safety margin percentage by which to increase the simulation range when proposing
fixed-point types. The specified safety margin must be a real number greater than -100.

Values: 0 (default) | double

StaticAnalysisQuickMode

Perform faster static analysis.

Values: true | false (default)

StaticAnalysisTimeoutMinutes

Abort analysis if timeout is reached.

Values: '' (default) | positive integer

TestBenchName

Test bench function name or names, specified as a string or cell array of strings. You
must specify at least one test bench.

If you do not explicitly specify input parameter data types, the conversion uses the first
test bench function to infer these data types.

3-77
3 Class Reference

Values: '' (default) | string | cell array of strings

TestNumerics

Enable numerics testing.

Values: true| false (default)

Methods

Examples
Generate Fixed-Point C Code from Floating-Point MATLAB Code

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 dti_test.

fixptcfg.TestBenchName = 'dti_test';

Create a code generation configuration object to generate a standalone C static library.

cfg = coder.config('lib');

Convert a floating-point MATLAB function to fixed-point C code. In this example, the


MATLAB function name is dti.

codegen -float2fixed fixptcfg -config cfg dti

Convert Floating-Point MATLAB Code to Fixed Point Based On Derived Ranges

Create a coder.FixptConfig object, fixptcfg, with default settings.

fixptcfg = coder.config('fixpt');

Set the name of the test bench to use to infer input data types. In this example, the test
bench function name is dti_test. The conversion process uses the test bench to infer
input data types.

3-78
coder.FixptConfig class

fixptcfg.TestBenchName = 'dti_test';

Select to propose data types based on derived ranges.


fixptcfg.ProposeTypesUsing = 'DerivedRanges';
fixptcfg.ComputeDerivedRanges = true;

Add design ranges. In this example, the dti function has one scalar double input, u_in.
Set the design minimum value for u_in to -1 and the design maximum to 1.
fixptcfg.addDesignRangeSpecification('dti', 'u_in', -1.0, 1.0);

Convert the floating-point MATLAB function, dti, to fixed-point MATLAB code.


codegen -float2fixed fixptcfg dti

Enable Overflow Detection

When you select to detect potential overflows, codegen generates a scaled double version
of the generated fixed-point MEX function. Scaled doubles store their data in double-
precision floating-point, so 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.

This example requires MATLAB Coder and Fixed-Point Designer licenses.

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 dti_test.
fixptcfg.TestBenchName = 'dti_test';

Enable numerics testing with overflow detection.


fixptcfg.TestNumerics = true;
fixptcfg.DetectFixptOverflows = true;

Create a code generation configuration object to generate a standalone C static library.


cfg = coder.config('lib');

Convert a floating-point MATLAB function to fixed-point C code. In this example, the


MATLAB function name is dti.

3-79
3 Class Reference

codegen -float2fixed fixptcfg -config cfg dti

• “C Code Generation at the Command Line”

Alternatives
You can convert floating-point MATLAB code to fixed-point code using the MATLAB
Coder app. Open the app using one of these methods:

• On the Apps tab, in the Code Generation section, click MATLAB Coder.
• Use the coder command.

See “Convert MATLAB Code to Fixed-Point C Code”.

See Also
coder.codeConfig | codegen | coder | coder.config

3-80
coder.HardwareImplementation class

coder.HardwareImplementation class
Package: coder

codegen configuration object that specifies hardware implementation parameters for


code generation

Description
A coder.HardwareImplementation object contains hardware-specific configuration
parameters. The codegen function uses these parameters to generate standalone C/C
++ libraries and executables for specific target hardware. To use this object, refer to it
from the related coder.CodeConfig or coder.EmbeddedCodeConfig object that codegen is
using.

Construction
hw_cfg = coder.HardwareImplementation creates a
coder.HardwareImplementation object.

Properties
Description

Description of hardware implementation object.

string, 'class HardwareImplementation: Hardware implementation


specifications.' , Maximum Length: 78 characters

Name

Name of hardware implementation object.

string, 'HardwareImplementation' , Maximum Length: 22 characters

3-81
3 Class Reference

ProdBitPerChar

Describe length in bits of the C char data type that the deployment hardware supports.

Value must be a multiple of 8 between 8 and 32.

Dependencies:

• Specifying a device using the ProdHWDeviceType parameter sets a device-specific


value for this parameter.
• This parameter is enabled only if you can modify it for the specified device.

integer, 8

ProdBitPerDouble

Describe the bit length of C double data type that the deployment hardware supports
(read only).

double, 64

ProdBitPerFloat

Describe the bit length of C floating-point data type that the deployment hardware
supports (read only).

double, 32

ProdBitPerInt

Describe length in bits of the C int data type that the deployment hardware supports.

Value must be a multiple of 8 between 8 and 32.

Dependencies:

• Specifying a device using the ProdHWDeviceType parameter sets a device-specific


value for this parameter.

3-82
coder.HardwareImplementation class

• This parameter is enabled only if you can modify it for the specified device.

integer, 32

ProdBitPerLong

Describe length in bits of the C long data type that the deployment hardware supports.

Value must be a multiple of 8 between 32 and 128.

Dependencies:

• Specifying a device using the ProdHWDeviceType parameter sets a device-specific


value for this parameter.
• This parameter is enabled only if you can modify it for the specified device.

integer, 32

ProdBitPerLongLong

Describe length in bits of the C long long data type that the deployment hardware
supports.

Tips:

• Use the C long long data type only if your C compiler supports long long.
• You can change the value of this parameter only for custom targets. For custom
targets, values must be a multiple of 8 and between 64 and 128.

Dependencies:

• ProdLongLongMode enables use of this parameter.


• The value of this parameter must be greater than or equal to the value of
ProdBitPerLong.
• Selecting a device using the ProdHWDeviceType parameter sets a device-specific
value for this parameter.
• This parameter is enabled only if you can modify it for the specified device.

integer, 64

3-83
3 Class Reference

ProdBitPerPointer

Describe the bit-length of pointer data for the deployment hardware (read only).

integer, 64

ProdBitPerShort

Describe length in bits of the C short data type that the deployment hardware supports.

Value must be a multiple of 8 between 8 and 32.

Dependencies:

• Selecting a device using the ProdHWDeviceType parameter sets a device-specific


value for this parameter.
• This parameter is enabled only if you can modify it for the specified device.

integer, 16

ProdEndianess

Describe significance of the first byte of a data word for the deployment hardware.

string, 'Unspecified', 'LittleEndian', 'BigEndian'

ProdEqTarget

Specify whether the test hardware differs from the deployment hardware.

Dependencies:

• Setting this parameter to true disables the target properties.


• Setting this parameter to false enables the target properties that specify the test
hardware properties.

true, false

ProdHWDeviceType: [1x29 char]

Specify manufacturer and type of hardware that you use to implement the production
version of the system.

3-84
coder.HardwareImplementation class

Because codegen cannot generate code for ASICs or FPGAs, if ProdHWDeviceType


is set to ASIC/FPGA, TestHWDeviceType is automatically set to 'Generic->MATLAB
Host Computer'.

string, 'Generic->MATLAB Host Computer'

ProdIntDivRoundTo

Describe how your compiler rounds the result of dividing one signed integer by another to
produce a signed integer quotient.

string, 'Undefined', 'Zero', 'Floor'

ProdLargestAtomicFloat

Specify the largest floating-point data type that can be atomically loaded and stored on
the deployment hardware.

Dependencies:

• Specifying a device using the ProdHWDeviceType parameter sets a device-specific


value for this parameter.
• This parameter is enabled only if you can modify it for the specified device.

string, 'None'

ProdLargestAtomicInteger

Specify the largest integer data type that can be atomically loaded and stored on the
deployment hardware.

Dependencies:

• Specifying a device using the ProdHWDeviceType parameter sets a device-specific


value for this parameter.
• This parameter is enabled only if you can modify it for the specified device.
• You can set this parameter to long long only if the deployment hardware supports
the C long long data type and you have set the ProdLongLongMode parameter to
true.

string, 'Char'

3-85
3 Class Reference

ProdLongLongMode

Specify that your C compiler supports the C long long data type. Most C99 compilers
support long long. Set to true to enable use of the C long long data type for code
generation for the deployment hardware. Set to false to disable the use of C long long
data type for code generation for the deployment hardware.

Tips:

• This parameter is enabled only if the specified deployment hardware supports the C
long long data type.
• If your compiler does not support C long long, do not select this parameter.

Dependency:

• This parameter enables use of ProdBitPerLongLong.

true, false

ProdShiftRightIntArith

Describe whether your compiler implements a signed integer right shift as an arithmetic
right shift.

true, false

ProdWordSize

Describe microprocessor native word size for the deployment hardware.

Value must be a multiple of 8 between 8 and 64.

Dependencies:

• Selecting a device using the ProdHWDeviceType parameter sets a device-specific


value for this parameter.
• This parameter is enabled only if you can modify it for the specified device.

integer, 64

TargetBitPerChar

Describe length in bits of the C char data type that the test hardware supports.

3-86
coder.HardwareImplementation class

Value must be a multiple of 8 between 8 and 32.

Dependencies:

• Specifying a device using the TargetHWDeviceType parameter sets a device-specific


value for this parameter.
• This parameter is enabled only if you can modify it for the specified device.

integer, 8

TargetBitPerDouble

Describe the bit length of C double data type that the test hardware supports (read
only).

integer, 64

TargetBitPerFloat

Describe the bit length of C floating-point data type that the test hardware supports
(read only).

integer, 32

TargetBitPerInt

Describe length in bits of the C int data type that the test hardware supports.

Value must be a multiple of 8 between 8 and 32.

Dependencies:

• Specifying a device using the TargetHWDeviceType parameter sets a device-specific


value for this parameter.
• This parameter is enabled only if you can modify it for the specified device.

integer, 32

TargetBitPerLong

Describe length in bits of the C long data type that the test hardware supports.

3-87
3 Class Reference

Value must be a multiple of 8 between 32 and 128.

Dependencies:

• Specifying a device using the TargetHWDeviceType parameter sets a device-specific


value for this parameter.
• This parameter is enabled only if you can modify it for the specified device.

integer, 32

TargetBitPerLongLong

Describe length in bits of the C long long data type that the test hardware supports.

Dependencies:

• TargetLongLongMode enables use of this parameter.


• The value of this parameter must be greater than or equal to the value of
TargetBitPerLong.

Tips:

• Use the C long long data type only if your C compiler supports long long.
• Change the value of this parameter for custom targets only. For custom targets,
values must be a multiple of 8 and between 64 and 128.

integer, 64

TargetBitPerPointer

Describe the bit-length of pointer data for the test hardware (read only).

integer, 64

TargetBitPerShort

Describe length in bits of the C short data type that the test hardware supports.

Value must be a multiple of 8 between 8 and 32 .

Dependencies:

3-88
coder.HardwareImplementation class

• Selecting a device using the TargetHWDeviceType parameter sets a device-specific


value for this parameter.
• This parameter is enabled only if you can modify it for the specified device.

integer, 16

TargetEndianess

Describe significance of the first byte of a data word for the test hardware.

string, 'Unspecified', 'LittleEndian', 'BigEndian'

TargetHWDeviceType: [1x29 char]

Specify manufacturer and type of the hardware that you use to test the generated code.

Because codegen cannot generate code for ASICs or FPGAs, if ProdHWDeviceType


is set to ASIC/FPGA, TestHWDeviceType is automatically set to 'Generic->MATLAB
Host Computer'.

string, 'Generic->MATLAB Host Computer'

TargetIntDivRoundTo

Describe how your compiler rounds the result of two signed integers for the test
hardware.

string, 'Undefined', 'Zero', 'Floor'

TargetLargestAtomicFloat

Specify the largest floating-point data type that can be atomically loaded and stored on
the test hardware.

Dependencies:

• Specifying a device using the TargetHWDeviceType parameter sets a device-specific


value for this parameter.
• This parameter is enabled only if you can modify it for the specified device.

string, , 'None'

3-89
3 Class Reference

TargetLargestAtomicInteger

Specify the largest integer data type that can be atomically loaded and stored on the test
hardware.

Dependencies:

• Specifying a device using the TargetHWDeviceType parameter sets a device-specific


value for this parameter.
• This parameter is enabled only if you can modify it for the specified device.
• You can set this parameter to long long only if the test hardware supports the C
long long data type and you have set the TargetLongLongMode parameter to
true.

string, , 'Char'

TargetLongLongMode

Specify that your C compiler supports the C long long data type. Most C99 compilers
support long long. Set to true to enable use of the C long long data type for code
generation for the test hardware. Set to false to disable use of the C long long data
type for code generation for the test hardware.

Tips:

• This parameter is enabled only if the specified test hardware supports the C long
long data type.
• If your compiler does not support C long long, do not select this parameter.

Dependency:

This parameter enables use of TargetBitPerLongLong.

true, false

TargetShiftRightIntArith

Describe whether your compiler implements a signed integer right shift as an arithmetic
right shift.

true, false

3-90
coder.HardwareImplementation class

TargetWordSize

Describe microprocessor native word size for the test hardware.

Value must be a multiple of 8 between 8 and 64.

Dependencies:

• Selecting a device using theTargetHWDeviceType parameter sets a device-specific


value for this parameter.
• This parameter is enabled only if you can modify it for the specified device.

integer, 64

Copy Semantics
Handle. To learn how handle classes affect copy operations, see Copying Objects in the
MATLAB documentation.

Examples
Create a hardware implementation configuration object. Use the object to generate a C
static library.

1 Create a hardware implementation configuration object.

hw_cfg = coder.HardwareImplementation;
2 Create a code generation configuration object to generate a C static library.

cfg = coder.config('lib');
3 Associate the hardware implementation object with the code generation
configuration object.

cfg.HardwareImplementation = hw_cfg;
4 Generate a C library for a MATLAB function foo that has no input parameters.
Specify the configuration object using the -config option:

codegen -config cfg foo

3-91
3 Class Reference

Alternatives
Use the coder function to create a MATLAB Coder project. The project provides a
user interface that facilitates adding MATLAB files, defining input parameters, and
specifying build parameters.

See Also
codegen | coder.CodeConfig | coder | coder.EmbeddedCodeConfig

3-92
coder.LAPACKCallback class

coder.LAPACKCallback class
Package: coder

Abstract class for specifying the LAPACK library and LAPACKE header file for LAPACK
calls in generated code

Description
coder.LAPACKCallback is an abstract class for defining a LAPACK callback class. A
LAPACK callback class specifies the LAPACK library and LAPACKE header file to use
for LAPACK calls in code generated from MATLAB code. If you use MATLAB Coder to
generate standalone code or generate code for the MATLAB Function block, for certain
linear algebra function calls, you can generate LAPACK calls. To generate LAPACK
calls, specify the name of the LAPACK callback class.

• If you generate code by using the MATLAB Coder codegen command, set the code
configuration object property CustomLAPACKCallback to the name of the callback
class.
• If you generate code by using the MATLAB Coder app, set Custom LAPACK library
callback to the name of the callback class.
• If the code is in the MATLAB Function block and you have Simulink Coder, in the
Configuration Parameters dialog box, in the Code Generation category, on the
All Parameters tab, set Custom LAPACK library callback to the name of the
callback class.

To define a LAPACK callback class with the name useMyLAPACK, make the following
line the first line of your class definition file.

classdef useMyLAPACK < coder.LAPACKCallback

You must define all of the methods listed in “Methods” on page 3-94. These methods
are static and are not compiled.

3-93
3 Class Reference

Methods

Examples
Write a LAPACK Callback Class

This example shows how to write a LAPACK callback class.

Use this example LAPACK callback class as a template.


classdef useMyLAPACK < coder.LAPACKCallback
methods (Static)
function hn = getHeaderFilename()
hn = 'mylapacke_custom.h';
end
function updateBuildInfo(buildInfo, buildctx)
buildInfo.addIncludePaths(fullfile(pwd,'include'));
libName = 'mylapack';
libPath = fullfile(pwd,'lib');
[~,linkLibExt] = buildctx.getStdLibInfo();
buildInfo.addLinkObjects([libName linkLibExt], libPath, ...
'', true, true);
buildInfo.addDefines('HAVE_LAPACK_CONFIG_H');
buildInfo.addDefines('LAPACK_COMPLEX_STRUCTURE');
end
end
end

Replace useMyLAPACK with the name of your callback class.

The getHeaderFilename method returns the name of the header file for the LAPACKE
C interface to the LAPACK library. Replace mylapacke_custom.h with the name of
your LAPACKE header file.

The updateBuildInfo method updates the build information with the locations of the
header files and the name and location of the LAPACK library. Replace mylapack with
the name of your LAPACK library.

If your compiler supports only complex data types that are represented as structures,
include these lines in the updateBuildInfo method.
buildInfo.addDefines('HAVE_LAPACK_CONFIG_H');

3-94
coder.LAPACKCallback class

buildInfo.addDefines('LAPACK_COMPLEX_STRUCTURE');

• “Speed Up Linear Algebra in Generated Standalone Code by Using LAPACK Calls”


• “Speed Up Linear Algebra in Code Generated from a MATLAB Function Block”

See Also
coder.ExternalDependency | coder.BuildConfig

External Websites
• www.netlib.org/lapack

Introduced in R2016a

3-95
3 Class Reference

coder.MexCodeConfig class
Package: coder

codegen configuration object that specifies MEX function generation parameters

Description
A coder.MexCodeConfig object contains the configuration parameters required by the
codegen function to generate MEX functions. Use the -config option to pass the object
to the codegen function.

Construction

cfg=coder.config creates a coder.MexCodeConfig object for MEX function


generation.

cfg=coder.config('mex') creates a coder.MexCodeConfig object for MEX function


generation.

Properties
ConstantFoldingTimeout

Specify, as a positive integer, the maximum number of instructions to be executed by the


constant folder.

Default: integer, 10000

ConstantInputs

Specify whether to include constant inputs in the MEX function signature.

By default, ('CheckValues'), the MEX function signature contains the constant inputs.
The run-time values of the constant inputs must match their compile-time values. This

3-96
coder.MexCodeConfig class

option allows you to use the same test file to run the original MATLAB algorithm and the
MEX function. Selecting this option slows down execution of the MEX function.

If you specify 'IgnoreValues', the MEX function signature contains the constant
inputs. The run-time values of the constant inputs are ignored and do not need to match
their compile-time values. This option allows you to use the same test file to run the
original MATLAB algorithm and the MEX function.

If you specify 'Remove', the MEX function signature does not contain the constant
inputs and does not match the MATLAB signature. This option is provided for backwards
compatibility.

Default: string, 'CheckValues'

CustomHeaderCode

Specify code to appear near the top of each C/C++ header file generated from your
MATLAB algorithm code.

Default: string, ''

CustomInclude

Specify a space-separated list of include folders to add to the include path when
compiling the generated code.

If your list includes Windows path strings that contain spaces, enclose each instance in
double quotes within the argument string, for example:
'C:\Project "C:\Custom Files"'

Default: string, ''

CustomInitializer

Specify code to appear in the initialize function of the generated .c or .cpp file.

Default: string, ''

CustomLibrary

Specify a space-separated list of static library files to link with the generated code.

Default: string, ''

3-97
3 Class Reference

CustomSource

Specify a space-separated list of source files to compile and link with the generated code.

Default: string, ''

CustomSourceCode

Specify code to appear near the top of the generated .c or .cpp file, outside of a function.

Default: string, ''

CustomTerminator

Specify code to appear in the terminate function of the generated .c or .cpp file.

Default: string, ''

Description

Description of object.

Default: string, ''

DynamicMemoryAllocation

Control use of dynamic memory allocation for variable-size data.

By default, dynamic memory allocation is enabled for variable-size arrays whose size (in
bytes) is greater than or equal to DynamicMemoryAllocationThreshold and codegen
allocates memory for this variable-size data dynamically on the heap.

Set this property to 'Off' to allocate memory statically on the stack. Set it to
'AllVariableSizeArrays' to allocate memory for all arrays dynamically on the heap .
You must use dynamic memory allocation for unbounded, variable-size data.

Dependencies:

• EnableVariableSizing enables this parameter.


• Setting this parameter to 'Threshold' enables the
DynamicMemoryAllocationThreshold parameter.

Default: string, 'Threshold'

3-98
coder.MexCodeConfig class

DynamicMemoryAllocationThreshold

Specify the size threshold in bytes.codegen allocates memory on the heap for variable-
size arrays whose size is greater than or equal to this threshold.

Dependency:

• Setting DynamicMemoryAllocation to 'Threshold' enables this parameter.

Default: integer, 65536

EchoExpressions

Specify whether or not actions that do not terminate with a semicolon appear in the
MATLAB Command Window.

Default: true

EnableAutoExtrinsicCalls

Specify whether MATLAB Coder should treat common visualization functions as


extrinsic functions. When this option is enabled, MATLAB Coder detects calls to many
common visualization functions, such as plot, disp, and figure. For MEX code
generation, MATLAB Coder calls out to MATLAB for these functions. For standalone
code generation, MATLAB Coder does not generate code for these visualization functions.
This capability reduces the amount of time that you spend making your code suitable
for code generation. It also removes the requirement to declare these functions extrinsic
using the coder.extrinsic function.

Default: true

EnableDebugging

Specify whether to use the debug option for the C compiler. If you enable debug mode,
the C compiler does not optimize the code. The compilation is faster, but the execution is
slower.

Default: false

EnableMemcpy

Enable the memcpy optimization. To optimize code that copies consecutive array
elements, the memcpy optimization replaces the code with a memcpy call. A memcpy call

3-99
3 Class Reference

can be more efficient than code, such as a for-loop or multiple, consecutive element
assignments. The code generation software invokes the memcpy optimization when the
following conditions are true:

• EnableMemcpy is true.
• The number of bytes to copy is greater than or equal to MemcpyThreshold. The
number of bytes to copy is the number of array elements multiplied by the number of
bytes required for the C/C++ data type.

See “memcpy Optimization”.

Default: true

EnableOpenMP

If possible, enable OpenMP. Using the OpenMP library, the MEX functions that
MATLAB Coder generates for parfor-loops can run on multiple threads. With OpenMP
disabled, MATLAB Coder treats parfor-loops as for-loops and generates a MEX function
that runs on a single thread.

Default: true

EnableVariableSizing

Enable support for variable-size arrays.

Dependency:

• Enables Dynamic memory allocation.

Default: true

ExtrinsicCalls

Allow calls to extrinsic functions.

An extrinsic function is a function on the MATLAB path that MATLAB Coder dispatches
to MATLAB software for execution. MATLAB Coder does not compile or generate code for
extrinsic functions.

When enabled (true), generates code for the call to a MATLAB function, but does not
generate the function's internal code.

3-100
coder.MexCodeConfig class

When disabled (false), ignores the extrinsic function. Does not generate code for the call
to the MATLAB function — as long as the extrinsic function does not affect the output of
the MATLAB function. Otherwise, issues a compilation error.

ExtrinsicCalls affects how MEX functions built by MATLAB Coder generate random
numbers when using the MATLAB rand, randi, and randn functions. If extrinsic calls
are enabled, the generated MEX function uses the MATLAB global random number
stream to generate random numbers. If extrinsic calls are not enabled, the MEX function
built with MATLAB Coder uses a self-contained random number generator.

If you disable extrinsic calls, the generated MEX function cannot display run-time
messages from error or assert statements in your MATLAB code. The MEX function
reports that it cannot display the error message. To see the error message, enable
extrinsic function calls and generate the MEX function again.

Default: true

FilePartitionMethod

Specify whether to generate one C/C++ file for each MATLAB language file
('MapMFileToCFile') or generate all C/C++ functions into a single file
('SingleFile').

Default: string, 'MapMFileToCFile'

GenCodeOnly

Control whether to compile the generated MEX function C/C++ code to produce a MEX
function.

Default: false

GenerateComments

Place comments in the generated files.

Default: true

GenerateReport

Document generated code in a report.

Default: false

3-101
3 Class Reference

GlobalDataSyncMethod

Controls synchronization of MEX function global data with the MATLAB global
workspace. For constant global data, controls verification of consistency between the
MEX function constant global data and the MATLAB global workspace.

Value Description for Global Data Description for Constant Global Data
SyncAlways (default) Synchronizes global data at MEX Verifies consistency of constant
function entry and exit and for global data at MEX function entry
extrinsic calls for maximum and after extrinsic calls. The MEX
consistency between MATLAB function ends with an error if the
and the generated MEX function. global data values in the MATLAB
To maximize performance, global workspace are inconsistent
if the extrinsic calls do not with the compile-time constant
change global data, use this global values in the MEX function.
option in conjunction with the Use the coder.extrinsic -
coder.extrinsic -sync:off sync:off option to turn off
option to turn off synchronization consistency checks after specific
for these calls. extrinsic calls.
SyncAtEntryAndExits Synchronizes global data at Verifies constant global data at
MEX function entry and exit MEX function entry only. The MEX
only. To maximize performance, function ends with an error if the
if only a few extrinsic calls global data values in the MATLAB
change global data, use this global workspace are inconsistent
option in conjunction with the with the compile-time constant
coder.extrinsic -sync:on global values in the MEX function.
option to turn on synchronization Use the coder.extrinsic
for these calls. -sync:on option to turn on
consistency checks after specific
extrinsic calls.
NoSync Disables synchronization. Before Disables consistency checks.
disabling synchronization, verify
that your MEX function does not
interact with MATLAB globals.
Otherwise, inconsistencies
between MATLAB and the MEX
function can occur.

Default: SyncAlways

3-102
coder.MexCodeConfig class

InitFltsAndDblsToZero

Enable the memset optimization for assignment of float or double 0 to consecutive


array elements. To optimize code that assigns a constant value to consecutive array
elements, the memset optimization replaces the code with a memset call. A memset call
can be more efficient than code, such as a for-loop or multiple, consecutive element
assignments. To assign float or double 0 to consecutive array elements, the code
generation software invokes the memset optimization when the following conditions are
true:

• InitFltsAndDblsToZero is true.
• The number of bytes to assign is greater than or equal to MemcpyThreshold. The
number of bytes to assign is the number of array elements multiplied by the number
of bytes required for the C/C++ data type.

See “memset Optimization”.

Default: true

InlineStackLimit

Specify the stack size limit on inlined functions. This specification determines the
amount of stack space allocated for local variables of the inlined function.

Specifying a limit on the stack space constrains the amount of inlining allowed. For out-
of-line functions, stack space for variables local to the function is released when the
function returns. However, for inlined functions, stack space remains occupied by the
local variables even when the function returns.

This feature is especially important for embedded processors, where stack size can be
limited.

Default: integer, 4000

InlineThreshold

Specify function size for inline threshold. Unless there are conflicts with other inlining
conditions, MATLAB Coder inlines functions that are smaller than this size.

The function size is measured in terms of an abstract number of instructions, not actual
MATLAB instructions or instructions in the target processor. You must experiment
with this parameter to obtain the inlining behavior that you want. For instance, if the

3-103
3 Class Reference

default setting for this parameter is leading to large functions being inlined and in turn
generating large C code, you can tune the parameter in steps until you are satisfied with
the size of generated code.

Default: integer, 10

InlineThresholdMax

Specify the maximum size of functions after inlining. If the size of the calling function
after inlining exceeds InlineThresholdMax, MATLAB Coder does not inline the called
function.

The function size is measured in terms of an abstract number of instructions, not actual
MATLAB instructions or instructions in the target processor. You must experiment
with this parameter to obtain the inlining behavior that you want. For instance, if the
default setting for this parameter is leading to large functions being inlined and in turn
generating large C code, you can tune the parameter in steps until you are satisfied with
the size of generated code.

Default: integer, 200

IntegrityChecks

Detect violations of memory integrity in code generated for MATLAB functions and stops
execution with a diagnostic message.

Setting IntegrityChecks to false also disables the run-time stack.

Default: true

LaunchReport

Specify whether to automatically display HTML reports after code generation is complete
or an error occurs.

Default: true

MATLABSourceComments

Include MATLAB source code as comments in the generated code.

Dependencies:

• GenerateComments enables this parameter.

3-104
coder.MexCodeConfig class

Default: false

MemcpyThreshold

Specify the minimum number of bytes for the code generation software to invoke the
memcpy optimization or the memset optimization. To optimize generated code that copies
consecutive array elements, the code generation software tries to replace the code with
a memcpy call. To optimize generated code that assigns a literal constant to consecutive
array elements, the code generation software tries to replace the code with a memset call.
A memcpy or memset call can be more efficient than code, such as a for-loop or multiple,
consecutive element assignments.

The number of bytes is the number of array elements to copy or assign multiplied by the
number of bytes required for the C/C++ data type.

See “memcpy Optimization” and “memset Optimization”.

Default: integer, 64

Name

Name of code generation configuration object.

Default: string, 'MexCodeConfig'

PostCodeGenCommand

Specify command to customize build processing after MEX function generation using
codegen.

Default: string, ''

PreserveVariableNames

Specify the variable names that the variable reuse optimization must preserve.

Value Description
UserNames Preserve names that correspond to user-
defined variables in the MATLAB code. For
this option, the variable reuse optimization
does not replace your variable name with
another name and does not use your name

3-105
3 Class Reference

Value Description
for another variable. Use this option for
readability. You can more easily trace the
variables in the generated code back to the
variables in your MATLAB code.

The variable reuse optimization preserves


your variable names, however, other
optimizations can remove them from the
generated code. MATLAB Coder does not
reuse your variables in the generated C/
C++ code, however, the C/C++ compiler
can reuse these variables in the generated
binary code.
None The variable reuse optimization does not
have to preserve any variable names. It
can reuse any variables that meet the
requirements for variable reuse. If your
code uses large data structures or arrays,
in some cases, the extra memory required
to preserve your variable names can affect
performance. In these cases, use this
option to reduce memory usage or improve
execution speed.
All Preserve all variable names. This option
disables variable reuse. Use this option
only for testing or debugging. Do not use
this option for production code.

Default: string, 'UserNames'

ReservedNameArray

Enter a list of names that MATLAB Coder is not to use for naming functions or variables.

Default: string, ''

ResponsivenessChecks

Enable responsiveness checks in code generated for MATLAB functions.

3-106
coder.MexCodeConfig class

These checks enable periodic checks for Ctrl+C breaks in the generated code. Enabling
responsiveness checks also enables graphics refreshing.

Caution These checks are enabled by default for safety. Without these checks, the only
way to end a long-running execution might be to terminate MATLAB.

Default: true

SaturateOnIntegerOverflow

Overflows saturate to either the minimum or maximum value that the data type can
represent. Otherwise, the overflow behavior depends on your target C compiler. Most C
compilers wrap on overflow.

This parameter applies only to MATLAB built-in integer types. It does not apply to
doubles, singles, or fixed-point data types.

Default: true

StackUsageMax

Specify the maximum stack usage per application in bytes. Set a limit that is lower than
the available stack size. Otherwise, a runtime stack overflow might occur. Overflows are
detected and reported by the C compiler, not by codegen.

Default: integer, 200000

TargetLang

Specify the target language. Set to 'C' to generate C code. Set to C++ to generate C++
code. If you specify C++, MATLAB Coder wraps the C code into .cpp files so that you can
use a C++ compiler and interface with external C++ applications. It does not generate C+
+ classes.

Default: string, 'C'

Copy Semantics
Handle. To learn how handle classes affect copy operations, see Copying Objects in the
MATLAB documentation.

3-107
3 Class Reference

Examples
Generate a MEX function from a MATLAB function that is suitable for code generation
and enable a code generation report.

1 Write a MATLAB function, coderand, that generates a random scalar value from
the standard uniform distribution on the open interval (0,1).
function r = coderand() %#codegen
% The directive %#codegen declares that the function
% is intended for code generation
r = rand();
2 Create a code generation configuration object to generate a MEX function.
cfg = coder.config('mex')
3 Enable the code generation report.
cfg.GenerateReport = true;
4 Generate a MEX function in the current folder specifying the configuration object
using the -config option.

% Generate a MEX function and code generation report


codegen -config cfg coderand

Alternatives
Use the coder function to create a MATLAB Coder project. The project provides a
user interface that facilitates adding MATLAB files, defining input parameters, and
specifying build parameters.

See Also
codegen | coder | | coder.extrinsic

3-108
coder.PrimitiveType class

coder.PrimitiveType class
Package: coder
Superclasses: coder.ArrayType

Represent set of logical, numeric, or char arrays

Description
Specifies the set of logical, numeric, or char values that
the generated code should accept. Supported classes are
double,single,int8,uint8,int16,uint16,int32,uint32,int64,uint64, char,
and logical. Use only with the codegen -args option. Do not pass as an input to a
generated MEX function.

Construction
t=coder.typeof(v) creates a coder.PrimitiveType object denoting the smallest
non-constant type that contains v. v must be a MATLAB numeric, logical or char.

t=coder.typeof(v, sz, variable_dims) returns a modified copy of


coder.typeof(v) with (upper bound) size specified by sz and variable dimensions
variable_dims. If sz specifies inf for a dimension, then the size of the dimension
is assumed to be unbounded and the dimension is assumed to be variable sized. When
sz is [], the (upper bound) sizes of v remain unchanged. When variable_dims is not
specified, the dimensions of the type are assumed to be fixed except for those that are
unbounded. When variable_dims is a scalar, it is applied to bounded dimensions that
are not 1 or 0 (which are assumed to be fixed).

t=coder.newtype(numeric_class, sz, variable_dims) creates a


coder.PrimitiveType object representing values of class numeric_class with
(upper bound) sizes sz and variable dimensions variable_dims. If sz specifies inf
for a dimension, then the size of the dimension is assumed to be unbounded and the
dimension is assumed to be variable sized. When variable_dims is not specified, the
dimensions of the type are assumed to be fixed except for those that are unbounded.
When variable_dims is a scalar, it is applied to the dimensions of the type that are not
1 or 0 (which are assumed to be fixed).

3-109
3 Class Reference

t=coder.newtype(numeric_class, sz, variable_dims, Name, Value) creates


a coder.PrimitiveType object with additional options specified by one or more Name,
Value pair arguments. Name can also be a property name and Value is the corresponding
value. Name must appear inside single quotes (''). You can specify several name-value
pair arguments in any order as Name1,Value1,…,NameN,ValueN.

Input Arguments
v

Input that is not a coder.Type object

sz

Size for corresponding dimension of type object. Size must be a valid size vector.

Default: [1 1] for coder.newtype

variable_dims

Logical vector that specifies whether each dimension is variable size (true) or fixed size
(false).

Default: false(size(sz)) | sz==Inf for coder.newtype

numeric_class

Class of type object.

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the


argument name and Value is the corresponding value. Name must appear inside single
quotes (' '). You can specify several name and value pair arguments in any order as
Name1,Value1,...,NameN,ValueN.

'complex'

Set complex to true to create a coder.PrimitiveType object that can represent


complex values. The type must support complex data.

Default: false

3-110
coder.PrimitiveType class

'sparse'

Set sparse to true to create a coder.PrimitiveType object representing sparse data.


The type must support sparse data.

Default: false

Properties
ClassName

Class of values in this set

Complex

Indicates whether the values in this set are real (false) or complex (true)

SizeVector

The upper-bound size of arrays in this set.

Sparse

Indicates whether the values in this set are sparse arrays (true)

VariableDims

A vector used to specify whether each dimension of the array is fixed or variable size. If a
vector element is true, the corresponding dimension is variable size.

Copy Semantics
Value. To learn how value classes affect copy operations, see Copying Objects in the
MATLAB documentation.

Examples
Create a coder.PrimitiveType object.

3-111
3 Class Reference

z = coder.typeof(0,[2 3 4],[1 1 0]) % returns double :2x:3x4


% ':' indicates variable-size dimensions

Create a coder.PrimitiveType object then call codegen to generate a C library for a


function fcn.m that has one input parameter of this type.

1 Create a coder.PrimitiveType object.

z = coder.typeof(0,[2 3 4],[1 1 0]) % returns double :2x:3x4


% ':' indicates variable-size dimensions
2 Call codegen to generate a C library for a MATLAB function fcn.m that has one
input parameter type z.

% Use the config:lib option to generate a C library


codegen -config:lib fcn -args {z}

See Also
coder.ArrayType | coder.typeof | coder.Type | coder.newtype | coder.resize |
codegen

Introduced in R2011a

3-112
coder.StructType class

coder.StructType class
Package: coder
Superclasses: coder.ArrayType

Represent set of MATLAB structure arrays

Description
Specifies the set of structure arrays that the generated code should accept. Use only with
the codegen -args option. Do not pass as an input to a generated MEX function.

Construction
t=coder.typeof(struct_v) creates a coder.StructType object for a structure with
the same fields as the scalar structure struct_v.

t=coder.typeof(struct_v, sz, variable_dims) returns a modified copy of


coder.typeof(struct_v) with (upper bound) size specified by sz and variable
dimensions variable_dims. If sz specifies inf for a dimension, then the size of the
dimension is assumed to be unbounded and the dimension is assumed to be variable
sized. When sz is [], the (upper bound) sizes of struct_v remain unchanged. If the
variable_dims input parameter is not specified, the dimensions of the type are
assumed to be fixed except for those that are unbounded. When variable_dims is a
scalar, it is applied to the bounded dimensions that are not 1 or 0 (which are assumed to
be fixed).

t=coder.newtype('struct', struct_v, sz, variable_dims) creates a


coder.StructType object for an array of structures with the same fields as the
scalar structure struct_v and (upper bound) size sz and variable dimensions
variable_dims. If sz specifies inf for a dimension, then the size of the dimension
is assumed to be unbounded and the dimension is assumed to be variable sized. When
variable_dims is not specified, the dimensions of the type are assumed to be fixed
except for those that are unbounded. When variable_dims is a scalar, it is applied
to the dimensions of the type, except if the dimension is 1 or 0, which is assumed to be
fixed.

3-113
3 Class Reference

Input Arguments
struct_v

Scalar structure used to specify the fields in a new structure type.

sz

Size vector specifying each dimension of type object.

Default: [1 1] for coder.newtype

variable_dims

Logical vector that specifies whether each dimension is variable size (true) or fixed size
(false).

Default: false(size(sz)) | sz==Inf for coder.newtype

Properties
Alignment

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. This capability allows you to take advantage of target-specific function
implementations that require data to be aligned. By default, the structure is not aligned
on a specific boundary so it will not be matched by CRL functions that require alignment.

Alignment must be either -1 or a power of 2 that is no more than 128.

ClassName

Class of values in this set.

Extern

Whether the structure type is externally defined.

Fields

A structure giving the coder.Type of each field in the structure.

3-114
coder.StructType class

HeaderFile

If the structure type is externally defined, 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 codegen -I option or the Additional include directories parameter in
the MATLAB Coder 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. By specifying the HeaderFile option, MATLAB Coder
includes that header file exactly at the point where it is required.

Must be a non-empty string.

SizeVector

The upper-bound size of arrays in this set.

VariableDims

A vector used to specify whether each dimension of the array is fixed or variable size. If a
vector element is true, the corresponding dimension is variable size.

Copy Semantics
Value. To learn how value classes affect copy operations, see Copying Objects in the
MATLAB documentation.

Examples
Create a type for a structure with a variable-size field.
x.a = coder.typeof(0,[3 5],1);
x.b = magic(3);
coder.typeof(x)
% Returns
% coder.StructType
% 1x1 struct
% a: :3x:5 double
% b: 3x3 double

3-115
3 Class Reference

% ':' indicates variable-size dimensions

Create a coder.StructType object then call codegen to generate a C library for a


function fcn.m that has one input parameter of this type

1 Create a new structure type.

ta = coder.newtype('int8',[1 1]);
tb = coder.newtype('double',[1 2],[1 1]);
z = coder.newtype('struct',struct('a',ta,'b',tb))
% Returns
% coder.StructType
% 1x1 struct
% a: 1x1 int8
% b: :1x:2 double
2 Call codegen to generate a C library for a MATLAB function fcn.m that has one
input parameter of this type.

% Use the -config:lib option to generate a C library


codegen -config:lib fcn -args {z}

Create a coder.StructType object that uses an externally-defined structure type.

1 Create a type that uses an externally-defined structure type.

S.a = coder.typeof(double(0));
S.b = coder.typeof(single(0));
T = coder.typeof(S);
T = coder.cstructname(T,'mytype','extern','HeaderFile','myheader.h');

T =

coder.StructType
1x1 extern mytype (myheader.h) struct
a: 1x1 double
b: 1x1 single
2 View the types of the structure fields.

T.Fields

ans =

a: [1x1 coder.PrimitiveType]
b: [1x1 coder.PrimitiveType]

3-116
coder.StructType class

See Also
coder.EnumType | coder.FiType | coder.Constant | coder.ArrayType | coder.typeof |
coder | coder.cstructname | coder.Type | coder.PrimitiveType | coder.newtype |
coder.resize | codegen

Introduced in R2011a

3-117
3 Class Reference

coder.SingleConfig class
Package: coder

Double-precision to single-precision conversion configuration object

Description
A coder.SingleConfig object contains the configuration parameters that the
MATLAB Coder codegen function requires to convert double-precision code to single-
precision MATLAB code. To pass this object to the codegen function, use the -
double2single option.

Construction
scfg = coder.config('single') creates a coder.SingleConfig object for double-
precision to single-precision conversion.

Properties
OutputFileNameSuffix — Suffix for single-precision file name
'_single' (default) | string

Suffix that the single-conversion process uses for generated single-precision files.

LogIOForComparisonPlotting — Enable simulation data logging for comparison plotting


of input and output variables
false (default) | true

Enable simulation data logging to plot the data differences introduced by single-precision
conversion.

PlotFunction — Name of function for comparison plots


'' (default) | string

Name of function to use for comparison plots.

3-118
coder.SingleConfig class

To enable comparison plotting, set LogIOForComparisonPlotting to true. This option


takes precedence over PlotWithSimulationDataInspector.

The plot function must accept three inputs:

• A structure that holds the name of the variable and the function that uses it.
• A cell array to hold the logged floating-point values for the variable.
• A cell array to hold the logged values for the variable after fixed-point conversion.

PlotWithSimulationDataInspector — Specify use of Simulation Data Inspector for


comparison plots
false (default) | true

Use Simulation Data Inspector for comparison plots.

LogIOForComparisonPlotting must be set to true to enable comparison plotting. The


PlotFunction option takes precedence over PlotWithSimulationDataInspector.

TestBenchName — Name of test file


'' (default) | string | cell array of strings

Test file name or names, specified as a string or cell array of strings. Specify at least one
test file.

If you do not explicitly specify input parameter data types, the conversion uses the first
file to infer these data types.

TestNumerics — Enable numerics testing


false (default) | true

Enable numerics testing to verify the generated single-precision code. The test file runs
the single-precision code.

Methods

Examples
Generate Single-Precision MATLAB Code

Create a coder.SingleConfig object.

3-119
3 Class Reference

scfg= coder.config('single');

Set the properties of the doubles-to-singles configuration object. Specify the test file. In
this example, the name of the test file is myfunction_test. The conversion process uses
the test file to infer input data types and collect simulation range data. Enable numerics
testing and generation of comparison plots.
scfg.TestBenchName = 'myfunction_test';
scfg.TestNumerics = true;
scfg.LogIOForComparisonPlotting = true;

Run codegen. Use the -double2single option to specify the coder.SingleConfig


that you want to use. In this example, the MATLAB function name is myfunction.

codegen -double2single scfg myfunction

• “Generate Single-Precision MATLAB Code”


• “Generate Single-Precision C Code at the Command Line”

Alternatives
You can convert double-precision MATLAB code to single-precision C/C++ code by using
the 'singleC' option of the codegen function.

You can convert double-precision MATLAB code to single-precision code using the
MATLAB Coder app. Open the app using one of these methods:

• On the Apps tab, in the Code Generation section, click MATLAB Coder.
• Use the coder command.

See Also
codegen | coder.config

Introduced in R2015b

3-120
coder.Type class

coder.Type class
Package: coder

Represent set of MATLAB values

Description
Specifies the set of values that the generated code should accept. Use only with the
codegen -args option. Do not pass as an input to a generated MEX function.

Construction
coder.Type is an abstract class, and you cannot create instances of it directly. You can
create coder.Constant, coder.EnumType, coder.FiType, coder.PrimitiveType,
coder.StructType, and coder.CellType objects that are derived from this class.

Properties
ClassName

Class of values in this set

Copy Semantics
Value. To learn how value classes affect copy operations, see Copying Objects in the
MATLAB documentation.

See Also
coder.EnumType | coder.FiType | coder.Constant | coder.ArrayType | coder.typeof |
coder | coder.CellType | coder.StructType | coder.PrimitiveType | coder.newtype |
coder.resize | codegen

Introduced in R2011a

3-121
3 Class Reference

coder.make.BuildConfiguration class
Package: coder.make

Represent build configuration

Description
A build configuration contains information on how to build source code and binaries.

Give each build configuration a unique name that you can use to reference or access it,
such as ‘Faster Builds’.

A build configuration contains options with values. Each option maps to a build tool in
the ToolchainInfo object that uses the build configuration.

For example, a build configuration can contain options for the following build tools in
coder.make.ToolchainInfo:

• C Compiler
• C++ Compiler’
• Linker
• Shared Library Linker
• Archiver
• Download
• Execute

The value of each option can vary from one build configuration to another. For
example, the “Faster Runs” build configuration can have compiler options that include
optimization flags, while the “Debug” build configuration can have compiler options that
include a symbolic debug flag.

Construction
ConfigObj = coder.make.BuildConfiguration(ConfigName,{Name,
Value,...})

3-122
coder.make.BuildConfiguration class

Input Arguments
ConfigName — Name of build configuration
string

Name of build configuration, specified as a string.


Example: 'Faster Builds II'
Data Types: char

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the


argument name and Value is the corresponding value. Name must appear inside single
quotes (' '). You can specify several name and value pair arguments in any order as
Name1,Value1,...,NameN,ValueN.

'Name' — Name of option


string

Name of option, specified as a string.


Data Types: char

'Value' — Value of option


string

Value of option, specified as a string.


Data Types: char

Output Arguments
ConfigObj — Object handle for configuration
variable

Object handle for configuration, returned as a variable.


Data Types: char

3-123
3 Class Reference

Properties
Description — Brief description of build configuration

A brief description of the build configuration. The MATLAB Coder software displays
this description in the project build settings, on the Hardware tab, below the Build
Configuration parameter.

You can assign a description to this property after you create the BuildConfiguration
object.

config.Description = 'BldConfigDescription'
config =

##############################################
# Build Configuration : BldConfigName
# Description : BldConfigDescription
##############################################

Data type: char

Attributes:

GetAccess public
SetAccess public

Name — Name of build configuration

The name of the build configuration.

You can assign a name to this property when you create a BuildConfiguration object.
config = coder.make.BuildConfiguration ...
('BldConfigName',{'optiona','1','optionb','2','optionc','3'})

You can also assign a name to this property after you create a BuildConfiguration
object.

config.Name = 'BldConfigName'

Both approaches produce the same result

config =

3-124
coder.make.BuildConfiguration class

##############################################
# Build Configuration : BldConfigName
# Description :
##############################################

Data type: char

Attributes:

GetAccess public
SetAccess public

Options — List of options or settings for specific build configuration

A list of options or settings for a specific build configuration. This list contains name-
value pairs. The Options property has an option for each coder.make.BuildTool
object in coder.make.Toolchain.BuildTools. For example, Options has a C
Compiler option for the C Compiler build tool.

Data type: coder.make.UnorderedList

Attributes:

GetAccess public
SetAccess public

Methods

Copy Semantics
Handle. To learn how handle classes affect copy operations, see Copying Objects in the
MATLAB documentation.

See Also
coder.make.BuildItem | coder.make.BuildTool | coder.make.ToolchainInfo
| coder.make.ToolchainInfo.getBuildConfiguration |
coder.make.ToolchainInfo.removeBuildConfiguration

3-125
3 Class Reference

| coder.make.ToolchainInfo.setBuildConfiguration |
coder.make.ToolchainInfo.setBuildConfigurationOption

Related Examples
• “Adding a Custom Toolchain”
• “Toolchain Definition File with Commentary”

3-126
coder.make.BuildItem class

coder.make.BuildItem class
Package: coder.make

Represent build item

Description
Create a coder.make.BuildItem object that can have macro name and
value. Then, use the BuildItem object as an argument for one of the following
coder.make.BuildTool methods:

• coder.make.BuildTool.getCommand
• coder.make.BuildTool.setCommand
• coder.make.BuildTool.setPath
• coder.make.BuildTool.addFileExtension

Note: What is a macro? The term has a different meaning depending on the context:

• In this context, a macro is a variable that the makefile can use to refer to a given
value, such as a build tool’s command, path, or file extension.
• In topics for the coder.make.ToolchainInfo.Macros and related methods, a
macro is a variable that the makefile can use to refer to arbitrary or predefined value.

Construction
h = coder.make.BuildItem(blditm_macrovalue) creates a
coder.make.BuildItem object that has a value.

h = coder.make.BuildItem(blditm_macroname,blditm_value) creates a
coder.make.BuildItem object that has a macro name and value.

Input Arguments
blditm_macroname — Macro name of build item
string

3-127
3 Class Reference

Macro name of build item, specified as a string.


Data Types: char

blditm_value — Value of build item


string

Value of build item


Data Types: char

Output Arguments
buildItemHandle — BuildItem handle
object handle

BuildItem handle, specified as a coder.make.BuildItem object that contains an option


value.
Example: bi

Methods

Copy Semantics
Handle. To learn how handle classes affect copy operations, see Copying Objects in the
MATLAB documentation.

Example
bi1 = coder.make.BuildItem('BuildItemMacroValue')

bi1 =

Macro : (empty)
Value : BuildItemMacroValue

bi2 = coder.make.BuildItem('BIMV','BuildItemMacroValue')

3-128
coder.make.BuildItem class

bi2 =

Macro : BIMV
Value : BuildItemMacroValue

See Also
coder.make.ToolchainInfo | coder.make.BuildTool |
coder.make.ToolchainInfo | coder.make.BuildTool.getCommand |
coder.make.BuildTool.setCommand | coder.make.BuildTool.setPath |
coder.make.BuildTool.addFileExtension

Related Examples
• “Adding a Custom Toolchain”

3-129
3 Class Reference

coder.make.BuildTool class
Package: coder.make

Represent build tool

Description
Use coder.make.BuildTool to get and define an existing default
coder.make.BuildTool object, or to create a new coder.make.BuildTool object.

In most cases, get and define one of the default BuildTool objects from the following
ToolchainInfo properties:

• coder.make.ToolchainInfo.BuildTools
• coder.make.ToolchainInfo.PostbuildTools

The “get and define” approach is shown in:

• “Toolchain Definition File with Commentary”


• Tutorial example: “Adding a Custom Toolchain” tutorial

The alternative “create a new” approach is shown in “Create a New BuildTool” on page
3-135.

The following illustration shows the relationship between the default BuildTool objects
and ToolchainInfo.

3-130
coder.make.BuildTool class

3-131
3 Class Reference

Construction
h = coder.make.BuildTool(bldtl_name) creates a coder.make.BuildTool object
and sets its Name property.

Input Arguments
bldtl_name — Build tool name
string

Build tool name, specified as a string.


Data Types: char

Output Arguments
h — Object handle
variable

Object handle for a coder.make.BuildTool object, specified as a variable.


Example: tool

Properties
Command — Build tool command or command macro

Represents the build tool command using:

• An optional macro name, such as: CC.


• The system call (command) that starts the build tool, such as: gcc.

The macro name and system call appear together in the generated makefile. For
example: CC = gcc

Assigning a value to this property is optional.

You can use the following methods with Command:

• coder.make.BuildTool.getCommand
• coder.make.BuildTool.setCommand

3-132
coder.make.BuildTool class

Attributes:

GetAccess public
SetAccess public

Directives — Tool-specific directives

Defines any tool-specific directives, such as -D for preprocessor defines. Assigning a value
to this property is optional.

You can use the following methods with Directives:

• coder.make.BuildTool.addDirective
• coder.make.BuildTool.getDirective
• coder.make.BuildTool.setDirective

Attributes:

GetAccess public
SetAccess public

FileExtensions — Tool-specific file extensions

Defines any tool-specific file extensions. This value is optional.

You can use the following methods with FileExtensions:

• coder.make.BuildTool.addFileExtension
• coder.make.BuildTool.getFileExtension
• coder.make.BuildTool.setFileExtension

Attributes:

GetAccess public
SetAccess public

Name — Name of build tool

Defines the name of the build tool.

You can use the following methods with Name.

3-133
3 Class Reference

• coder.make.BuildTool.getName
• coder.make.BuildTool.setName

Attributes:

GetAccess public
SetAccess public

Path — Tool-specific paths

Defines any tool-specific paths. If the command is on the system path, this value is
optional.

You can use the following methods with Path:

• coder.make.BuildTool.getPath
• coder.make.BuildTool.setPath

Attributes:

GetAccess public
SetAccess public

Methods

Copy Semantics
Handle. To learn how handle classes affect copy operations, see Copying Objects in the
MATLAB documentation.

Example
Get a default build tool and set its properties
The intel_tc.m file from “Adding a Custom Toolchain”, uses the following lines to get a
default build tool, C Compiler, from a ToolchainInfo object called tc, and then sets
its properties.

3-134
coder.make.BuildTool class

% ------------------------------
% C Compiler
% ------------------------------

tool = tc.getBuildTool('C Compiler');

tool.setName('Intel C Compiler');
tool.setCommand('icl');
tool.setPath('');

tool.setDirective('IncludeSearchPath','-I');
tool.setDirective('PreprocessorDefine','-D');
tool.setDirective('OutputFlag','-Fo');
tool.setDirective('Debug','-Zi');

tool.setFileExtension('Source','.c');
tool.setFileExtension('Header','.h');
tool.setFileExtension('Object','.obj');

tool.setCommandPattern('|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<||>OUTPUT<|');

The following examples show the same “get and define” approach in more detail:

• “Toolchain Definition File with Commentary”


• Tutorial example: “Adding a Custom Toolchain” tutorial

Create a New BuildTool


To create a new build tool:

1 Create a file that defines a BuildTool object, such as createBuildTool_1.m or


createBuildTool_2.
2 Create a file like addBuildToolToToolchainInfo.m, that:

• Creates a ToolchainInfo object, or uses an existing one.


• Creates a BuildTool object from createBuildTool_1.m or
createBuildTool_2.
• Adds the BuildTool object to the ToolchainInfo object.
3 Run addBuildToolToToolchainInfo.m.

Refer to the following examples of addBuildToolToToolchainInfo.m,


createBuildTool_1.m, and createBuildTool_2.

addBuildToolToToolchainInfo.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Adding a build tool to ToolchainInfo
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

3-135
3 Class Reference

% Create a toolchain object


h = coder.make.ToolchainInfo();

% User function for creating and populating a build tool


tool = createBuildTool_1();
% or tool = createBuildTool_2();

% Add the build tool to ToolchainInfo


h.addBuildTool('My C Compiler',tool);

createBuildTool_1.m
function buildToolObj = createBuildTool_1()

toolinfo.Name = 'My GNU C Compiler';


toolinfo.Language = 'C';

toolinfo.Command.Macro = 'CC';
toolinfo.Command.Value = 'gcc';

toolinfo.Path.Macro = 'CC_PATH';
toolinfo.Path.Value = '';

toolinfo.OptionsRegistry = {'My C Compiler','MY_CFLAGS'};

% Key name of this directive


toolinfo.Directives(1).Key = 'IncludeSearchPath';

% Macro of this directive (directives can have empty macros)


toolinfo.Directives(1).Macro = '';

% Value of this directive


toolinfo.Directives(1).Value = '-I';

toolinfo.Directives(2).Key = 'PreprocessorDefine';
toolinfo.Directives(2).Macro = '';
toolinfo.Directives(2).Value = '-D';

toolinfo.Directives(3).Key = 'Debug';
toolinfo.Directives(3).Macro = 'CDEBUG';
toolinfo.Directives(3).Value = '-g';

toolinfo.Directives(4).Key = 'OutputFlag';
toolinfo.Directives(4).Macro = 'C_OUTPUT_FLAG';
toolinfo.Directives(4).Value = '-o';

% Key name of this file extension


toolinfo.FileExtensions(1).Key = 'Source';

% Macro of this file extension


toolinfo.FileExtensions(1).Macro = 'C_EXT';

% Value of this file extension


toolinfo.FileExtensions(1).Value = '.c';

toolinfo.FileExtensions(2).Key = 'Header';
toolinfo.FileExtensions(2).Macro = 'H_EXT';

3-136
coder.make.BuildTool class

toolinfo.FileExtensions(2).Value = '.h';

toolinfo.FileExtensions(3).Key = 'Object';
toolinfo.FileExtensions(3).Macro = 'OBJ_EXT';
toolinfo.FileExtensions(3).Value = '.obj';

toolinfo.DerivedFileExtensions = {'$(OBJ_EXT)'};
% '*' means all outputs are supported
toolinfo.SupportedOutputs = {'*'};

% put actual extension (e.g. '.c') or keyname if already registered


% under 'FileExtensions'
toolinfo.InputFileExtensions = {'Source'};
toolinfo.OutputFileExtensions = {'Object'};

% Create a build tool object and populate it with the above data
buildToolObj = createAndpopulateBuildTool(toolinfo);

function buildToolObj = createAndpopulateBuildTool(toolinfo)

% -------------------------
% Construct a BuildTool
% -------------------------
buildToolObj = coder.make.BuildTool();

% -------------------------
% Set general properties
% -------------------------
buildToolObj.Name = toolinfo.Name;
buildToolObj.Language = toolinfo.Language;
buildToolObj.Command = coder.make.BuildItem ...
(toolinfo.Command.Macro,toolinfo.Command.Value);
buildToolObj.Path = coder.make.BuildItem ...
(toolinfo.Path.Macro,toolinfo.Path.Value);
buildToolObj.OptionsRegistry = toolinfo.OptionsRegistry;
buildToolObj.SupportedOutputs = toolinfo.SupportedOutputs;

% -------------------------
% Directives
% -------------------------
for i = 1:numel(toolinfo.Directives)
directiveBuildItem = coder.make.BuildItem(...
toolinfo.Directives(i).Macro,toolinfo.Directives(i).Value);
buildToolObj.addDirective(toolinfo.Directives(i).Key,directiveBuildItem);
end

% -------------------------
% File extensions
% -------------------------
for i = 1:numel(toolinfo.FileExtensions)
fileExtBuildItem = coder.make.BuildItem(...
toolinfo.FileExtensions(i).Macro,toolinfo.FileExtensions(i).Value);
buildToolObj.addFileExtension(toolinfo.FileExtensions(i).Key,fileExtBuildItem);
end

% -------------------------
% Derived file extensions
% -------------------------
for i = 1:numel(toolinfo.DerivedFileExtensions)
if buildToolObj.FileExtensions.isKey(toolinfo.DerivedFileExtensions{i})
buildToolObj.DerivedFileExtensions{end+1} = ...

3-137
3 Class Reference

['$(' buildToolObj.getFileExtension
(toolinfo.DerivedFileExtensions{i}) ')'];
else
buildToolObj.DerivedFileExtensions{end+1} = toolinfo.DerivedFileExtensions{i};
end
end

% -------------------------
% Command pattern
% -------------------------
if isfield(toolinfo,'CommandPattern')
buildToolObj.CommandPattern = toolinfo.CommandPattern;
end

% --------------------------------
% [Input/Output]FileExtensions
% --------------------------------
if isfield(toolinfo,'InputFileExtensions')
buildToolObj.InputFileExtensions = toolinfo.InputFileExtensions;
end
if isfield(toolinfo,'OutputFileExtensions')
buildToolObj.OutputFileExtensions = toolinfo.OutputFileExtensions;
end

createBuildTool_2.m
function buildToolObj = createBuildTool_2()

% -------------------------
% Construct a BuildTool
% -------------------------
buildToolObj = coder.make.BuildTool();

% -------------------------
% Set general properties
% -------------------------
buildToolObj.Name = 'My GNU C Compiler';
buildToolObj.Language = 'C';
buildToolObj.Command = coder.make.BuildItem('CC','gcc');
buildToolObj.Path = coder.make.BuildItem('CC_PATH','');
buildToolObj.OptionsRegistry = {'My C Compiler','MY_CFLAGS'};
buildToolObj.SupportedOutputs = {'*'}; % '*' means all outputs are supported

% -------------------------
% Directives
% -------------------------

directiveBuildItem = coder.make.BuildItem('','-I');
buildToolObj.addDirective('IncludeSearchPath',directiveBuildItem);

directiveBuildItem = coder.make.BuildItem('','-D');
buildToolObj.addDirective('PreprocessorDefine',directiveBuildItem);

directiveBuildItem = coder.make.BuildItem('CDEBUG','-g');
buildToolObj.addDirective('Debug',directiveBuildItem);

directiveBuildItem = coder.make.BuildItem('C_OUTPUT_FLAG','-o');
buildToolObj.addDirective('OutputFlag',directiveBuildItem);

% -------------------------
% File Extensions
% -------------------------

3-138
coder.make.BuildTool class

fileExtBuildItem = coder.make.BuildItem('C_EXT','.c');
buildToolObj.addFileExtension('Source',fileExtBuildItem);

fileExtBuildItem = coder.make.BuildItem('H_EXT','.h');
buildToolObj.addFileExtension('Header',fileExtBuildItem);

fileExtBuildItem = coder.make.BuildItem('OBJ_EXT','.obj');
buildToolObj.addFileExtension('Object',fileExtBuildItem);

% -------------------------
% Others
% -------------------------

buildToolObj.DerivedFileExtensions = {'$(OBJ_EXT)'};
buildToolObj.InputFileExtensions = {'Source'};
% put actual extension (e.g. '.c')
% or keyname if already registered under 'FileExtensions'
buildToolObj.OutputFileExtensions = {'Object'};
% put actual extension (e.g. '.c')
% or keyname if already registered under 'FileExtensions'

See Also
coder.make.ToolchainInfo | “Toolchain Definition File with Commentary”
| coder.make.BuildTool | coder.make.ToolchainInfo.addBuildTool
| coder.make.ToolchainInfo.getBuildTool |
coder.make.ToolchainInfo.removeBuildTool |
coder.make.ToolchainInfo.setBuildTool

Related Examples
• “Adding a Custom Toolchain”

3-139
3 Class Reference

coder.make.ToolchainInfo class
Package: coder.make

Represent custom toolchain

Description
Use coder.make.ToolchainInfo to define and register a new set of software build
tools (toolchain) with MathWorks code generation products.

A coder.make.ToolchainInfo object contains:

• coder.make.BuildTool objects that can describe each build tool


• coder.make.BuildConfiguration objects that can apply sets of options to the
build tools

3-140
coder.make.ToolchainInfo class

3-141
3 Class Reference

Construction
h = coder.make.ToolchainInfo creates a default ToolchainInfo object and assigns it
to a handle, h.

The default ToolchainInfo object includes BuildTool objects and configurations for C,
C++, and gmake:

• The default value of SupportedLanguages, C/C++, adds BuildTool and


BuildConfiguration objects for C and C++ compilers to ToolchainInfo.
• The default value of BuildArtifact, gmake, adds a BuildTool object for gmake to
ToolchainInfo.BuilderApplication.

You can use the following arguments to override these defaults when you create the
ToolchainInfo object, not afterwards.

h = coder.make.ToolchainInfo(SupportedLanguages,value1,
BuildArtifact,value2) overrides the SupportedLanguages or BuildArtifact
defaults.

Each property is optional. Each property requires a corresponding value.

Input Arguments
SupportedLanguages

The property name. For more information, see SupportedLanguages.

value1 — Supported language or languages


C/C++ (default) | C | C++ | Asm/C | Asm/C/C++ | Asm/C++

Supported language or languages, specified as a scalar.

BuildArtifact — Name of BuildArtifact property

The property name. For more information, see BuildArtifact.

value2 — Value of BuildArtifact property


gmake (default) | gmake makefile | nmake | nmake makefile

Values for the BuildArtifact property, specified as a scalar.

3-142
coder.make.ToolchainInfo class

Output Arguments
h — ToolchainInfo object handle

A coder.make.ToolchainInfo object, specified using an object handle, such as h. To create


h, enter h = coder.make.ToolchainInfo in a MATLAB Command Window.

Properties
Attributes — Custom attributes of toolchain

Custom attributes of the toolchain

Add custom attributes required by the toolchain and specify their default values.

By default, the list of custom attributes is empty.

Attributes returns a coder.make.util.UnorderedList.

For example, the intel_tc.m file from “Adding a Custom Toolchain”, defines the
following custom attributes:

tc.addAttribute('TransformPathsWithSpaces');
tc.addAttribute('RequiresCommandFile');
tc.addAttribute('RequiresBatchFile');

To display the Attributes list from that example in a MATLAB Command Window,
enter:

h = intel_tc;
h.Attributes

ans =

# -------------------
# "Attributes" List
# -------------------
RequiresBatchFile = true
RequiresCommandFile = true

3-143
3 Class Reference

TransformPathsWithSpaces = true

Use the following methods with Attributes:

• coder.make.ToolchainInfo.addAttribute
• coder.make.ToolchainInfo.getAttribute
• coder.make.ToolchainInfo.getAttributes
• coder.make.ToolchainInfo.isAttribute
• coder.make.ToolchainInfo.removeAttribute

Attributes:

GetAccess public
SetAccess public

BuildArtifact — Type of makefile or build artifact

The type of makefile (build artifact) MATLAB Coder uses during the software build
process.

Initialize this property when you create coder.make.ToolchainInfo. Use the


default value, gmake makefile, or override the default value using a name-value pair
argument, as described in “Construction” on page 3-142.

For example:

h = coder.make.ToolchainInfo('BuildArtifact','nmake');
The values can be:

• 'gmake' or 'gmake makefile' — The GNU make utility


• 'nmake' or 'nmake makefile' — The Windows make utility

For example, to display the value of BuildArtifact in a MATLAB Command Window,


enter:

h = coder.make.ToolchainInfo;
h.BuildArtifact

ans =

3-144
coder.make.ToolchainInfo class

gmake makefile

ToolchainInfo uses the value of the BuildArtifact property to create a BuildTool


object for the build artifact in coder.make.ToolchainInfo.BuilderApplication.

The intel_tc.m file from the “Adding a Custom Toolchain”example uses the following
line to set the value of BuildArtifact:
tc = coder.make.ToolchainInfo('BuildArtifact','nmake makefile');

There are no methods to use with BuildArtifact.

Attributes:

GetAccess public
SetAccess protected

BuildConfigurations — List of build configurations

List of build configurations

Each entry in this list is a coder.make.BuildConfiguration object.

For example, the intel_tc.m file from “Adding a Custom Toolchain”, uses the following
lines to define the build configurations:
cfg = tc.getBuildConfiguration('Faster Builds');
cfg.setOption('C Compiler',horzcat(cCompilerOpts,optimsOffOpts));
cfg.setOption('C++ Compiler',horzcat(cppCompilerOpts,optimsOffOpts));
cfg.setOption('Linker',linkerOpts);
cfg.setOption('Shared Library Linker',sharedLinkerOpts);
cfg.setOption('Archiver',archiverOpts);

cfg = tc.getBuildConfiguration('Faster Runs');


cfg.setOption('C Compiler',horzcat(cCompilerOpts,optimsOnOpts));
cfg.setOption('C++ Compiler',horzcat(cppCompilerOpts,optimsOnOpts));
cfg.setOption('Linker',linkerOpts);
cfg.setOption('Shared Library Linker',sharedLinkerOpts);
cfg.setOption('Archiver',archiverOpts);

cfg = tc.getBuildConfiguration('Debug');
cfg.setOption('C Compiler',horzcat(cCompilerOpts,optimsOffOpts,debugFlag.CCompiler));
cfg.setOption('C++ Compiler',horzcat(cppCompilerOpts,optimsOffOpts,debugFlag.CppCompiler));
cfg.setOption('Linker',horzcat(linkerOpts,debugFlag.Linker));
cfg.setOption('Shared Library Linker',horzcat(sharedLinkerOpts,debugFlag.Linker));
cfg.setOption('Archiver',horzcat(archiverOpts,debugFlag.Archiver));

tc.setBuildConfigurationOption('all','Download','');
tc.setBuildConfigurationOption('all','Execute','');
tc.setBuildConfigurationOption('all','Make Tool','-f $(MAKEFILE)');

3-145
3 Class Reference

To display the BuildConfigurations list from that example in a MATLAB Command


Window, enter:
h = intel_tc;
h.BuildConfigurations

ans =

# ----------------------------
# "BuildConfigurations" List
# ----------------------------
Debug = <coder.make.BuildConfiguration>
Faster Builds = <coder.make.BuildConfiguration>
Faster Runs = <coder.make.BuildConfiguration>

Use the following methods with BuildConfigurations:

• coder.make.ToolchainInfo.getBuildConfiguration
• coder.make.ToolchainInfo.removeBuildConfiguration
• coder.make.ToolchainInfo.setBuildConfiguration

Attributes:

GetAccess public
SetAccess public

BuildTools — List of build tools in toolchain

The list of build tools in the toolchain.

Each entry in this list is a coder.make.BuildTool object.

When you initialize ToolchainInfo, the SupportedLanguages property


determines which build tools are created in BuildTools. For more information, see
SupportedLanguages or “Construction” on page 3-142.

The BuildTool objects ToolchainInfo can create based on the SupportedLanguages


are:

• Assembler
• C Compiler

3-146
coder.make.ToolchainInfo class

• C++ Compiler
• Linker
• Archiver

For example, the intel_tc.m file from “Adding a Custom Toolchain”, uses the following
lines to get and update one of the BuildTool objects:
% ------------------------------
% C Compiler
% ------------------------------

tool = tc.getBuildTool('C Compiler');

tool.setName('Intel C Compiler');
tool.setCommand('icl');
tool.setPath('');

tool.setDirective('IncludeSearchPath','-I');
tool.setDirective('PreprocessorDefine','-D');
tool.setDirective('OutputFlag','-Fo');
tool.setDirective('Debug','-Zi');

tool.setFileExtension('Source','.c');
tool.setFileExtension('Header','.h');
tool.setFileExtension('Object','.obj');

tool.setCommandPattern('|>TOOL<| |>TOOL_OPTIONS<| |>OUTPUT_FLAG<||>OUTPUT<|');

To display the BuildTools list from that example in a MATLAB Command Window,
enter:
h = intel_tc;
h.BuildTools

ans =

# -------------------
# "BuildTools" List
# -------------------
C Compiler = <coder.make.BuildTool>
C++ Compiler = <coder.make.BuildTool>
Archiver = <coder.make.BuildTool>
Linker = <coder.make.BuildTool>
MEX Tool = <coder.make.BuildTool>

Use the following methods with BuildTools:

• coder.make.ToolchainInfo.addBuildTool

3-147
3 Class Reference

• coder.make.ToolchainInfo.getBuildTool
• coder.make.ToolchainInfo.removeBuildTool
• coder.make.ToolchainInfo.setBuildTool

Attributes:

GetAccess public
SetAccess public

BuilderApplication — Properties of build tool

Properties of the build tool that runs the makefile or build artifact

ToolchainInfo uses the value of the BuildArtifact property to create a BuildTool


object for coder.make.ToolchainInfo.BuilderApplication, as described in
“Construction” on page 3-142.

For example, the intel_tc.m file from “Adding a Custom Toolchain”, uses the following
lines to set the BuildArtifact and update BuilderApplication objects:

h = coder.make.ToolchainInfo('BuildArtifact','nmake');

To display the value of BuilderApplication from that example in a MATLAB


Command Window, enter:
h.BuilderApplication
ans =

##############################################
# Build Tool: NMAKE Utility
##############################################

Language : ''
OptionsRegistry : {'Make Tool','MAKE_FLAGS'}
InputFileExtensions : {}
OutputFileExtensions : {}
DerivedFileExtensions : {}
SupportedOutputs : {'*'}
CommandPattern : '|>TOOL<| |>TOOL_OPTIONS<|'

# ---------
# Command
# ---------
MAKE = nmake
MAKE_PATH =

# ------------
# Directives

3-148
coder.make.ToolchainInfo class

# ------------
Comment = #
DeleteCommand = @del
DisplayCommand = @echo
FileSeparator = \
ImpliedFirstDependency = $<
ImpliedTarget = $@
IncludeFile = !include
LineContinuation = \
MoveCommand = @mv
ReferencePattern = \$\($1\)
RunScriptCommand = @cmd /C

# -----------------
# File Extensions
# -----------------
Makefile = .mk

Use the coder.make.ToolchainInfo.setBuilderApplication method with


BuilderApplication.

Attributes:

GetAccess public
SetAccess public

InlinedCommands — Commands toolchain needs to inline within generated makefile

Commands the toolchain needs to inline within the generated makefile

Specify inlined commands to insert verbatim into the makefile. The default value is
empty.

The datatype is String.

For example, to display and then update the value of the InlinedCommands property,
use the MATLAB Command Window to enter:

h.InlinedCommands

ans =

''

h.InlinedCommands = '!include <ntwin32.mak>';


h.InlinedCommands

3-149
3 Class Reference

!include <ntwin32.mak>

The “Adding a Custom Toolchain” example does not include the InlinedCommands
property.

There are no methods to use with InlinedCommands.

Attributes:

GetAccess public
SetAccess public

MATLABCleanup — MATLAB cleanup commands

MATLAB cleanup commands

Specify MATLAB commands or scripts to perform cleanup routines specific to this


toolchain. Use commands or scripts that can be invoked from the MATLAB Command
Window. The default value is empty.

The datatype is a cell array of strings.

For example, to display and then update the value of the MATLABSetup and
MATLABCleanup properties, use the MATLAB Command Window to enter:
h = coder.make.ToolchainInfo;
h.MATLABSetup;
h.MATLABCleanup;
h.MATLABSetup{1} = sprintf('if ispc \n origTMP=getenv(''TMP''); \n setenv(''TMP'',''C:\\TEMP'');\nend');
h.MATLABCleanup{1} = sprintf('if ispc \n setenv(''TMP'',origTMP); \nend');

The following list illustrates where this property fits in the sequence of operations :

1 MATLAB Setup
2 Shell Setup
3 Prebuild
4 Build (assembler, compilers, linker, archiver)
5 Postbuild

a Download
b Execute
6 Shell Cleanup

3-150
coder.make.ToolchainInfo class

7 MATLAB Cleanup

The “Adding a Custom Toolchain” example does not include the MATLABCleanup
property.

There are no methods to use with MATLABCleanup.

Attributes:

GetAccess public
SetAccess public

MATLABSetup — MATLAB setup commands

MATLAB setup commands

Specify MATLAB commands or scripts to perform setup routines specific to this


toolchain. Use commands or scripts that can be invoked from the MATLAB Command
Window. The default value is empty.

The datatype is a cell array of strings.

For example, to display and then update the value of the MATLABSetup and
MATLABCleanup properties, use the MATLAB Command Window to enter:
h = coder.make.ToolchainInfo;
h.MATLABSetup;
h.MATLABCleanup;
h.MATLABSetup{1} = sprintf('if ispc \n origTMP=getenv(''TMP''); \n setenv(''TMP'',''C:\\TEMP'');\nend');
h.MATLABCleanup{1} = sprintf('if ispc \n setenv(''TMP'',origTMP); \nend');

The following list illustrates where this property fits in the sequence of operations :

1 MATLAB Setup
2 Shell Setup
3 Prebuild
4 Build (assembler, compilers, linker, archiver)
5 Postbuild

a Download
b Execute
6 Shell Cleanup

3-151
3 Class Reference

7 MATLAB Cleanup

The “Adding a Custom Toolchain” example does not include the MATLABSetup property.

There are no methods to use with MATLABCleanup.

Attributes:

GetAccess public
SetAccess public

Macros — List of custom macros

List of custom macros that contains macro names and values

The list is a coder.make.util.OrderedList of coder.make.BuildItem objects.

By default this list is empty. For example:

h = coder.make.ToolchainInfo;
h.Macros

ans =

# ---------------
# "Macros" List
# ---------------
(empty)

ToolchainInfo uses macros in two ways:

• It writes macros that are used by the current build to the makefile as variables. For
example:

TI_INSTALL = C:\Program Files\CCSv4


TI_C2000_TOOLS = $(TI_INSTALL)\tools\compiler\c2000\bin
• When the custom toolchain has been registered, validate expands the complete path
provided by a macro, including macros contained within macros. For example, when
ToolchainInfo validates the path in the following compiler information, it expands
both TI_C2000_TOOLS and TI_INSTALL:

Command = 'cl2000'

3-152
coder.make.ToolchainInfo class

Path = '$(TI_C2000_TOOLS)'

The default value of Macros is an empty list.

The datatype is coder.make.util.OrderedList of coder.make.BuildItem objects.

For example, the intel_tc.m file from “Adding a Custom Toolchain”uses the following
lines to add macros to Macros:
% ------------------------------
% Macros
% ------------------------------
tc.addMacro('MW_EXTERNLIB_DIR',['$(MATLAB_ROOT)\extern\lib\' tc.Platform '\microsoft']);
tc.addMacro('MW_LIB_DIR',['$(MATLAB_ROOT)\lib\' tc.Platform]);
tc.addMacro('CFLAGS_ADDITIONAL','-D_CRT_SECURE_NO_WARNINGS');
tc.addMacro('CPPFLAGS_ADDITIONAL','-EHs -D_CRT_SECURE_NO_WARNINGS');
tc.addMacro('LIBS_TOOLCHAIN','$(conlibs)');
tc.addMacro('CVARSFLAG','');

tc.addIntrinsicMacros({'ldebug','conflags','cflags'});

With that example, to see the corresponding property values in a MATLAB command
window, enter:
h = intel_tc;
h.Macros

ans =

# ---------------
# "Macros" List
# ---------------
MW_EXTERNLIB_DIR = $(MATLAB_ROOT)\extern\lib\win64\microsoft
MW_LIB_DIR = $(MATLAB_ROOT)\lib\win64
CFLAGS_ADDITIONAL = -D_CRT_SECURE_NO_WARNINGS
CPPFLAGS_ADDITIONAL = -EHs -D_CRT_SECURE_NO_WARNINGS
LIBS_TOOLCHAIN = $(conlibs)
CVARSFLAG =
ldebug =
conflags =
cflags =

Use the following methods with this property:

• coder.make.ToolchainInfo.addMacro
• coder.make.ToolchainInfo.getMacro

3-153
3 Class Reference

• coder.make.ToolchainInfo.removeMacro
• coder.make.ToolchainInfo.setMacro
• coder.make.ToolchainInfo.addIntrinsicMacros
• coder.make.ToolchainInfo.removeIntrinsicMacros

Attributes:

GetAccess public
SetAccess public

Name — Unique name for toolchain definition

Unique name for the toolchain definition

Specify the full name of the toolchain. This name also appears as one of the Toolchain
parameter options on the Hardware tab of the project build settings. The default value
is empty. The recommended format is:

name version | build artifact (platform)

The datatype is String.

For example, the intel_tc.m file from “Adding a Custom Toolchain”uses the following
line to define the value of Name:
tc.Name = 'Intel v12.1 | nmake makefile (64-bit Windows)';

With that example, to see the corresponding property values in the MATLAB Command
Window, enter:
h = intel_tc;
h.Name

ans =

Intel v12.1 | nmake makefile (64-bit Windows)

Attributes:

GetAccess public
SetAccess public

3-154
coder.make.ToolchainInfo class

Platform — Specify supported platform

Specify the supported platform

Specify the platform upon which the toolchain will be used. The default value is the
current platform. Supported values are win32, win64, maci64, glnxa64, and ''. A ''
value means the toolchain supported on all platforms.

Create a separate ToolchainInfo for each platform.

The datatype is String.

This property does not have any associated methods. Assign the value directly to the
Platform.

For example, the intel_tc.m file from “Adding a Custom Toolchain”uses the following
line to define the value of Platform:

tc.Platform = 'win64';

With that example, to see the corresponding property values in a MATLAB Command
Window, enter:
h = intel_tc;
h.Platform

ans =

win64

Attributes:

GetAccess public
SetAccess public

PostbuildTools — List of tools used after linker archiver

The list of tools used after the linker/archiver are invoked.

The list is a coder.make.util.OrderedList of coder.make.BuildTool objects.

By default the list contains two BuildTool objects: Download and Execute.

3-155
3 Class Reference

To see the corresponding property values in the MATLAB Command Window, enter:
h = coder.make.ToolchainInfo;
h.PostbuildTools

ans =

# -----------------------
# "PostbuildTools" List
# -----------------------
Download = <coder.make.BuildTool>
Execute = <coder.make.BuildTool>

The “Adding a Custom Toolchain” example does not include the PostbuildTools
property.

Use the following methods with this property:

• coder.make.ToolchainInfo.addPostbuildTool
• coder.make.ToolchainInfo.getPostbuildTool
• coder.make.ToolchainInfo.removePostbuildTool
• coder.make.ToolchainInfo.setPostbuildTool

Attributes:

Download public
Execute public

PrebuildTools — List of tools used before compiling source files

The list of tools used before compiling the source files into object files.

The list is a coder.make.util.OrderedList of coder.make.BuildTool objects.

By default this list is empty. For example:


h.PrebuildTools

ans =

3-156
coder.make.ToolchainInfo class

# ----------------------
# "PrebuildTools" List
# ----------------------
(empty)

The “Adding a Custom Toolchain” example does not include the PrebuildTools
property.

Use the following methods with this property:

• coder.make.ToolchainInfo.addPrebuildTool
• coder.make.ToolchainInfo.getPrebuildTool
• coder.make.ToolchainInfo.removePrebuildTool
• coder.make.ToolchainInfo.setPrebuildTool

Attributes:

GetAccess public
SetAccess public

Revision — Assign revision number to ToolchainInfo

Assign revision number to ToolchainInfo

The author of the toolchain definition file can use this information to differentiate one
version of the file from another. The default value is 1.0.

The datatype is String.

This property does not have any associated methods. Assign the value directly to the
Revision.

For example:
h.Revision

ans =

1.0

3-157
3 Class Reference

h.Revision = '2.0';
h.Revision

ans =

2.0

Attributes:

GetAccess public
SetAccess public

ShellCleanup — Shell scripts that clean up toolchain

Shell scripts that clean up the toolchain

Specify shell commands or scripts to perform cleanup routines specific to this toolchain.
Use commands or scripts that can be invoked from the system command environment.
The default value is empty.

The datatype is a Cell array of strings. Each string is a shell cleanup command.

If ToolchainInfo invokes a setup routine, you can use a corresponding set of cleanup
routines to restore the system environment to its original settings. For example, if a
setup routine added environment variables and folders to the system path, you can use a
cleanup routine to remove them.

For example:

>> h.ShellCleanup

ans =

[]

>> h.ShellCleanup = 'call "cleanup_mssdk71.bat"';

>> h.ShellCleanup

ans =

'call "cleanup_mssdk71.bat"'

3-158
coder.make.ToolchainInfo class

The following list illustrates where this property fits in the sequence of operations :

1 MATLAB Setup
2 Shell Setup
3 Prebuild
4 Build (assembler, compilers, linker, archiver)
5 Postbuild

a Download
b Execute
6 Shell Cleanup
7 MATLAB Cleanup

The “Adding a Custom Toolchain” example does not include the ShellCleanup property.

Attributes:

GetAccess public
SetAccess public

ShellSetup — Shell scripts that set up toolchain

Shell scripts that set up the toolchain

Specify shell commands or scripts to perform setup routines specific to this toolchain. Use
commands or scripts that can be invoked from the system command environment. The
default value is empty.

The datatype is a Cell array of strings. Each string is a shell setup command.

If ToolchainInfo invokes a setup routine, you can use a corresponding set of cleanup
routines to restore the system environment to its original settings. For example, if a
setup routine added environment variables and folders to the system path, you can use a
cleanup routine to remove them.

For example:

>> h.ShellSetup

3-159
3 Class Reference

ans =

[]

>> h.ShellSetup = 'call "setup_mssdk71.bat"';

>> h.ShellSetup

ans =

'call "setup_mssdk71.bat"'

The intel_tc.m file in “Adding a Custom Toolchain” uses the following lines to set the
value of ShellSetup:

% ------------------------------
% Setup
% ------------------------------
% Below we are using %ICPP_COMPILER12% as root folder where Intel Compiler is
% installed. You can either set an environment variable or give full path to the
% compilervars.bat file
tc.ShellSetup{1} = 'call %ICPP_COMPILER12%\bin\compilervars.bat intel64';

With that example, to see the corresponding property values in the MATLAB Command
Window, enter:
h = intel_tc;
h.ShellSetup

ans =

'call %ICPP_COMPILER12%\bin\compilervars.bat intel64'

The following list illustrates where this property fits in the sequence of operations :

1 MATLAB Setup
2 Shell Setup
3 Prebuild
4 Build (assembler, compilers, linker, archiver)
5 Postbuild

a Download

3-160
coder.make.ToolchainInfo class

b Execute
6 Shell Cleanup
7 MATLAB Cleanup

Attributes:

GetAccess public
SetAccess public

SupportedLanguages — Create BuildTool objects for specific languages

Create BuildTool objects for specific languages

Initializing ToolchainInfo creates BuildTool objects for the language or set of


languages specified by SupportedLanguages.

If you do not specify a value for SupportedLanguages, the default value is 'C/C++'. This
adds BuildTool objects for a C compiler and a C++ compiler to the other BuildTool
objects in ToolchainInfo.

To override the default, use a name-value pair to specify a value for SupportedLanguages
when you initialize ToolchainInfo. For example:
h = coder.make.ToolchainInfo('SupportedLanguages','C');
The value can be: 'C', 'C++', 'C/C++', 'Asm/C', 'Asm/C++', or 'Asm/C/C++'.

The SupportedLanguages property does not have any related methods.

The “Adding a Custom Toolchain” example does not include the SupportedLanguages
property.

Attributes:

GetAccess public
SetAccess public

SupportedVersion — Version of software build tools that ToolchainInfo supports

The version of the software build tools ToolchainInfo supports.

The default value is empty.

3-161
3 Class Reference

The datatype is String.

This property does not have any associated methods. Assign the value directly to the
SupportedVersion.

With the “Adding a Custom Toolchain” example, the value of SupportedVersion is


defined in the intel_tc.m toolchain definition file:

tc.SupportedVersion = '12.1';

With that example, to see the corresponding property values in the MATLAB command
window, enter:
h = intel_tc;
h.SupportedVersion

ans =

12.1

Attributes:

GetAccess public
SetAccess public

Methods

See Also
coder.make.BuildConfiguration | coder.make.BuildItem |
coder.make.BuildTool

Related Examples
• “Adding a Custom Toolchain”

More About
• “About coder.make.ToolchainInfo”

3-162
4

Tools — Alphabetical List


4 Tools — Alphabetical List

Code Replacement Viewer


Explore content of code replacement libraries

Description
The Code Replacement Viewer displays the content of code replacement libraries. Use
the tool to explore and choose a library. If you develop a custom code replacement library,
use the tool to verify table entries.

• Argument order is correct.


• Conceptual argument names match code generator naming conventions.
• Implementation argument names are correct.
• Header or source file specification is not missing.
• I/O types are correct.
• Relative priority of entries is correct (highest priority is 0, and lowest priority is 100).
• Saturation or rounding mode specifications are not missing.

If you specify a library name when you open the viewer, the viewer displays the code
replacement tables that the library contains. When you select a code replacement table,
the viewer displays function and operator code replacement entries that are in that table.

Abbreviated Entry Information


In the middle pane, the viewer displays entries that are in the selected code replacement
table, along with abbreviated information for each entry.

Field Description
Name Name or identifier of the function or operator being replaced
(for example, cos or RTW_OP_ADD).
Implementation Name of the implementation function, which can match or
differ from Name.
NumIn Number of input arguments.
In1Type Data type of the first conceptual input argument.
In2Type Data type of the second conceptual input argument.
OutType Data type of the conceptual output argument.

4-2
Code Replacement Viewer

Field Description
Priority The entry's match priority, relative to other entries of the
same name and to the conceptual argument list within the
selected code replacement library. The priority can range from
0 to 100, with 0 being the highest priority. The default is 100.
If the library provides two implementations for a function
or operator, the implementation with the higher priority
shadows the one with the lower priority.
UsageCount Not used.

Detailed Entry Information


In the middle pane, when you select an entry, the viewer displays entry details.

Field Description
Description Text description of the table entry (can be empty).
Key Name or identifier of the function or operator being replaced (for
example, cos or RTW_OP_ADD), and the number of conceptual
input arguments.
Implementation Name of the implementation function, and the number of
implementation input arguments.
Implementation Type of implementation: FCN_IMPL_FUNCT for function or
type FCN_IMPL_MACRO for macro.
Saturation mode Saturation mode that the implementation function supports. One
of:
RTW_SATURATE_ON_OVERFLOW
RTW_WRAP_ON_OVERFLOW
RTW_SATURATE_UNSPECIFIED
Rounding modes Rounding modes that the implementation function supports. One
or more of:
RTW_ROUND_FLOOR
RTW_ROUND_CEILING
RTW_ROUND_ZERO
RTW_ROUND_NEAREST
RTW_ROUND_NEAREST_ML
RTW_ROUND_SIMPLEST

4-3
4 Tools — Alphabetical List

Field Description
RTW_ROUND_CONV
RTW_ROUND_UNSPECIFIED
GenCallback file Not used.
Implementation Name of the header file that declares the implementation function.
header
Implementation Name of the implementation source file.
source
Priority The entry's match priority, relative to other entries of the same
name and to the conceptual argument list within the selected
code replacement library. The priority can range from 0 to 100,
with 0 being the highest priority. The default is 100. If the library
provides two implementations for a function or operator, the
implementation with the higher priority shadows the one with the
lower priority.
Total Usage Not used.
Count
Entry class Class from which the current table entry is instantiated.
Conceptual Name, I/O type (RTW_IO_OUTPUT or RTW_IO_INPUT), and data
arguments type for each conceptual argument.
Implementation Name, I/O type (RTW_IO_OUTPUT or RTW_IO_INPUT), data type,
and alignment requirement for each implementation argument.

Fixed-Point Entry Information


When you select an operator entry that specifies net slope fixed-point parameters, the
viewer displays fixed-point information.

Field Description
Net slope Slope adjustment factor (F) part of the net slope factor, F2E ,
adjustment factor for net slope table entries. You use this factor with fixed-point
F multiplication and division replacement to map a range of slope
and bias values to a replacement function.
Net fixed exponent Fixed exponent (E) part of the net slope factor, F2E, for net
E slope table entries. You use this fixed exponent with fixed-point

4-4
Code Replacement Viewer

Field Description
multiplication and division replacement to map a range of slope
and bias values to a replacement function.
Slopes must be the Indicates whether code replacement request processing must
same check that the slopes on arguments (input and output) are
equal. You use this information with fixed-point addition and
subtraction replacement to disregard specific slope and bias
values, and map relative slope and bias values to a replacement
function.
Must have zero net Indicates whether code replacement request processing
bias must check that the net bias on arguments is zero. You use
this information with fixed-point addition and subtraction
replacement to disregard specific slope and bias values, and map
relative slope and bias values to a replacement function.

Open the Code Replacement Viewer App


Open from the MATLAB command prompt using crviewer.

Examples
Display Contents of Code Replacement Library

crviewer('ARM Cortex-A')

4-5
4 Tools — Alphabetical List

Display Contents of Code Replacement Table

crviewer(clr_table_ne10)

4-6
Code Replacement Viewer

• “Choose a Code Replacement Library”

Programmatic Use
crviewer(library) opens the Code Replacement Viewer and displays the contents of
library, where library is a string that names a registered code replacement library.
For example, 'GNU 99 extensions'.

crviewer(table) opens the Code Replacement Viewer and displays the contents of
table, where table is a MATLAB file that defines code replacement tables. The file
must be in the current folder or on the MATLAB path.

More About
• “What Is Code Replacement?”
• “Code Replacement Libraries”
• “Code Replacement Terminology”

4-7
MATLAB® Coder™ Release Notes
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™ Release Notes


© 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.
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

R2016a

Cell Array Support: Use additional cell array features in


MATLAB code for code generation . . . . . . . . . . . . . . . . . . . 1-2
Use of {end + 1} to grow a cell array . . . . . . . . . . . . . . . . . . . 1-2
Value and handle objects in cell arrays . . . . . . . . . . . . . . . . . 1-2
Function handles in cell arrays . . . . . . . . . . . . . . . . . . . . . . . 1-2

Non-Power-of-Two FFT Support: Generate code for fast


Fourier transforms for non-power-of-two transform
lengths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2

Faster Standalone Code for Linear Algebra: Generate code


that takes advantage of your own target-specific LAPACK
library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2

Computer Vision System Toolbox and Image Processing


Toolbox Code Generation: Generate code for additional
functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3

MATLAB Coder Student Access: Obtain MATLAB Coder as


student-use, add-on product or with MATLAB Primary and
Secondary School Suite . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3

Concatenation of Variable-Size Empty Arrays: Generate code


for concatenation when a component array is empty . . . . 1-3

memset Optimization for More Cases: Optimize code that


assigns a constant value to consecutive array elements . . 1-6

Optimization for Conditional and Boolean Expressions:


Generate efficient code for more cases . . . . . . . . . . . . . . . . 1-7

v
MATLAB Coder App Line Execution Count: See how well test
exercises MATLAB code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8

MATLAB Coder App Undo and Redo: Easily revert changes to


type definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10

MATLAB Coder App Error Table: View complete error


message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11

Changes to Fixed-Point Conversion Code Coverage . . . . . . 1-12

More Keyboard Shortcuts in Code Generation Report:


Navigate the report more easily . . . . . . . . . . . . . . . . . . . . 1-13

xcorr Code Generation: Generate faster code for xcorr with


long input vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14

Code generation for additional MATLAB functions . . . . . . 1-14


Specialized Math in MATLAB . . . . . . . . . . . . . . . . . . . . . . . 1-14
Trigonometry in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . 1-14
Interpolation and Computational Geometry in MATLAB . . . 1-15

Changes to code generation support for MATLAB


functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-15

Code generation for Audio System Toolbox functions and


System objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-15

Code generation for additional Communications System


Toolbox functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-15

Code generation for additional DSP System Toolbox . . . . . 1-15

Code generation for additional Phased Array System Toolbox


functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16

Code generation for additional Robotics System Toolbox


functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16

Code generation for WLAN System Toolbox functions and


System objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16

Check bug reports for issues and fixes . . . . . . . . . . . . . . . . . 1-17

vi Contents
R2015aSP1

Bug Fixes

Check bug reports for issues and fixes . . . . . . . . . . . . . . . . . . 2-2

R2015b

Cell Array Support: Generate C code from MATLAB code that


uses cell arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2

Faster MEX Functions for Linear Algebra: Generate MEX


functions that take advantage of LAPACK . . . . . . . . . . . . . 3-2

Double-Precision to Single-Precision Conversion: Convert


double-precision MATLAB code to single-precision C
code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2

Run-Time Checks in Standalone C Code: Detect and


report run-time errors while testing generated standalone
libraries and executables . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3

Multicore Capable Functions: Generate OpenMP-enabled


C code from more than twenty MATLAB mathematics
functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4

Image Processing Toolbox and Computer Vision System


Toolbox Code Generation: Generate code for additional
functions in these toolboxes . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
Image Processing Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
Computer Vision System Toolbox . . . . . . . . . . . . . . . . . . . . . 3-4

Statistics and Machine Learning Toolbox Code Generation:


Generate code for kmeans and randsample . . . . . . . . . . . . 3-5

Simplified hardware specification in the MATLAB Coder


app . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5

vii
MATLAB Coder app user interface improvements . . . . . . . . 3-7
Improvements for manual type definition . . . . . . . . . . . . . . . 3-7
Tab completion for specifying files . . . . . . . . . . . . . . . . . . . . 3-8
Compatibility between the app colors and MATLAB
preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8
Progress indicators for the Check for Run-Time Issues step . . 3-8

Saving and restoring of workflow state between MATLAB


Coder app sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-9

Project reuse between MATLAB Coder and HDL Coder . . . . 3-9

Code generation using freely available MinGW-w64


compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10

codegen debug option for libraries and executables . . . . . . 3-10

Code generation for additional MATLAB functions . . . . . . 3-10


Data Types in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10
String Functions in MATLAB . . . . . . . . . . . . . . . . . . . . . . . 3-11

Code generation for additional Communications System


Toolbox, DSP System Toolbox, and Phased Array System
Toolbox System objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-11
Communications System Toolbox . . . . . . . . . . . . . . . . . . . . 3-11
DSP System Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-11
Phased Array System Toolbox . . . . . . . . . . . . . . . . . . . . . . . 3-11

Code generation for Robotics System Toolbox functions and


System objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12

Code generation for System Identification Toolbox functions


and System objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12

Fixed-Point Conversion Enhancements . . . . . . . . . . . . . . . . 3-12


Saving and restoring fixed-point conversion workflow state in
the app . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12
Reuse of MEX files during fixed-point conversion using the
app . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12
Specification of additional fimath properties in app editor . 3-12
Improved management of comparison plots . . . . . . . . . . . . . 3-13
Variable specializations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-14
Detection of multiword operations . . . . . . . . . . . . . . . . . . . . 3-15

viii Contents
Check bug reports for issues and fixes . . . . . . . . . . . . . . . . . . 3-2

R2015a

Improved MATLAB Coder app with integrated editor and


simplified workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2

Generation of example C/C++ main for integration of


generated code into an application . . . . . . . . . . . . . . . . . . . 4-3

Better preservation of MATLAB variable names in generated


code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4

More efficient generated code for logical indexing . . . . . . . . 4-4

Code generation for additional Image Processing Toolbox


and Computer Vision System Toolbox functions . . . . . . . . 4-5
Image Processing Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5
Computer Vision System Toolbox . . . . . . . . . . . . . . . . . . . . . 4-5

Code generation for additional Communications System


Toolbox, DSP System Toolbox, and Phased Array System
Toolbox System objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6
Communications System Toolbox . . . . . . . . . . . . . . . . . . . . . 4-6
DSP System Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6
Phased Array System Toolbox . . . . . . . . . . . . . . . . . . . . . . . . 4-6

Code generation for additional Statistics and Machine


Learning Toolbox functions . . . . . . . . . . . . . . . . . . . . . . . . . 4-7

Code generation for additional MATLAB functions . . . . . . . 4-7


Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7
Statistics in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7

Code generation for additional MATLAB function options . 4-7

Conversion from project to MATLAB script using MATLAB


Coder app . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8

ix
Improved recognition of compile-time constants . . . . . . . . . 4-8

Improved emxArray interface function generation . . . . . . . . 4-9


emxArray interface functions for variable-size arrays that
external C/C++ functions use . . . . . . . . . . . . . . . . . . . . . . 4-9
Functions to initialize output emxArrays and emxArrays in
structure outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9
External definition of a structure that contains emxArrays . 4-10

Code generation for casts to and from types of variables


declared using coder.opaque . . . . . . . . . . . . . . . . . . . . . . . 4-10

Generation of reentrant code without an Embedded Coder


license . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-12

Code generation for parfor-loops with stack overflow . . . . 4-12

Change in default value of the PassStructByReference code


configuration object property . . . . . . . . . . . . . . . . . . . . . . 4-12

Change in GLOBALS variable in scripts generated from a


project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-13

Target build log display for command-line code generation


when hyperlinks disabled . . . . . . . . . . . . . . . . . . . . . . . . . . 4-13

Removal of instrumented MEX output type . . . . . . . . . . . . . 4-14

Truncation of long enumerated type value names that


include the class name prefix . . . . . . . . . . . . . . . . . . . . . . 4-14

Fixed-point conversion enhancements . . . . . . . . . . . . . . . . . 4-15


Support for multiple entry-point functions . . . . . . . . . . . . . 4-15
Support for global variables . . . . . . . . . . . . . . . . . . . . . . . . 4-15
Code coverage-based translation . . . . . . . . . . . . . . . . . . . . . 4-15
Generated fixed-point code enhancements . . . . . . . . . . . . . . 4-16
Automated fixed-point conversion of additional DSP System
Toolbox objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-16
New interpolation method for generating lookup table MATLAB
function replacements . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-16

Check bug reports for issues and fixes . . . . . . . . . . . . . . . . . 4-17

x Contents
R2014b

Code generation for additional Image Processing Toolbox


and Computer Vision System Toolbox functions . . . . . . . . 5-2
Image Processing Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Computer Vision System Toolbox . . . . . . . . . . . . . . . . . . . . . 5-2

Code generation for additional Communications System


Toolbox and DSP System Toolbox functions and System
objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Communications System Toolbox . . . . . . . . . . . . . . . . . . . . . 5-2
DSP System Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2

Code generation for enumerated types based on built-in


MATLAB integer types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3

Code generation for function handles in structures . . . . . . . 5-4

Change in enumerated type value names in generated


code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4

Code generation for ode23 and ode45 ordinary differential


equation solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5

Code generation for additional MATLAB functions . . . . . . . 5-5


Data and File Management in MATLAB . . . . . . . . . . . . . . . . 5-5
Linear Algebra in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . 5-6
String Functions in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . 5-6

Code generation for additional MATLAB function options . 5-6

Collapsed list for inherited properties in code generation


report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-6

Change in length of exported identifiers . . . . . . . . . . . . . . . . 5-6

Intel Performance Primitives (IPP) platform-specific


code replacement libraries for cross-platform code
generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7

xi
Fixed-point conversion enhancements . . . . . . . . . . . . . . . . . . 5-8
Conversion from project to MATLAB scripts for command-line
fixed-point conversion and code generation . . . . . . . . . . . . 5-8
Lookup table approximations for unsupported functions . . . . 5-8
Enhanced plotting capabilities . . . . . . . . . . . . . . . . . . . . . . . 5-9
Automated fixed-point conversion for commonly used System
objects in MATLAB including Biquad Filter, FIR Filter, and
Rate converter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10
Additional fixed-point conversion command-line options . . . 5-10
Type proposal report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10
Generated fixed-point code enhancements . . . . . . . . . . . . . . 5-11
Highlighting of potential data type issues in generated HTML
report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-12

Check bug reports for issues and fixes . . . . . . . . . . . . . . . . . 5-14

R2014a

Code generation for additional Image Processing Toolbox


and Computer Vision System Toolbox functions . . . . . . . . 6-2
Image Processing Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Computer Vision System Toolbox . . . . . . . . . . . . . . . . . . . . . 6-2

Code generation for additional Signal Processing Toolbox,


Communications System Toolbox, and DSP System Toolbox
functions and System objects . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Signal Processing Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Communications System Toolbox . . . . . . . . . . . . . . . . . . . . . 6-3
DSP System Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3

Code generation for fminsearch optimization function and


additional interpolation functions in MATLAB . . . . . . . . . 6-3
Optimization Functions in MATLAB . . . . . . . . . . . . . . . . . . . 6-3
Interpolation and Computational Geometry in MATLAB . . . . 6-3

Conversion from project to MATLAB script for command-line


code generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4

Code generation for fread function . . . . . . . . . . . . . . . . . . . . . 6-4

xii Contents
Automatic C/C++ compiler setup . . . . . . . . . . . . . . . . . . . . . . . 6-4

Compile-time declaration of constant global variables . . . . . 6-4

Enhanced code generation support for switch statements . 6-5

Code generation support for value classes with set.prop


methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5

Code generation error for property that uses AbortSet


attribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6

Independent configuration selections for standard math and


code replacement libraries . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6

Restrictions on bit length for integer types in a


coder.HardwareImplementation object . . . . . . . . . . . . . . . 6-9

Change in location of interface files in code generation


report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9

Compiler warnings in code generation report . . . . . . . . . . . . 6-9

Removal of date and time comment from generated code


files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9

Removal of two's complement guard from rtwtypes.h . . . . 6-9

Removal of TRUE and FALSE from rtwtypes.h . . . . . . . . . . . 6-10

Change to default names for structure types generated from


entry-point function inputs and outputs . . . . . . . . . . . . . 6-10

Toolbox functions supported for code generation . . . . . . . . 6-11

Fixed-point conversion enhancements . . . . . . . . . . . . . . . . . 6-13


Overflow detection with scaled double data types in MATLAB
Coder projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-13
Support for MATLAB classes . . . . . . . . . . . . . . . . . . . . . . . 6-13
Generated fixed-point code enhancements . . . . . . . . . . . . . . 6-13
Fixed-point report for float-to-fixed conversion . . . . . . . . . . 6-14

Check bug reports for issues and fixes . . . . . . . . . . . . . . . . . 6-15

xiii
R2013b

Code generation for Statistics Toolbox and Phased Array


System Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2

Toolbox functions supported for code generation . . . . . . . . . 7-2

parfor function for standalone code generation, enabling


execution on multiple cores . . . . . . . . . . . . . . . . . . . . . . . . . 7-3

Persistent variables in parfor-loops . . . . . . . . . . . . . . . . . . . . 7-3

Random number generator functions in parfor-loops . . . . . 7-3

External code integration using


coder.ExternalDependency . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3

Updating build information using coder.updateBuildInfo . . 7-3

Generation of simplified code using built-in C types . . . . . . 7-4

Conversion of MATLAB expressions into C constants using


coder.const . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4

Highlighting of constant function arguments in the


compilation report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4

Code Generation Support for int64, uint64 data types . . . . . 7-4

C99 long long integer data type for code generation . . . . . . 7-5

Change to passing structures by reference . . . . . . . . . . . . . . 7-5

coder.runTest new syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6

coder.target syntax change . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6

Changes for complex values with imaginary part equal to


zero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6

Subfolder for code generation interface files . . . . . . . . . . . . 7-7

xiv Contents
Support for LCC compiler on Windows 64-bit machines . . . 7-7

Fixed-Point conversion enhancements . . . . . . . . . . . . . . . . . . 7-7

Check bug reports for issues and fixes . . . . . . . . . . . . . . . . . . 7-9

R2013a

Automatic fixed-point conversion during code generation


(with Fixed-Point Designer) . . . . . . . . . . . . . . . . . . . . . . . . . 8-2

File I/O function support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2

Support for nonpersistent handle objects . . . . . . . . . . . . . . . 8-3

Structures passed by reference to entry-point functions . . . 8-3

Include custom C header files from MATLAB code . . . . . . . . 8-3

Load from MAT-files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4

coder.opaque function enhancements . . . . . . . . . . . . . . . . . . 8-4

Automatic regeneration of MEX functions in projects . . . . . 8-4

MEX function signatures include constant inputs . . . . . . . . 8-5

Custom toolchain registration . . . . . . . . . . . . . . . . . . . . . . . . . 8-5

Complex trigonometric functions . . . . . . . . . . . . . . . . . . . . . . 8-6

parfor function reduction improvements and C support . . . 8-6

Support for integers in number theory functions . . . . . . . . . 8-6

Enhanced support for class property initial values . . . . . . . 8-7

Optimized generated code for x=[x c] when x is a vector . . 8-8

xv
Default use of Basic Linear Algebra Subprograms (BLAS)
libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-9

Changes to compiler support . . . . . . . . . . . . . . . . . . . . . . . . . . 8-9

New toolbox functions supported for code generation . . . . . 8-9

Functions being removed . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-11

Check bug reports for issues and fixes . . . . . . . . . . . . . . . . . 8-12

R2012b

parfor function support for MEX code generation, enabling


execution on multiple cores . . . . . . . . . . . . . . . . . . . . . . . . . 9-2

Code generation readiness tool . . . . . . . . . . . . . . . . . . . . . . . . 9-2

Reduced data copies and lightweight run-time checks for


generated MEX functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2

Additional string function support for code generation . . . . 9-2

Visualization functions in generated MEX functions . . . . . . 9-3

Input parameter type specification enhancements . . . . . . . . 9-3

Project import and export capability . . . . . . . . . . . . . . . . . . . 9-4

Package generated code in zip file for relocation . . . . . . . . . 9-5

Fixed-point instrumentation and data type proposals . . . . . 9-5

New toolbox functions supported for code generation . . . . . 9-5

New System objects supported for code generation . . . . . . . 9-6

Check bug reports for issues and fixes . . . . . . . . . . . . . . . . . . 9-8

xvi Contents
R2012a

Code Generation for MATLAB Classes . . . . . . . . . . . . . . . . . 10-2

Dynamic Memory Allocation Based on Size . . . . . . . . . . . . . 10-2

C/C++ Dynamic Library Generation . . . . . . . . . . . . . . . . . . . 10-2

Automatic Definition of Input Parameter Types . . . . . . . . . 10-2

Verification of MEX Functions . . . . . . . . . . . . . . . . . . . . . . . 10-3

Enhanced Project Settings Dialog Box . . . . . . . . . . . . . . . . . 10-3

Projects Infer Input Types from assert Statements in Source


Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-4

Code Generation from MATLAB . . . . . . . . . . . . . . . . . . . . . . 10-4

New Demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-4

Check bug reports for issues and fixes . . . . . . . . . . . . . . . . . 10-5

R2011b

Support for Deletion of Rows and Columns from Matrices 11-2

Code Generation from MATLAB . . . . . . . . . . . . . . . . . . . . . . 11-2

Check bug reports for issues and fixes . . . . . . . . . . . . . . . . . 11-3

xvii
R2011a

New User Interface for Managing Projects . . . . . . . . . . . . . 12-2


To Get Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-2

Migrating from Real-Time Workshop emlc Function . . . . . 12-2


New codegen Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-2
New Code Generation Configuration Objects . . . . . . . . . . . . 12-4
The codegen Function Has No Default Primary Function Input
Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-5
The codegen Function Processes Compilation Options in a
Different Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-5

New coder.Type Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-5

New coder Package Functions . . . . . . . . . . . . . . . . . . . . . . . . 12-6

Script to Upgrade MATLAB Code to Use MATLAB Coder


Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-6

Embedded MATLAB Now Called Code Generation from


MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-6

MATLAB Coder Uses rtwTargetInfo.m to Register Target


Function Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-7

New Getting Started Tutorial Video . . . . . . . . . . . . . . . . . . . 12-7

New Demos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-7

Functionality Being Removed in a Future Version . . . . . . . 12-8

Function Elements Being Removed in a Future Release . . 12-8

Check bug reports for issues and fixes . . . . . . . . . . . . . . . . 12-10

xviii Contents
R2016a
Version: 3.1

New Features

Bug Fixes

Compatibility Considerations
R2016a

Cell Array Support: Use additional cell array features in MATLAB code for
code generation
In R2016a, code generation support for cell arrays includes:

Use of {end + 1} to grow a cell array

You can write code such as X{end + 1} to grow a cell array X. For example:

X = {1 2};
X(end + 1} = 'a';

When you use {end + 1} to grow a cell array, follow the restrictions described in
“Growing a Cell Array by Using {end + 1}”.

Value and handle objects in cell arrays

Cell arrays can contain value and handle objects. You can use a cell array of objects as a
workaround for the limitation that code generation does not support objects in matrices
or structures.

Function handles in cell arrays

Cell arrays can contain function handles.

Non-Power-of-Two FFT Support: Generate code for fast Fourier


transforms for non-power-of-two transform lengths
In previous releases, code generation required a power of two transform length for fft,
fft2, fftn, ifft, ifft2, and ifftn. In R2016a, code generation allows a non-power-of-
two length for these functions.

Faster Standalone Code for Linear Algebra: Generate code that takes
advantage of your own target-specific LAPACK library
To improve the execution speed of code generated for algorithms that call linear algebra
functions, MATLAB® Coder™ can generate calls to LAPACK functions by using the
LAPACKE C interface to LAPACK. If the input arrays for the linear algebra functions
meet certain criteria, MATLAB Coder generates calls to relevant LAPACK functions.

1-2
Check Bug Reports for Issues and Fixes

In R2015b, only generated MEX called LAPACK functions. In R2016a, generated


standalone code can call LAPACK functions.

LAPACK is a software library for numerical linear algebra. MATLAB uses this library in
some linear algebra functions such as eig and svd. For MEX functions, MATLAB Coder
uses the LAPACK library that is included with MATLAB. For standalone code, MATLAB
Coder uses the LAPACKE interface for the LAPACK library that you specify. If you do
not specify a LAPACK library, MATLAB Coder generates code for the linear algebra
function instead of generating a LAPACK call.

See “Speed Up Linear Algebra in Generated Standalone Code by Using LAPACK Calls”.

Computer Vision System Toolbox and Image Processing Toolbox Code


Generation: Generate code for additional functions
See “C code generation support” in the Computer Vision System Toolbox™ release notes.

See “C-code generation support for more than 20 functions, including regionprops,
watershed, bweuler, bwlabel, bwperim, and multithresh using MATLAB Coder” in the
Image Processing Toolbox™ release notes.

MATLAB Coder Student Access: Obtain MATLAB Coder as student-use,


add-on product or with MATLAB Primary and Secondary School Suite
Starting with R2016a, MATLAB Coder is available for purchase as an add-on product
for student-use software: MATLAB Student™ and MATLAB and Simulink® Student
Suite™. Student-use software provides the same tools that professional engineers and
scientists use. Students use the software to develop skills that help them excel in courses
and prepare for careers.

Starting with R2016a, MATLAB Coder is included in the MATLAB Primary and
Secondary School Suite.

Concatenation of Variable-Size Empty Arrays: Generate code for


concatenation when a component array is empty
In R2016a, the MATLAB Coder treatment of an empty array in a concatenation more
closely matches the MATLAB treatment.

1-3
R2016a

For concatenation of arrays, MATLAB and MATLAB Coder require that corresponding
dimensions across component arrays have the same size, except for the dimension
that grows. For horizontal concatenation, the second dimension grows. For vertical
concatenation, the first dimension grows.

In MATLAB, when a component array is empty, the sizes of the nongrowing dimensions
do not matter because MATLAB ignores empty arrays in a concatenation. In previous
releases, MATLAB Coder required that the sizes of nongrowing dimensions of a variable-
size, empty array matched the sizes of the corresponding dimensions in the other
component arrays. A dimension size mismatch resulted in an error in the MEX function
and a possible incorrect answer in standalone code.

In R2016a, for most cases of empty arrays in concatenation, MATLAB Coder behavior
matches MATLAB behavior. In some cases, if MATLAB Coder does not recognize the
empty array and treats it as a variable-size array, a dimension size mismatch results in a
compile-time error.

Consider the function myconcat that concatenates two arrays.

function C = myconcat(A, B)
C = [A, B];
end

Define the types IN1 and IN2. IN1 is variable-size in both dimensions with no upper
bounds. IN2 is variable-size with an upper bound of 5 in each dimension.

IN1 = coder.typeof(1, [Inf Inf], [1 1]);


IN2 = coder.typeof(1, [5 5], [1 1]);

Generate MEX for myconcat. Use the -args option to indicate that the input arguments
have the types defined by IN1 and IN2.

codegen myconcat -args {IN1, IN2} -report

Define R1 and R2.

R1 = zeros(0,5);
R2 = magic(3)

R1 is a 0-by-5 empty matrix. R2 is a 3-by-3 matrix.

In previous releases, myconcat_mex(R1, R2) resulted in a size mismatch error. The


size of dimension 1 of the empty array R1 did not match the size of dimension 1 of R2.

1-4
Check Bug Reports for Issues and Fixes

In R2016a, myconcat_mex(R1, R2) produces the same answer as the answer in


MATLAB.

ans =

8 1 6
3 5 7
4 9 2

Compatibility Considerations
When the result of the concatenation is assigned to a variable that must be fixed-size,
support for a variable-size, empty array in a concatenation introduces an incompatibility.

In previous releases, it is possible that a concatenation that included a variable-size


array produced a fixed-size array because concatenation rules were stricter in MATLAB
Coder than in MATLAB. In R2016a, a concatenation that includes a variable-size array
produces a variable-size array. If the result of the concatenation is assigned to a variable
that must be fixed-size, the code generation software produces a compile-time error.

Consider the function myconcat.

function Z = myconcat1(X, Y)
%#codegen
Z.f = [X Y];

Suppose that you generate a MEX function for myconcat1. Suppose that you specify
these sizes for the input arguments:

• X has size :?-by-2. The first dimension has a variable size with no upper bound and
the second dimension has a fixed size of 2.
• Y has size 2-by-4.

In the generated code, the size of the result of [X Y] is 2-by-:6. The first dimension
has a fixed size of 2 and the second dimension has a variable size with an upper
bound of 6. This size accommodates both an empty and nonempty X. If you pass an
empty X to myconcat_mex, the size of the result is 2-by-4. If you pass a nonempty X to
myconcat_mex, the size of the result is 2-by-6.

Consider the function myconcat2.

function Z = myconcat2(X, Y)

1-5
R2016a

%#codegen
Z.f = ones(2, 6);
myfcn(Z);
Z.f = [X Y];

function myfcn(~)

myconcat2 assigns a 2-by-6 value to Z.f. At compile time, the size of Z.f is fixed at 2-
by-6 because Z is passed to myfcn. In the assignment Z.f = [X Y], the result of the
concatenation[X Y] is variable-size. Code generation fails because the left side of the
assignment is fixed-size and the right side is variable-size.

To work around this incompatibility, you can use coder.varsize to declare that Z.f is
variable-size.
function Z = myconcat2(X, Y)
%#codegen
coder.varsize('Z.f');
Z.f = ones(2, 6);
myfcn(Z);
Z.f = [X Y];

function myfcn(~)

memset Optimization for More Cases: Optimize code that assigns a


constant value to consecutive array elements
To optimize generated code that assigns a literal constant to consecutive array elements,
the code generation software tries to replace the code with a memset call. A memset call
can be more efficient than code, such as a for-loop or multiple, consecutive element
assignments.

In R2016a, MATLAB Coder invokes the memset optimization for more cases than in
previous releases.

A loop with multiple assignments.

Previous Releases R2016a


for (i = 0; i < 100; i++) { memset(&Y1[0],0,100U*sizeof(double));
Y1[i] = 0.0; memset(&Y2[0],0,100U*sizeof(double ));
Y2[i] = 0.0; memset(&Y3[0],0,100U*sizeof(double ));
Y3[i] = 0.0;
}

1-6
Check Bug Reports for Issues and Fixes

Consecutive statements that define a continuous write.

Previous Releases R2016a


Y1[0] = 255; memset(&Y1[0], 255, 100U * sizeof(unsigned char));
Y1[1] = 255;
Y1[2] = 255;
...
Y1[99] = 255

A structure that contains an array.

Previous Releases R2016a


for (i = 0; i < 100; i++) { memset(&S>f1[0], 0, 100U * sizeof(double));

S->f1[i] = 0.0;

All fields of a structure array assigned the same constant value.

Previous Releases R2016a


for (i = 0; i < 100; i++) { memset(&S[0], 255, 100U * sizeof(struct0_T));
S[i].f1 = 255;
S[i].f2 = 255;
S[i].f3 = 255;
}

For information about settings that affect the memset optimization, see “memset
Optimization”.

Optimization for Conditional and Boolean Expressions: Generate efficient


code for more cases
For certain conditional and Boolean expressions, MATLAB Coder optimizes the
generated code by replacing expressions with simpler, more efficient expressions. In
R2016a, MATLAB Coder uses this optimization for more cases.

Here are examples of this optimization.

Previous Releases R2016a


if (cond) { return cond || val;
y = true;
} else {
y = val;
}

return y;
y = x && !x; y = false;

1-7
R2016a

MATLAB Coder App Line Execution Count: See how well test exercises
MATLAB code
When you perform the Check for Run-Time Issues step in the MATLAB Coder
app, you must provide a test that calls your entry-point functions with representative
data. The Check for Run-Time Issues step generates a MEX function from your
MATLAB functions and runs the test replacing calls to the MATLAB functions with
calls to the MEX function. In R2016a, to help you see how well your test exercises your
MATLAB code, the app collects and displays line execution counts. When the app runs
the MEX function, the app counts executions of the MEX code that corresponds to a line
of MATLAB code.

To see the line execution counts, after you check for run-time issues, click View
MATLAB line execution counts.

The app displays your MATLAB code in the app editor. The app displays a color-coded
coverage bar to the left of the code. This table describes the color coding.

Color Indicates
Green One of the following situations:

1-8
Check Bug Reports for Issues and Fixes

Color Indicates
• 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 position 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.

Line execution count collection is enabled by default. To disable the collection, clear the
Collect MATLAB line execution counts check box. If line execution collection slows
the run-time issue checking, consider disabling it.

1-9
R2016a

See “Collect and View Line Execution Counts for Your MATLAB Code”.

MATLAB Coder App Undo and Redo: Easily revert changes to type
definitions
In R2016a, you can revert and restore changes to type definitions in the Define
Input Types step of the MATLAB Coder app. Revert and restore changes in the input
arguments table or the global variables table.

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.

1-10
Check Bug Reports for Issues and Fixes

See “Define Keyboard Shortcuts”.

MATLAB Coder App Error Table: View complete error message


In previous releases, the MATLAB Coder app truncated a message that did not fit on one
line of the error message table on the Build Errors tab in the Check for Run-Time
Issues or Generate Code steps. In R2016a, the app displays the entire message.

In previous releases, if a message included a link, the app excluded the link from the
error in the error message table on the Build Errors tab. In R2016a, the app includes
the link.

1-11
R2016a

Changes to Fixed-Point Conversion Code Coverage


If you use the MATLAB Coder app to convert your MATLAB code to fixed-point code
and propose types based on simulation ranges, the app shows code coverage results.
In previous releases, the app showed the coverage as a percentage. In R2016a, the app
shows the coverage as a line execution count.

See “Code Coverage” in “Automated Fixed-Point Conversion”.

Fixed-point conversion requires the Fixed-Point Designer™ software.

1-12
Check Bug Reports for Issues and Fixes

More Keyboard Shortcuts in Code Generation Report: Navigate the


report more easily
In R2016a, you can use keyboard shortcuts to perform the following actions in a code
generation report.

Action Default Keyboard Shortcut for a Windows


Platform
Zoom in Ctrl+Plus
Zoom out Ctrl+Minus
Evaluate selected MATLAB code F9
Open help for selected MATLAB code F1
Open selected MATLAB code Ctrl+D
Step backward through files that you Alt+Left
opened in the code pane
Step forward through files that you opened Alt+Right
in the code pane
Refresh F5
Find Ctrl+F

Your MATLAB preferences define the keyboard shortcuts associated with these actions.
You can also select these actions from a context menu. To open the context menu, right-
click anywhere in the report.

1-13
R2016a

See “Define Keyboard Shortcuts” and “Code Generation Reports”.

xcorr Code Generation: Generate faster code for xcorr with long input
vectors
For long input vectors, code generation for xcorr now uses a frequency-domain
calculation instead of a time-domain calculation. The resulting code can be faster than in
previous releases.

To use the xcorr function, you must have the Signal Processing Toolbox™ software.

Code generation for additional MATLAB functions


Specialized Math in MATLAB

• airy
• besseli
• besselj

Trigonometry in MATLAB

• deg2rad

1-14
Check Bug Reports for Issues and Fixes

• rad2deg

Interpolation and Computational Geometry in MATLAB

• interpn

Changes to code generation support for MATLAB functions


• Code generation now supports the nanflag option for sum, mean, median, min, max,
cov, var, and std.
• Code generation for ismember no longer requires that the second input be sorted.

Code generation for Audio System Toolbox functions and System objects
See “Audio System Toolbox” in “Functions and Objects Supported for C and C++ Code
Generation — Category List”.

Code generation for additional Communications System Toolbox functions


• convenc
• dpskdemod
• dpskmod
• qammod
• qamdemod
• vitdec

See “Communications System Toolbox” in “Functions and Objects Supported for C and C
++ Code Generation — Category List”.

Code generation for additional DSP System Toolbox


• audioDeviceWriter
• dsp.Differentiator
• designMultirateFIR
• dsp.SubbandAnalysisFilter
• dsp.SubbandSynthesisFilter

1-15
R2016a

See “DSP System Toolbox” in “Functions and Objects Supported for C and C++ Code
Generation — Category List”.

Code generation for additional Phased Array System Toolbox functions


• fogpl
• gaspl
• rainpl
• phased.BackscatterRadarTarget
• phased.LOSChannel
• phased.WidebandLOSChannel

See “Phased Array System Toolbox” in “Functions and Objects Supported for C and C++
Code Generation — Category List”.

Code generation for additional Robotics System Toolbox functions


• robotics.ParticleFilter

See “Robotics System Toolbox” in “Functions and Objects Supported for C and C++ Code
Generation — Category List”.

Code generation for WLAN System Toolbox functions and System objects
See “WLAN System Toolbox” in “Functions and Objects Supported for C and C++ Code
Generation — Category List”.

1-16
Check bug reports for issues and fixes

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.

1-17
R2015aSP1
Version: 2.8.1

Bug Fixes
R2015aSP1

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.

2-2
R2015b
Version: 3.0

New Features

Bug Fixes

Compatibility Considerations
R2015b

Cell Array Support: Generate C code from MATLAB code that uses cell
arrays
In R2015b, you can generate code from MATLAB code that uses 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. See Homogeneous vs. Heterogeneous Cell Arrays.

As long as you do not specify conflicting requirements, you can control whether a
cell array is homogeneous or heterogeneous. See Control Whether a Cell Array is
Homogeneous or Heterogeneous.

When you use cell arrays in MATLAB code from which you generate C/C++ code, you
must follow certain restrictions. See Cell Array Requirements and Limitations for Code
Generation.

Faster MEX Functions for Linear Algebra: Generate MEX functions that
take advantage of LAPACK
To improve the speed of the MEX generated for algorithms that call linear algebra
functions, the generated MEX can now call LAPACK functions. If the input arrays for the
linear algebra functions meet certain criteria, MATLAB Coder generates calls to relevant
LAPACK functions.

LAPACK is a software library for numerical linear algebra. MATLAB uses this library in
some linear algebra functions such as eig and svd. MATLAB Coder uses the LAPACK
library that is included with MATLAB.

For information about the open source reference version, see LAPACK — Linear Algebra
PACKage.

Double-Precision to Single-Precision Conversion: Convert double-precision


MATLAB code to single-precision C code
In R2015b, if you have a Fixed-Point Designer license, you can convert double-precision
MATLAB code to single-precision MATLAB code or single-precision C code.

3-2
Check bug reports for issues and fixes

You can develop code for embedded hardware that requires single-precision code without
changing your original MATLAB algorithm. You can verify the single-precision code
using the same test files that you use for your original algorithm. When a double-
precision operation cannot be removed, the code generation report highlights the
MATLAB expression that results in that operation.

You can generate single-precision code in the following ways:

• Generate single-precision C code by using the MATLAB Coder app. See Generate
Single-Precision C Code Using the MATLAB Coder App .
• Generate single-precision C code by using codegen with the -singleC option. See
Generate Single-Precision C Code at the Command Line.
• Generate single-precision MATLAB code by using codegen with a
coder.SingleConfig object. Optionally, you can generate single-precision C code
from the single-precision MATLAB code. See Generate Single-Precision MATLAB
Code.

Run-Time Checks in Standalone C Code: Detect and report run-time errors


while testing generated standalone libraries and executables
In R2015b, generated standalone libraries and executables can detect and report run-
time errors such as out-of-bounds array indexing. In previous releases, only generated
MEX detected and reported run-time errors.

By default, run-time error detection is enabled for MEX. By default, run-time error
detection is disabled for standalone libraries and executables.

To enable run-time error detection for standalone libraries and executables:

• At the command line, use the code configuration property RuntimeChecks.

cfg = coder.config('lib'); % or 'dll' or 'exe'


cfg.RuntimeChecks = true;
codegen -config cfg myfunction
• Using the MATLAB Coder app, in the project build settings, on the Debugging tab,
select the Generate run-time error checks check box.

The generated libraries and executables use fprintf to write error messages to stderr
and abort to terminate the application. If fprintf and abort are not available, you
must provide them. Error messages are in English.

3-3
R2015b

See Run-Time Error Detection and Reporting in Standalone C/C++ Code and Generate
Standalone Code That Detects and Reports Run-Time Errors.

Multicore Capable Functions: Generate OpenMP-enabled C code from


more than twenty MATLAB mathematics functions
For code generation, some MATLAB mathematics functions now use parfor to create
loops that run in parallel on shared-memory multicore platforms. Loops that run in
parallel can be faster than loops that run on a single thread.

Some functions use parfor when the number of elements warrants parallelism. These
functions include interp1, interp2, interp3, and most functions in Specialized Math
in MATLAB. Some functions use parfor when they operate on columns and when the
number of columns to process warrants parallelism. These functions include filter,
median, mode, sort, std, and var.

If your compiler does not support the Open Multiprocessing (OpenMP) application
interface, MATLAB Coder treats the parfor-loops as for-loops. In the generated code,
the loop iterations run on a single thread. See http://www.mathworks.com/support/
compilers/current_release/.

Image Processing Toolbox and Computer Vision System Toolbox Code


Generation: Generate code for additional functions in these toolboxes
Image Processing Toolbox

bwareaopen houghpeaks immse integralBoxFilter


grayconnected imabsdiff imresize psnr
hough imcrop imrotate
houghlines imgaborfilt imtranslate

See Image Processing Toolbox in Functions and Objects Supported for C and C++ Code
Generation — Category List.

Computer Vision System Toolbox

• cameraPose

3-4
Check bug reports for issues and fixes

• detectCheckerboardPoints
• extractLBPFeatures
• generateCheckerboardPoints
• insertText
• opticalFlowFarneback

See Computer Vision System Toolbox in Functions and Objects Supported for C and C++
Code Generation — Category List.

Statistics and Machine Learning Toolbox Code Generation: Generate code


for kmeans and randsample
• kmeans
• randsample

See Statistics and Machine Learning Toolbox in Functions and Objects Supported for C
and C++ Code Generation — Category List.

Simplified hardware specification in the MATLAB Coder app


In R2015b, redesigned dialog boxes simplify the way that you specify hardware settings
on the Generate Code page and on the project build settings Hardware tab. The
redesign consolidates hardware settings, supports use of installed hardware support
packages for processor-in-the-loop (PIL) execution, and hides hardware implementation
details until you want to see them. Use of hardware support packages and PIL execution
with MATLAB Coder requires an Embedded Coder® license.

Here is the redesigned Generate Code page.

3-5
R2015b

Here is the redesigned project build settings Hardware tab.

The changes include:

3-6
Check bug reports for issues and fixes

• Toolchain settings on the Generate Code page and on the project build settings
Hardware tab replace the Toolchain tab.
• The Standard math library and Code replacement library, formerly on the
Hardware tab, are now on the Custom Code tab.
• You can specify the Hardware board instead of the Device vendor and Device
type. The app populates Device vendor and Device type based on the hardware
board. To specify the hardware on which MATLAB is running, select MATLAB Host
Computer. To specify the device vendor and type, select None — Select device
below.

If you have an Embedded Coder license, you can select a board for an installed
hardware support package. For R2015b, the hardware support packages are:

• Embedded Coder Support Package for BeagleBone Black Hardware


• Embedded Coder Support Package for ARM® Cortex®-A Processors

For information about using hardware support packages with MATLAB Coder, see
the Embedded Coder release notes.
• On the Hardware tab, the app hides the hardware implementation details. To
see or modify the hardware implementation details, click Customize hardware
implementation. By default, the test and production hardware implementation
settings are the same. The app shows only one set of settings. To display or modify
the test and production hardware implementation settings separately, on the All
Settings tab, under Hardware, set Test hardware is the same as production
hardware to No.

MATLAB Coder app user interface improvements


Improvements for manual type definition

Improvements for manual type definition include:

• Context menu options to specify array size.

3-7
R2015b

• Easier definition of structure types.

• Use the icon to add fields.


• See the structure type name in the table of input variables.

• Easier definition of embedded.fi types.

• See the numerictype properties in the table of input variables.


Use the icon to change the numerictype properties.

Tab completion for specifying files

You can use tab completion to specify entry-point functions and test files.

Compatibility between the app colors and MATLAB preferences

The app uses colors that are compatible with the Desktop tool colors preference in the
MATLAB preferences. For information about MATLAB preferences, see Preferences.

Progress indicators for the Check for Run-Time Issues step

When you perform the Check for Run-Time Issues step, you can see progress
indicators.

3-8
Check bug reports for issues and fixes

Saving and restoring of workflow state between MATLAB Coder app


sessions
In R2015b, when you complete the Check for Run-Time Issues or Generate Code
steps and close the project, the MATLAB Coder app saves the step results. When you
reopen the project, you do not have to repeat the step. You can continue from where you
left off.

Project reuse between MATLAB Coder and HDL Coder


In R2015b, you can open a MATLAB Coder project in the HDL Coder™ app. You can
open an HDL Coder project in the MATLAB Coder app. You must have an HDL Coder
license to use the HDL Coder app. When you move between apps, the project settings
for both apps are saved. For example, when you open a MATLAB Coder project in the
HDL Coder app, the app uses the settings that are common to both apps. It saves the
settings that it does not use so that if you open the project in the MATLAB Coder app,
those settings are available.

To open a MATLAB Coder project as an HDL Coder project:


In the MATLAB Coder app, click and select Reopen project as HDL Coder.
• In the HDL Coder app, click the Open tab and specify the project.

To open an HDL Coder project as a MATLAB Coder project:

3-9
R2015b


In the HDL Coder app, click and select Reopen in MATLAB Coder.

In the MATLAB Coder app, click and select Open existing project.

Code generation using freely available MinGW-w64 compiler


In R2015b, you can use the MinGW-w64 compiler from TDM-GCC to generate C/C++
MEX, libraries, and executables on a 64-bit Windows host. For installation instructions,
see Install MinGW-w64 Compiler.

When you generate code for C/C++ libraries and executables, you can specify a MinGW
compiler toolchain. If you use the command-line workflow, set the Toolchain property
in a code configuration object for a library or executable:
cfg = coder.config('lib')
cfg.Toolchain = 'MinGW64 v4.x | gmake (64-bit Windows)'

If you use the MATLAB Coder app, in the project build settings, on the Hardware tab,
set Toolchain to MinGW64 v4.x | gmake (64-bit Windows).

codegen debug option for libraries and executables


In R2015b, for lib, dll, and exe targets, you can use the -g option of the codegen
command to enable the compiler debug mode. In previous releases, the -g option enabled
the compiler debug mode for MEX targets only.

If you enable debug mode, the C compiler disables some optimizations. The compilation is
faster, but the execution is slower.

Compatibility Considerations
In R2015b, for lib, dll, and exe targets, the -g option enables the compiler debug
mode. In previous releases, for lib, dll, and exe targets, codegen ignored the -g option.
The compiler generated the same code as when you omitted the -g option.

Code generation for additional MATLAB functions


Data Types in MATLAB

• cell

3-10
Check bug reports for issues and fixes

• fieldnames
• struct2cell

See Data Types in MATLAB in Functions and Objects Supported for C and C++ Code
Generation — Category List.

String Functions in MATLAB

• iscellstr
• strjoin

See String Functions in MATLAB in Functions and Objects Supported for C and C++
Code Generation — Category List.

Code generation for additional Communications System Toolbox, DSP


System Toolbox, and Phased Array System Toolbox System objects
Communications System Toolbox

comm.CoarseFrequencyCompensator

See Communications System Toolbox in Functions and Objects Supported for C and C++
Code Generation — Category List.

DSP System Toolbox

• dsp.IIRHalfbandDecimator
• dsp.IIRHalfbandInterpolator
• dsp.AllpassFilter

See DSP System Toolbox in Functions and Objects Supported for C and C++ Code
Generation — Category List.

Phased Array System Toolbox

• phased.TwoRayChannel
• phased.GCCEstimator
• phased.WidebandRadiator
• phased.SubbandMVDRBeamformer
• phased.WidebandFreeSpace

3-11
R2015b

• gccphat

See Phased Array System Toolbox in Functions and Objects Supported for C and C++
Code Generation — Category List.

Code generation for Robotics System Toolbox functions and System


objects
See Robotics System Toolbox in Functions and Objects Supported for C and C++ Code
Generation — Category List.

Code generation for System Identification Toolbox functions and System


objects
See System Identification Toolbox in Functions and Objects Supported for C and C++
Code Generation — Category List.

Fixed-Point Conversion Enhancements


Saving and restoring fixed-point conversion workflow state in the app

If you close a project before completing the fixed-point conversion process, the app saves
your work. When you reopen the project, the app restores the state. You do not have to
repeat the fixed-point conversion steps that you completed in a previous session. For
example, suppose that you close the project after data type proposal. When you reopen
the project, the app shows the results of the data type proposal and enables conversion.
You can continue where you left off.

Reuse of MEX files during fixed-point conversion using the app

During fixed-point conversion, the app minimizes the number of times that it regenerates
MEX files. The app rebuilds the MEX files only when required by changes in your code.

Specification of additional fimath properties in app editor

You can control all fimath properties of variables in your code from within the app
editor. To modify the fimath settings of a variable, select a variable and click FIMATH
in the dialog box. You can alter the Rounding method, Overflow action, Product mode,
and Sum mode properties. For more information on these properties, see fimath.

3-12
Check bug reports for issues and fixes

You can also modify these properties from the fixed-point conversion settings dialog box.
To open the settings dialog box, on the Convert to Fixed Point page, click the Settings
arrow .

Improved management of comparison plots

During fixed-point conversion, the app docks plots that are generated during the testing
phase of your fixed-point code into separate tabs of one figure window. Each tabbed
figure represents one input or output variable and is labeled with the function, variable,
word length, and a timestamp. Each tab contains three subplots. The plots use a time
series-based plotting function to show the floating-point and fixed-point results and the
difference between them.

Subsequent iterations are also plotted in the same figure window.

3-13
R2015b

Variable specializations

On the Convert to Fixed Point page of the app, in the Variables table, you can view
variable specializations.

3-14
Check bug reports for issues and fixes

Detection of multiword operations

When an operation has an input or output larger than the largest word size of your
processor, the generated code contains multiword operations. Multiword operations can
be inefficient on hardware. The expensive fixed-point operations check now highlights
expressions in your MATLAB code that can result in multiword operations in generated
code.

3-15
R2015b

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.

3-16
R2015a
Version: 2.8

New Features

Bug Fixes

Compatibility Considerations
R2015a

Improved MATLAB Coder app with integrated editor and simplified


workflow
In R2015a, the MATLAB Coder app has a new user interface for the code generation
workflow.

The improved app includes:

• Automatic checks for code generation readiness and run-time issues. The code
generation readiness checks include identification of unsupported functions.
• An integrated editor to fix issues in your MATLAB code without leaving the app.
• A project summary and access to generated files.
• Export of project settings in the form of a MATLAB script.
• Help for each step and links to documentation for more information.

4-2
Check bug reports for issues and fixes

See C Code Generation Using the MATLAB Coder App.

Generation of example C/C++ main for integration of generated code


into an application
In R2015a, you can generate an example C/C++ main function when generating source
code, a static library, a dynamic library, or an executable. You modify the example main
function to meet the requirements of your application.

An example main function provides a template that helps you incorporate generated code
into your application. The template shows how to initialize function input arguments to
zero and call entry-point functions. Generating an example main function is especially
useful when the code uses dynamic memory allocation for data. See Use an Example C
Main in an Application.

By default, MATLAB Coder generates an example main function when generating source
code, a static library, a dynamic library, or an executable.

To control generation of an example main function using the MATLAB Coder app:

1 On the Generate Code page, to open the Generate dialog box, click the Generate
arrow .
2 In the Generate dialog box, set Build type to one of the following:

• Source Code
• Static Library (.lib)
• Dynamic Library (.dll)
• Executable (.exe)
3 Click More Settings.
4 On the All Settings tab, under Advanced, set Generate example main to one of
the following:

• Do not generate an example main function


• Generate, but do not compile, an example main function (default)
• Generate and compile an example main function

To control generation of an example main function using the command-line interface:

4-3
R2015a

1 Create a code configuration object for 'lib', 'dll', or 'exe'. For example:
cfg = coder.config('lib'); % or dll or exe
2 Set the GenerateExampleMain property to one of the following:

• 'DoNotGenerate'
• 'GenerateCodeOnly' (default)
• 'GenerateCodeAndCompile'

For example:
cfg.GenerateExampleMain = 'GenerateCodeOnly';

Better preservation of MATLAB variable names in generated code


To reduce memory usage, when possible, variables share names and memory in the
generated code. In previous releases, this variable reuse optimization reused your
variable names for other variables or replaced your variable names with the names of
other variables. In R2015a, by default, this optimization preserves your variable names
—it does not replace or reuse them. Other optimizations, however, can remove your
variable names from the generated code. See Variable Reuse in Generated Code.

Compatibility Considerations
If your MATLAB code uses large arrays or structures, in some cases, the extra memory to
preserve your variable names can affect performance. To reduce memory usage, specify
that the variable reuse optimization does not have to preserve variable names:

• Using a project, in the Project Settings dialog box, on the All Settings tab, set
Preserve variable names to None.
• Using the command-line interface, set the configuration object property
PreserveVariableNames to None.

See Reuse Large Arrays and Structures.

More efficient generated code for logical indexing


Code generated for logical array indexing is faster and uses less memory than in previous
releases. For example, the generated code for the following function is more efficient than
in previous releases.

4-4
Check bug reports for issues and fixes

function x = foo(x,N)
assert(all(size(x) == [1 100]))
x(x>N) = N;

In R2015a, you do not have to replace x(x>N) = N with a for-loop to improve


performance.

Code generation for additional Image Processing Toolbox and Computer


Vision System Toolbox functions
Image Processing Toolbox

• bweuler
• bwlabel
• bwperim
• regionprops
• watershed

See Image Processing in MATLAB.

Computer Vision System Toolbox

• cameraMatrix
• cameraParameters
• extrinsics
• opticalFlow
• opticalFlowHS
• opticalFlowLK
• opticalFlowLKDoG
• reconstructScene
• rectifyStereoImages
• stereoParameters
• triangulate
• undistortImage

4-5
R2015a

• vision.DeployableVideoPlayer on Mac platform.

In previous releases, vision.DeployableVideoPlayer supported code generation


on Linux® and Windows platforms. In R2015a, vision.DeployableVideoPlayer
also supports code generation on a Mac platform.

See Computer Vision System Toolbox.

Code generation for additional Communications System Toolbox, DSP


System Toolbox, and Phased Array System Toolbox System objects
Communications System Toolbox

• comm.CarrierSynchronizer
• comm.FMBroadcastDemodulator
• comm.FMBroadcastModulator
• comm.FMDemodulator
• comm.FMModulator
• comm.SymbolSynchronizer

See Communications System Toolbox.

DSP System Toolbox

• iirparameq
• dsp.HighpassFilter
• dsp.LowpassFilter

See DSP System Toolbox.

Phased Array System Toolbox

• pilotcalib
• phased.UCA
• phased.MFSKWaveform

See Phased Array System Toolbox

4-6
Check bug reports for issues and fixes

Code generation for additional Statistics and Machine Learning Toolbox


functions
• betafit
• betalike
• pca
• pearsrnd

See Statistics and Machine Learning Toolbox.

Code generation for additional MATLAB functions


Linear Algebra

• bandwidth
• isbanded
• isdiag
• istril
• istriu
• lsqnonneg

See Linear Algebra in MATLAB.

Statistics in MATLAB

• cummin
• cummax

See Statistics in MATLAB

Code generation for additional MATLAB function options


• dimension option for cumsum and cumprod

See Functions and Objects Supported for C and C++ Code Generation — Alphabetical
List.

4-7
R2015a

Conversion from project to MATLAB script using MATLAB Coder app


In previous releases, to convert a project to a MATLAB script, you used the -tocode
option of the coder command. In R2015a, you can also use the MATLAB Coder app to
convert a project to a script. Before you convert a project to a script, complete the Define
Input Types step.

To convert a project to a script using the MATLAB Coder app, on the workflow bar, click

, and then select Convert to script.

See Convert MATLAB Coder Project to MATLAB Script.

Improved recognition of compile-time constants


In previous releases, the code generation software recognized that structure fields or
array elements were constant only when all fields or elements were constant. In R2015a,
in some cases, the software can recognize constant fields or constant elements even when
some structure fields or array elements are not constant.

For example, consider the following code. Field s.a is constant and field s.b is not
constant:
function y = create_array(x)
s.a = 10;
s.b = x;
y = zeros(1, s.a);

In previous releases, the software did not recognize that field s.a was constant. In the
generated code, if variable-sizing was enabled, y was a variable-size array. If variable-
sizing was disabled, the code generation software reported an error. In R2015a, the
software recognizes that s.a is a constant. y is a static row vector with 10 elements.

As a result of this improvement, you can use individual assignments to assign constant
values to structure fields. For example:
function y = mystruct(x)
s.a = 3;
s.b = 4;
y = zeros(s.a,s.b);

In previous releases, the software recognized the constants only if you defined the
complete structure using the struct function: For example:

4-8
Check bug reports for issues and fixes

function y = mystruct(x)
s = struct('a', 3, 'b', 4);
y = zeros(s.a,s.b);

In some cases, the code generation software cannot recognize constant structure fields or
array elements. See Code Generation for Constants in Structures and Arrays.

Compatibility Considerations
The improved recognition of constant fields and elements can cause the following
differences between code generated in R2015a and code generated in previous releases:

• A function output can be more specific in R2015a than it was in previous releases. An
output that was complex in previous releases can be real in R2015a. An array output
that was variable-size in previous releases can be fixed-size in R2015a.
• Some branches of code that are present in code generated using previous releases are
eliminated from the generated code in R2015a.

Improved emxArray interface function generation


When you generate code that uses variable-size data, MATLAB Coder exports functions
that you can use to create and interact with emxArrays in your generated code. R2015a
includes the following improvements to emxArray interface functions:

emxArray interface functions for variable-size arrays that external C/C++ functions use

When you use coder.ceval to call an external C/C++ function, MATLAB Coder
generates emxArray interface functions for the variable-size arrays that the external
function uses.

Functions to initialize output emxArrays and emxArrays in structure outputs

MATLAB Coder generates functions to initialize emxArrays that are outputs or


emxArrays that are in structure outputs.

A function that creates an empty emxArray on the heap has a name of the form:

emxInitArray_<baseType>

<baseType> is the type of the elements of the emxArray. The inputs to this function are
a pointer to an emxArray pointer and the number of dimensions. For example:

4-9
R2015a

void emxInitArray_real_T(emxArray_real_T **pEmxArray, int numDimensions);

A function that creates empty emxArrays in a structure has a name of the form:

void emxInitArray_<structType>

<structType> is the type of the structure. The input to this function is a pointer to the
structure that contains the emxArrays. For example:

void emxInitArray_cstruct0_T(cstruct0_T *structure);

MATLAB Coder also generates functions that free the dynamic memory that the
functions that create the emxArrays allocate. For example, the function that frees
dynamic memory that emxInitArray_real_T allocates is:

void emxDestroyArray_real_T(emxArray_real_T *emxArray)

The function that frees dynamic memory that emxInitArray_cstruct0_T allocates is:

void emxDestroyArray_struct0_T(struct0_T *structure)

See C Code Interface for Arrays.

External definition of a structure that contains emxArrays

In previous releases, MATLAB Coder did not allow external definition of a structure
that contained emxArrays. If you defined the structure in C code and declared it in an
external header file, MATLAB Coder reported an error.

In R2015a, MATLAB Coder allows external definition of a structure that contains


emxArrays. However, do not define the type of the emxArray in the external C code.
MATLAB Coder defines the types of the emxArrays that a structure contains.

Code generation for casts to and from types of variables declared using
coder.opaque
For code generation, you can use the MATLAB cast function to cast a variable to or from
a variable that is declared using coder.opaque. Use cast with coder.opaque only for
numeric types.

To cast a variable declared by coder.opaque to a MATLAB type, you can use the B =
cast(A,type) syntax. For example:

4-10
Check bug reports for issues and fixes

x = coder.opaque('size_t','0');
x1 = cast(x, 'int32');

You can also use the B = cast(A,'like',p) syntax. For example:

x = coder.opaque('size_t','0');
x1 = cast(x, 'like', int32(0));

To cast a MATLAB variable to the type of a variable declared by coder.opaque, you


must use the B = cast(A,'like',p) syntax. For example:

x = int32(12);
x1 = coder.opaque('size_t', '0');
x2 = cast(x, 'like', x1));

Use cast with coder.opaque to generate the correct data types for:

• Inputs to C/C++ functions that you call using coder.ceval.


• Variables that you assign to outputs from C/C++ functions that you call using
coder.ceval.

Without this casting, it is possible to receive compiler warnings during code generation.

Consider this MATLAB code:

yt = coder.opaque('size_t', '42');
yt = coder.ceval('foo');
y = cast(yt, 'int32');

• coder.opaque declares that yt has C type size_t.


• y = cast(yt, 'int32') converts yt to int32 and assigns the result to y.

Because y is a MATLAB numeric type, you can use y as you would normally use a
variable in your MATLAB code.

The generated code looks like:

size_t yt= 42;


int32_T y;
y = (int32_T)yt;

It is possible that the explicit cast in the generated code prevents a compiler warning.

4-11
R2015a

Generation of reentrant code without an Embedded Coder license


In previous releases, generation of reentrant code required an Embedded Coder license.
In R2015a, you can generate reentrant code using MATLAB Coder without an Embedded
Coder license.

See Reentrant Code.

Code generation for parfor-loops with stack overflow


In previous releases, you could not generate code for parfor-loops that contained
variables that did not fit on the stack. In R2015a, you can generate code for these
parfor-loops. See Algorithm Acceleration Using Parallel for-Loops (parfor).

Change in default value of the PassStructByReference code


configuration object property
The PassStructByReference code configuration object property controls whether the
codegen command generates pass by reference or pass by value structures for entry-
point input and output structures.

In previous releases, the default value of PassStructByReference was false. By


default, codegen generated pass by value structures. This default behavior differed
from the MATLAB Coder app default behavior. The app generated pass by reference
structures.

In R2015a, the value of PassStructByReference is true. By default, codegen


generates pass by reference structures. The default behavior now matches the default
behavior of the MATLAB Coder app.

See Pass Structure Arguments by Reference or by Value.

Compatibility Considerations
For an entry-point function with structure arguments, if the PassStructByReference
property has the default value, codegen generates a different function signature in
R2015a than in previous releases.

Here is an example of a function signature generated in R2015a using the codegen


command with the PassStructByReference property set to the default value, true:

4-12
Check bug reports for issues and fixes

void my_struct_in(const struct0_T *s, double y[4])

my_struct_in passes the input structure s by reference.

The signature for the same function generated in previous releases, using the codegen
command with the PassStructByReference property set to the default value, false
is:

void my_struct_in(const struct0_T s, double y[4])

my_struct_in passes the input structure s by value.

To control whether codegen generates pass by reference or pass by value structures,


set the PassStructByReference code configuration object property. For example, to
generate pass by value structures:

cfg = coder.config('lib');
cfg.PassStructByReference = false;

Change in GLOBALS variable in scripts generated from a project


A script generated from a MATLAB Coder project that uses global variables creates the
variable GLOBALS. In previous releases, GLOBALS stored the types of global variables.
The initial values of the global variables were specified directly in the codegen
command. In R2015a, GLOBALS stores both the types and the initial values of global
variables. The codegen command obtains the initial values from GLOBALS.

See Convert MATLAB Coder Project to MATLAB Script.

Target build log display for command-line code generation when


hyperlinks disabled
In previous releases, if hyperlinks were disabled, you could not access the code
generation report to view compiler or linker messages in the target build log. In R2015a,
when hyperlinks are disabled, you see the target build log in the Command Window.

If you use the -nojvm startup option when you start MATLAB, hyperlinks are disabled.
See Commonly Used Startup Options.

For more information about the target build log, see View Target Build Information.

4-13
R2015a

Removal of instrumented MEX output type


You can no longer specify the output type Instrumented MEX.

Compatibility Considerations
For manual fixed-point conversion, use the command-line workflow. This
workflow uses the Fixed-Point Designer functions buildInstrumentedMex and
showInstrumentationResults. See Manually Convert a Floating-Point MATLAB
Algorithm to Fixed Point in the Fixed-Point Designer documentation.

Truncation of long enumerated type value names that include the class
name prefix
In previous releases, when the code generation software determined the length or
uniqueness of a generated enumerated type value name, it ignored the class name prefix.
If you specified that a generated enumerated type value name included the class name
prefix, it is possible that the generated type value name:

• Exceeded the maximum identifier length that you specified.


• Was the same as another identifier.

In R2015a, if you specify that a generated enumerated type value name includes the
class name prefix, the generated type value name:

• Does not exceed the maximum identifier length.


• Is unique.

Compatibility Considerations
For a long type value name that includes the class name prefix, the name generated in
previous releases can be different from the name generated in R2015a. For example,
consider the enumerated type:

classdef Colors < int32


enumeration
Red (1)
Green678911234567892123456789312 (2)
end

4-14
Check bug reports for issues and fixes

methods (Static)
function p = addClassNameToEnumNames()
p = true;
end
end
end

Suppose that the maximum identifier length is the default


value, 31. In previous releases, the generated name for the
enumerated value Green678911234567892123456789312 was
Colors_Green678911234567892123456789312. The length of the name exceeded
31 characters. In R2015a, the truncated name is 31 characters. Assuming that
the generated name does not clash with another name, the name in R2015a is
Colors_Green6789112345678921234. External code that uses the long name
generated in the previous release cannot interface with the code generated in R2015a.

To resolve this issue, if possible, increase the maximum identifier length:

• At the command line, set MaxIdLength.


• In the MATLAB Coder app, in the project build settings, on the Code Appearance
tab, set Maximum identifier length.

Fixed-point conversion enhancements


Support for multiple entry-point functions

Fixed-point conversion now supports multiple entry-point functions. You can generate C/
C++ library functions to integrate with larger applications.

Support for global variables

You can now convert MATLAB algorithms that contain global variables to fixed-point
code without modifying your MATLAB code.

Code coverage-based translation

During fixed-point conversion, MATLAB Coder now detects dead and constant folded
code. It warns you if any parts of your code do not execute during the simulation of your
test file. This detection can help you verify if your test file is testing the algorithm over
the intended operating range. The software uses this code coverage information during
the translation of your code from floating-point MATLAB code to fixed-point MATLAB

4-15
R2015a

code. The software 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.

Generated fixed-point code enhancements

The generated fixed-point code now:

• Uses colon syntax for multi-output assignments, reducing the number of fi casts in
the generated fixed-point code.
• Preserves the indentation and formatting of your original algorithm, improving the
readability of the generated fixed-point code.

Automated fixed-point conversion of additional DSP System Toolbox objects

If you have a DSP System Toolbox™ license, you can now convert the following DSP
System Toolbox System objects to fixed-point:

• dsp.FIRDecimator
• dsp.FIRInterpolator
• dsp.FIRFilter, direct form and direct form transposed only
• dsp.LUFactor
• dsp.VariableFractionalDelay
• dsp.Window

You can propose and apply data types for these System objects based on simulation
range data. Using the MATLAB Coder app, during the conversion process, you can view
simulation minimum and maximum values and proposed data types for these System
objects. You can also view whole number information and histogram data. You cannot
propose data types for these System objects based on static range data.

New interpolation method for generating lookup table MATLAB function replacements

The coder.approximation function now offers a 'Flat' interpolation method for


generating lookup table MATLAB function replacements. This fully specified lookup
table achieves high speeds by discarding the prelookup step and reducing the use of
multipliers in the data path. This interpolation method is available from the command-
line workflow, and in the Function Replacements tab of the Fixed-Point Conversion
step.

4-16
Check bug reports for issues and fixes

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.

4-17
R2014b
Version: 2.7

New Features

Bug Fixes

Compatibility Considerations
R2014b

Code generation for additional Image Processing Toolbox and Computer


Vision System Toolbox functions
Image Processing Toolbox

bwdist imadjust intlut ordfilt2


bwtraceboundary imclearborder iptcheckmap rgb2ycbcr
fitgeotrans imlincomb medfilt2 stretchlim
histeq imquantize multithresh ycbcr2rgb

For the list of Image Processing Toolbox functions supported for code generation, see
Image Processing Toolbox.

Computer Vision System Toolbox

• bboxOverlapRatio
• selectStrongestBbox
• vision.DeployableVideoPlayer on Linux

For the list of Computer Vision System Toolbox functions supported for code generation,
see Computer Vision System Toolbox.

Code generation for additional Communications System Toolbox and DSP


System Toolbox functions and System objects
Communications System Toolbox

• iqcoef2imbal
• iqimbal2coef
• comm.IQImbalanceCompensator

For the list of Communications System Toolbox™ functions supported for code
generation, see Communications System Toolbox.

DSP System Toolbox

• dsp.CICCompensationDecimator
• dsp.CICCompensationInterpolator

5-2
Check bug reports for issues and fixes

• dsp.FarrowRateConverter
• dsp.FilterCascade

You cannot generate code directly from this System object™. You can use the
generateFilteringCode method to generate a MATLAB function. You can
generate C/C++ code from this MATLAB function.
• dsp.FIRDecimator for transposed structure
• dsp.FIRHalfbandDecimator
• dsp.FIRHalfbandInterpolator
• dsp.PeakToPeak
• dsp.PeakToRMS
• dsp.PhaseExtractor
• dsp.SampleRateConverter
• dsp.StateLevels

For the list of DSP System Toolbox functions and System objects supported for code
generation, see DSP System Toolbox.

Code generation for enumerated types based on built-in MATLAB integer


types
In previous releases, enumeration types were based on int32. In R2014b, you can base
an enumerated type on one of the following built-in MATLAB integer data types:

• int8
• uint8
• int16
• uint16
• int32

You can use the base type to control the size of the enumerated type in the generated
code. You can choose a base type to:

• Represent an enumerated type as a fixed-size integer that is portable to different


targets.
• Reduce memory usage.

5-3
R2014b

• Interface to legacy code.


• Match company standards.

The base type determines the representation of the enumerated types in the generated
C and C++ code. For the base type int32, the code generation software generates a C
enumeration type. For example:

enum LEDcolor
{
GREEN = 1,
RED
};

typedef enum LEDcolor LEDcolor;


For the other base types, the code generation software generates a typedef statement
for the enumerated type and #define statements for the enumerated values. For
example:

typedef short LEDColor;


#define GREEN ((LEDColor)1)
#define RED((LEDColor)2)

See Enumerated Types Supported for Code Generation.

Code generation for function handles in structures


You can now generate code for structures containing fields that are function handles. See
Function Handle Definition for Code Generation.

Change in enumerated type value names in generated code


In previous releases, by default, the enumerated type value name in the generated code
included a class name prefix, for example, LEDcolor_GREEN. In R2014b, by default,
the generated enumerated type value name does not include the class name prefix.
To generate enumerated type value names that include the class name prefix, in the
enumerated type definition, modify the addClassNameToEnumNames method to return
true instead of false:

classdef(Enumeration) LEDcolor < int32


enumeration
GREEN(1),

5-4
Check bug reports for issues and fixes

RED(2)
end

methods(Static)
function y = addClassNameToEnumNames()
y = true;
end
end
end

See Control Names of Enumerated Type Values in Generated Code.

Compatibility Considerations
The name of an enumerated type value in code generated using previous releases differs
from the name generated using R2014b. If you have code that uses one of these names,
modify the code to use the R2014b name or generate the name so that it matches the
name from a previous release. If you want an enumerated type value name generated in
R2014b to match the name from a previous release, in the enumerated types definition,
modify the addClassNameToEnumNames method to return true instead of false.

Code generation for ode23 and ode45 ordinary differential equation


solvers
• ode23
• ode45
• odeget
• odeset

See Numerical Integration and Differentiation in MATLAB.

Code generation for additional MATLAB functions


Data and File Management in MATLAB

• feof
• frewind

See Data and File Management in MATLAB.

5-5
R2014b

Linear Algebra in MATLAB

• ishermitian
• issymmetric

See Linear Algebra in MATLAB.

String Functions in MATLAB

str2double

See String Functions in MATLAB.

Code generation for additional MATLAB function options


• 'vector' and 'matrix' eigenvalue options for eig
• All output class options for sum and prod
• All output class options for mean except 'native' for integer types
• Multidimensional array support for flipud, fliplr, and rot90
• Dimension to operate along option for circshift

See Functions and Objects Supported for C and C++ Code Generation — Alphabetical
List.

Collapsed list for inherited properties in code generation report


The code generation report displays inherited object properties on the Variables tab. In
R2014b, the list of inherited properties is collapsed by default.

Change in length of exported identifiers


In previous releases, the code generation software limited exported identifiers, such as
entry-point function names or emxArray utility function names, to a maximum length
defined by the maximum identifier length setting. If the truncation of identifiers resulted
in different functions having identical names, the code generation failed. In R2014b, for
exported identifiers, the code generation software uses the entire generated identifier,
even if its length exceeds the maximum identifier length setting. If, however, the target
C compiler has a maximum identifier length that is less than the length of the generated
identifier, the target C compiler truncates the identifier.

5-6
Check bug reports for issues and fixes

Compatibility Considerations
Unless the target C compiler has a maximum identifier length that equals the length of
a truncated exported identifier from a previous release, the identifier from the previous
release does not match the identifier that R2014b generates. For example, suppose the
maximum identifier length setting has the default value 31 and the target C compiler
has a maximum identifier length of 255. Suppose that in R2014b, the code generation
software generates the function emxCreateWrapperND_StructType_123 for an
unbounded variable-size structure array named StructType_123. In previous releases,
the same function had the truncated name emxCreateWrapperND_StructType_1. In
this example, code that previously called emxCreateWrapperND_StructType_1 must
now call emxCreateWrapperND_StructType_123.

Intel Performance Primitives (IPP) platform-specific code replacement


libraries for cross-platform code generation
In R2014b, you can select an Intel® Performance Primitive (IPP) code replacement
library for a specific platform. You can generate code for a platform that is different from
the host platform that you use for code generation. The new code replacement libraries
are:

• Intel IPP for x86-64 (Windows)


• Intel IPP/SSE with GNU99 extensions for x86-64 (Windows)
• Intel IPP for x86/Pentium (Windows)
• Intel IPP/SSE with GNU99 extensions for x86/Pentium (Windows)
• Intel IPP for x86-64 (Linux)
• Intel IPP/SSE with GNU99 extensions for x86-64 (Linux)

In a MATLAB Coder project that you create in R2014b, you can no longer select these
libraries:

• Intel IPP
• Intel IPP/SSE with GNU99 extensions

If, however, you open a project from a previous release that specifies Intel IPP or Intel
IPP/SSE with GNU99 extensions, the library selection is preserved and that library
appears in the selection list.

See Choose a Code Replacement Library.

5-7
R2014b

Fixed-point conversion enhancements


Conversion from project to MATLAB scripts for command-line fixed-point conversion and code
generation

For a MATLAB Coder project that 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 Numerics step of the fixed-point conversion process.

For example:
coder -tocode my_fixpt_proj -script myscript.m

This command generates two scripts:

• myscript.m contains the MATLAB commands to create a code configuration


object and generate fixed-point C code from fixed-point MATLAB code. The code
configuration object has the same settings as the project.
• myscriptsuffix.m contains the MATLAB commands to create a floating-point to
fixed-point configuration object and generate fixed-point MATLAB code from the
entry-point function. The floating-point to fixed-point configuration object has the
same fixed-point conversion settings as the project. suffix is the generated fixed-
point file name suffix specified by the project file.

If you do not specify the -script option, coder writes the scripts to the Command
Window.

See Convert Fixed-Point Conversion Project to MATLAB Scripts.

Lookup table approximations for unsupported functions

The Fixed-Point Conversion tool now provides an option to generate lookup table
approximations for continuous and stateless functions in your original MATLAB code.
This capability is useful for handling functions that are not supported for fixed point. To
replace a function with a generated lookup table, specify the function that you want to
replace on the Function Replacements tab.

In the command-line workflow, use coder.approximation and the coder.FixptConfig


configuration object addApproximation method.

5-8
Check bug reports for issues and fixes

See Replacing Functions Using Lookup Table Approximations.

Enhanced plotting capabilities

The Fixed-Point Conversion tool now provides additional plotting capabilities. You can
use these plotting capabilities during the testing phase to compare the generated fixed-
point versions of your algorithms to the original floating-point versions.
Default plots

The default comparison plots now plot vector and matrix data in addition to scalar data.
Custom plotting functions

You can now specify your own custom plotting function. The Fixed-Point Conversion
tool calls the function and, for each 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.
• A cell array to hold the logged floating-point values for the variable.
• A cell array to hold the logged values for the variable after fixed-point conversion.

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.

In the command-line workflow, set the coder.FixptConfig configuration object


PlotFunction property to the name of your plot function.

See Custom Plot Functions.


Integration with Simulation Data Inspector

You can now use the Simulation Data Inspector for comparison plots. The Simulation
Data Inspector provides the capability to inspect and compare logged simulation data for
multiple runs. You can import and export logged data, customize the organization of your
logged data, and create reports.

In the Fixed-Point Conversion tool, select Advanced and then set Plot with
Simulation Data Inspector to Yes. See Enable Plotting Using the Simulation Data
Inspector.

5-9
R2014b

When generating fixed-point code in the command-line workflow, set the


coder.FixptConfig configuration object PlotWithSimulationDataInspector property
to true.

Custom plotting functions take precedence over the Simulation Data Inspector. See
Enable Plotting Using the Simulation Data Inspector.

Automated fixed-point conversion for commonly used System objects in MATLAB including
Biquad Filter, FIR Filter, and Rate converter

You can now convert the following DSP System Toolbox System objects to fixed point
using the Fixed-Point Conversion tool.

• dsp.BiquadFilter
• dsp.FIRFilter, Direct Form only
• dsp.FIRRateConverter
• dsp.LowerTriangularSolver
• dsp.UpperTriangularSolver
• dsp.ArrayVectorAdder

You can propose and apply data types for these System objects based on simulation
range data. During the conversion process, you can view simulation minimum and
maximum values and proposed data types for these System objects. You can also view
Whole Number information and histogram data. You cannot propose data types for these
System objects based on static range data.

Additional fixed-point conversion command-line options

You can now use the codegen function with the -float2fixed option to convert
floating point to fixed point based on derived ranges as well as simulation ranges. For
more information, see coder.FixptConfig.

Type proposal report

After running the Test Numerics step to verify the data type proposals, the tool provides
a link to a type proposal report that shows the instrumentation results for the fixed-point
simulation. This report includes:

• The fixed-point code generated for each function in your original MATLAB algorithm
• Fixed-point instrumentation results for each variable in these functions:

• Simulation minimum value

5-10
Check bug reports for issues and fixes

• Simulation maximum value


• Proposed data type

Generated fixed-point code enhancements

The generated fixed-point code now:

• Avoids 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.
• Handles multiplication of fixed-point variables by non fixed-point variables. In
previous releases, the variable that did not have a fixed-point type had to be a
constant.
• Avoids overflows when adding and subtracting non fixed-point variables and fixed-
point variables.
• Avoids loss of range when concatenating arrays of fixed-point numbers using
vertcat and horzcat.

If you concatenate matrices, the conversion tool 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.
• If the function that you are converting has a scalar input, and the mpower
exponent input is not constant, the conversion tool sets fimath ProductMode to
SpecifyPrecision in the generated code. With this setting , the output data type
can be determined at compile time.
• Supports the following functions:

• true(m,n)
• false(m,n)
• sub2ind
• mode
• rem
• Uses enhanced division replacement.

For more information, see Generated Fixed-Point Code.

The tool now numbers function specializations sequentially in the Function list. In the
generated fixed-point code, the number of each fixed-point specialization matches the

5-11
R2014b

number in the Function 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 the
specialization of function foo named foo > 1 is named foo_s1. For more information,
see Specializations.

Highlighting of potential data type issues in generated HTML report


You now have the option to highlight potential data type issues in the generated HTML
report. The report highlights MATLAB code that requires single-precision, double-
precision, or 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, or expensive
rounding. The following example report highlights MATLAB code that requires expensive
fixed-point operations.

5-12
Check bug reports for issues and fixes

The checks for the data type issues are disabled by default.

To enable the checks in a project:

1 In the Fixed-Point Conversion Tool, click Advanced to view the advanced settings.
2 Set Highlight potential data type issues to Yes.

To enable the checks at the command-line interface:

1 Create a floating-point to fixed-point conversion configuration object:


fxptcfg = coder.config('fixpt');
2 Set the HighlightPotentialDataTypeIssues property to true:

fxptcfg.HighlightPotentialDataTypeIssues = true;

See Data Type Issues in Generated Code.

5-13
R2014b

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.

5-14
R2014a
Version: 2.6

New Features

Bug Fixes

Compatibility Considerations
R2014a

Code generation for additional Image Processing Toolbox and Computer


Vision System Toolbox functions
Image Processing Toolbox

affine2d im2uint16 imhist


bwpack im2uint8 imopen
bwselect imbothat imref2d
bwunpack imclose imref3d
edge imdilate imtophat
getrangefromclass imerode imwarp
im2double imextendedmax mean2
im2int16 imextendedmin projective2d
im2single imfilter strel

See Image Processing Toolbox.

Computer Vision System Toolbox

• detectHarrisFeatures
• detectMinEigenFeatures
• estimateGeometricTransform

See Computer Vision System Toolbox.

Code generation for additional Signal Processing Toolbox,


Communications System Toolbox, and DSP System Toolbox functions and
System objects
Signal Processing Toolbox

• findpeaks
• db2pow
• pow2db

See Signal Processing Toolbox.

6-2
Check bug reports for issues and fixes

Communications System Toolbox

• comm.OFDMModulator
• comm.OFDMDemodulator

See Communications System Toolbox.

DSP System Toolbox

ca2tf firhalfband ifir iirnotch


cl2tf firlpnorm iircomb iirpeak
firceqrip firminphase iirgrpdelay tf2ca
fireqint firnyquist iirlpnorm tf2cl
firgr firpr2chfb iirlpnormc dsp.DCBlocker

See DSP System Toolbox.

Code generation for fminsearch optimization function and additional


interpolation functions in MATLAB
Optimization Functions in MATLAB

• fminsearch
• optimget
• optimset

See Optimization Functions in MATLAB.

Interpolation and Computational Geometry in MATLAB

• interp3
• mkpp
• pchip
• ppval
• spline
• unmkpp
• 'spline’ and 'v5cubic’ interpolation methods for interp1
• 'spline’ and 'cubic’ interpolation methods for interp2

6-3
R2014a

See Interpolation and Computational Geometry in MATLAB.

Conversion from project to MATLAB script for command-line code


generation
Using the -tocode option of the coder command, you can convert a MATLAB Coder
project to the equivalent MATLAB code in a MATLAB script. The script reproduces the
project in a configuration object and runs the codegen command. With this capability,
you can:

• Move from a project workflow to a command-line workflow.


• Save the project as a text file that you can share.

The following command converts the project named myproject to the script named
myscript.m:
coder -tocode myproject -script myscript.m

If you omit the -script option, the coder command writes the script to the Command
Window.

See Convert MATLAB Coder Project to MATLAB Script.

Code generation for fread function


In R2014a, you can generate code for the fread function.

See Data and File Management in MATLAB.

Automatic C/C++ compiler setup


Previously, you used mex -setup to set up a compiler for C/C++ code generation. In
R2014a, the code generation software locates and uses a supported installed compiler.
You can use mex -setup to change the default compiler. See Changing Default
Compiler.

Compile-time declaration of constant global variables


You can specify that a global variable is a compile-time constant. Use a constant global
variable to:

6-4
Check bug reports for issues and fixes

• Generate optimized code.


• Define the value of a constant without changing source code.

To declare a constant global variable in a MATLAB Coder project:

1 On the Overview tab, click Add global. Enter a name for the global variable.
2 Click the field to the right of the global variable name.
3 Select Define Constant Value.
4 Enter the value in the field to the right of the global variable name.

To declare a constant global variable at the command-line interface, use the -globals
option along with the coder.Constant function.

In the following code, gConstant is a global variable with constant value 42.

cfg = coder.config('mex');
globals = {'gConstant', coder.Constant(42)};
codegen -config cfg myfunction -globals globals

See Define Constant Global Data.

Enhanced code generation support for switch statements


Code generation now supports:

• Switch expressions and case expressions that are noninteger numbers, nonconstant
strings, variable-size strings, or empty matrices
• Case expressions with mixed types and sizes

If all case expressions are scalar integer values, the code generation software generates
a C switch statement. If at run time, the switch value is not an integer, the code
generation software 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.

Code generation support for value classes with set.prop methods


In R2014a, you can generate code for value classes that have set.prop methods.

6-5
R2014a

Code generation error for property that uses AbortSet attribute


Previously, when the current and new property values were equal, the generated code
set the property value and called the set property method regardless of the value of
the AbortSet attribute. When the AbortSet attribute was true, the generated code
behavior differed from the MATLAB behavior.

In R2014a, if your code has properties that use the AbortSet attribute, the code
generation software generates an error.

Compatibility Considerations
Previously, for code using the AbortSet attribute, code generation succeeded, but the
behavior of the generated code was incorrect. Now, for the same code, code generation
ends with an error. Remove the AbortSet attribute from your code and rewrite the code
to explicitly compare the current and new property value.

Independent configuration selections for standard math and code


replacement libraries
In R2014a, you can independently select and configure standard math and code
replacement libraries for C and C++ code generation.

• The language selection (C or C++) determines the available standard math libraries.

• In a project, the Language setting on the All Settings tab determines options
that are available for a new Standard math library setting on the Hardware
tab.
• In a code configuration object, the TargetLang parameter determines options that
are available for a new TargetLangStandard parameter.
• Depending on the your language selection, the following options are available for
the Standard math library setting in a project and for the TargetLangStandard
parameter in a configuration object.

Language Standard Math Libraries (TargetLangStandard)


C C89/C90 (ANSI) – default

C99 (ISO)
C++ C89/C90 (ANSI) – default

6-6
Check bug reports for issues and fixes

Language Standard Math Libraries (TargetLangStandard)


C99 (ISO)

C++03 (ISO)
• The language selection and the standard math library selection determine the
available code replacement libraries.

• In a project, the Code replacement library setting on the Hardware tab lists
available code replacement libraries. The MATLAB Coder software filters the list
based on compatibility with the Language and Standard math library settings
and the product licensing. For example, Embedded Coder offers more libraries and
the ability to create and use custom code replacement libraries.
• In a configuration object, the valid values for the CodeReplacementLibrary
parameter depend on the values of the TargetLang and TargetLangStandard
parameters and the product licensing.

Compatibility Considerations
In R2014a, code replacement libraries provided by MathWorks® no longer include
standard math libraries.

• When you open a project that was saved with an earlier version:

• The Code replacement library setting remains the same unless previously set
to C89/C90 (ANSI), C99 (ISO), C++ (ISO), Intel IPP (ANSI), or Intel
IPP (ISO). In these cases, MATLAB Coder software sets Code replacement
library to None or Intel IPP.
• MATLAB Coder software sets the new Standard math library setting to a value
based on the previous Code replacement library setting.

If Code replacement library was set to: Standard Math Library is set to:
C89/C90 (ANSI), C99 (ISO), or C++ C89/C90 (ANSI), C99 (ISO), C++03
(ISO) (ISO), respectively
GNU99 (GNU), Intel IPP C99 (ISO)
(ISO),Intel IPP (GNU), ADI
TigerSHARC (Embedded Coder only), or
MULTI BF53x (Embedded Coder only)

6-7
R2014a

If Code replacement library was set to: Standard Math Library is set to:
A custom library (Embedded Coder), A value based on the BaseTfl property
and the corresponding registration file setting
has been loaded in memory
Any other value The default standard math library,
C89/C90 (ANSI)
• When you load a configuration object from a MAT file that was saved in an earlier
version:

• The CodeReplacementLibrary setting remains the same unless previously set


to Intel IPP (ANSI) or Intel IPP (ISO). In these cases, MATLAB Coder
software sets CodeReplacementLibrary to Intel IPP.
• MATLAB Coder software sets the new TargetLangStandard setting to a value
based on the previous CodeReplacementLibrary setting.

If CodeReplacementLibrary was set to: TargetLangStandard is set to:


Intel IPP (ANSI) C89/C90 ANSI
Intel IPP (ISO) C99 (ISO)
Any other value The default standard math library,
C89/C90 (ANSI)
• The generated code can differ from earlier versions if you use the default standard
math library, C89/C90 (ANSI), with one of these code replacement libraries:
GNU99 (GNU)
Intel IPP (GNU)
ADI TigerSHARC (Embedded Coder only)
MULTI BF53x (Embedded Coder only)

To generate the same code as in earlier versions, change TargetLangStandard to


C99 (ISO).
• After you open a project, if you select a code replacement library provided by
MathWorks, the code generation software can produce different code than in previous
versions, depending on the Standard math library setting. Verify generated code.
• If a script that you used in a previous version sets the configuration object
CodeReplacementLibrary parameter, modify the script to use both the
CodeReplacementLibrary and the TargetLangStandard parameters.

6-8
Check bug reports for issues and fixes

Restrictions on bit length for integer types in a


coder.HardwareImplementation object
In R2014a, the code generation software imposes restrictions on the bit length of
integer types in a coder.HardwareImplementation object. For example, the
value of ProdBitPerChar must be between 8 and 32 and less than or equal to
ProdBitPerShort. If you set the bit length to an invalid value, the code generation
software reports an error.

See coder.HardwareImplementation.

Change in location of interface files in code generation report


The code generation software creates and uses interface files prefixed with _coder. For
MEX code generation, these files appear in the code generation report. Previously, these
files appeared in the Target Source Files pane of the C code tab of the code generation
report. They now appear in the Interface Source Files pane of the C code tab. The
report is now consistent with the folder structure for generated files. Since R2013b, the
interface files are in a subfolder named interface.

Compiler warnings in code generation report


For MEX code generation, the code generation report now includes C and C++ compiler
warning messages. If the code generation software detects compiler warnings, it
generates a warning message in the All Messages tab. Compiler error and warning
messages are highlighted in red on the Target Build Log tab.

See View Errors and Warnings in a Report.

Removal of date and time comment from generated code files


Previously, generated code files contained a comment with the string C source code
generated on followed by a date and time stamp. This comment no longer appears in
the generated code files. If you have an Embedded Coder license, you can include the
date and time stamp in custom file banners by using code generation template (CGT)
files.

Removal of two's complement guard from rtwtypes.h


rtwtypes.h no longer contains the following code:

6-9
R2014a

#if ((SCHAR_MIN + 1) != -SCHAR_MAX)


#error "This code must be compiled using a 2's complement representation for signed integer values"
#endif
You must compile the code that is generated by the MATLAB Coder software on a target
that uses a two’s complement representation for signed integer values. The generated
code does not verify that the target uses a two’s complement representation for signed
integer values.

Removal of TRUE and FALSE from rtwtypes.h


When the target language is C, rtwtypes.h defines true and false. It no longer
defines TRUE and FALSE.

Compatibility Considerations
If you integrate code generated in R2014a with custom code that references TRUE or
FALSE, modify your custom code in one of these ways:

• Define TRUE or FALSE in your custom code.


• Change TRUE and FALSE to true and false, respectively.
• Change TRUE and FALSE to 1U and 0U, respectively.

Change to default names for structure types generated from entry-point


function inputs and outputs
In previous releases, the code generation software used the same default naming
convention for structure types generated from local variables and from entry-point
function inputs and outputs. The software used struct_T for the first generated
structure type name, a_struct_T for the next name, b_struct_T for the next name,
and so on.

In R2014a, the code generation software uses a different default naming convention for
structure types generated from entry-point function inputs and outputs. The software
uses struct0_T for the first generated structure type name, struct1_T for the next
name, struct2_T for the next name, and so on. With this new naming convention, you
can more easily predict the structure type name in the generated code.

6-10
Check bug reports for issues and fixes

Compatibility Considerations
If you have C or C++ code that uses default structure type names generated from an
entry-point function in a previous release, and you generate the entry-point function
in R2014a, you must rewrite the code to use the new structure type names. However,
subsequent changes to your MATLAB code, such as adding a variable with a structure
type, can change the default structure type names in the generated code. To avoid
compatibility issues caused by changes to default names for structure types in generated
code, specify structure type names using coder.cstructname.

Toolbox functions supported for code generation


See Functions and Objects Supported for C and C++ Code Generation — Alphabetical
List and Functions and Objects Supported for C and C++ Code Generation — Categorical
List.

Communications System Toolbox

• comm.OFDMModulator
• comm.OFDMDemodulator

Computer Vision System Toolbox

• detectHarrisFeatures
• detectMinEigenFeatures
• estimateGeometricTransform

Data and File Management in MATLAB

fread

DSP System Toolbox

ca2tf firhalfband ifir iirnotch


cl2tf firlpnorm iircomb iirpeak
firceqrip firminphase iirgrpdelay tf2ca
fireqint firnyquist iirlpnorm tf2cl
firgr firpr2chfb iirlpnormc dsp.DCBlocker

6-11
R2014a

Image Processing Toolbox

affine2d im2uint16 imhist


bwpack im2uint8 imopen
bwselect imbothat imref2d
bwunpack imclose imref3d
edge imdilate imtophat
getrangefromclass imerode imwarp
im2double imextendedmax mean2
im2int16 imextendedmin projective2d
im2single imfilter strel

Interpolation and Computational Geometry in MATLAB

• interp2
• interp3
• mkpp
• pchip
• ppval
• polyarea
• rectint
• spline
• unmkpp

Matrices and Arrays in MATLAB

flip

Optimization Functions in MATLAB

• fminsearch
• optimget
• optimset

Polynomials in MATLAB

• polyder

6-12
Check bug reports for issues and fixes

• polyint
• polyvalm

Signal Processing Toolbox

• findpeaks
• db2pow
• pow2db

Fixed-point conversion enhancements


These capabilities require a Fixed-Point Designer license.

Overflow detection with scaled double data types in MATLAB Coder projects

The MATLAB Coder Fixed-Point Conversion tool now provides the capability to detect
overflows. 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. For more information,
see Detect Overflows Using the Fixed-Point Conversion Tool and Detecting Overflows.

You can also detect overflows when using the codegen function. For more information,
see coder.FixptConfig and Detect Overflows at the Command Line.

Support for MATLAB classes

You can now use the MATLAB Coder Fixed-Point Conversion tool to convert floating-
point MATLAB code that uses MATLAB classes. For more information, see Fixed-Point
Code for MATLAB Classes.

Generated fixed-point code enhancements

The generated fixed-point code now:

• Uses subscripted assignment (the colon(:) operator). This enhancement produces


concise code that is more readable.
• Has better code for constant expressions. In previous releases, multiple parts of an
expression were quantized to fixed point. The final value of the expression was less
accurate and the code was less readable. Now, constant expressions are quantized
only once at the end of the evaluation. This new behavior results in more accurate
results and more readable code.

6-13
R2014a

For more informations, see Generated Fixed-Point Code.

Fixed-point report for float-to-fixed conversion

In R2014a, when you convert floating-point MATLAB code to fixed-point C or C++ code,
the code generation software generates a fixed-point report in HTML format. For the
variables in your MATLAB code, the report provides the proposed fixed-point types and
the simulation or derived ranges used to propose those types. For a function my_fcn and
code generation output folder out_folder, the location of the report is out_folder/
my_fcn/fixpt/my_fcn_fixpt_Report.html. If you do not specify out_folder in
the project settings or as an option of the codegen command, the default output folder is
codegen.

6-14
Check bug reports for issues and fixes

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.

6-15
R2013b
Version: 2.5

New Features

Bug Fixes

Compatibility Considerations
R2013b

Code generation for Statistics Toolbox and Phased Array System Toolbox
Code generation now supports more than 100 Statistics Toolbox™ functions. For
implementation details, see Statistics Toolbox Functions.

Code generation now supports most of the Phased Array System Toolbox™ functions and
System objects. For implementation details, see Phased Array System Toolbox Functions
and Phased Array System Toolbox System Objects.

Toolbox functions supported for code generation


For implementation details, see Functions Supported for C/C++ Code Generation —
Alphabetical List.

Data Type Functions

• narginchk

Programming Utilities

• mfilename

Specialized Math

• psi

Computer Vision System Toolbox Classes and Functions

• extractFeatures
• detectSURFFeatures
• disparity
• detectMSERFeatures
• detectFASTFeatures
• vision.CascadeObjectDetector
• vision.PointTracker
• vision.PeopleDetector
• cornerPoints
• MSERRegions
• SURFPoints

7-2
Check bug reports for issues and fixes

parfor function for standalone code generation, enabling execution on


multiple cores
You can use MATLAB Coder software to generate standalone C/C++ code from MATLAB
code that contains parfor-loops. The code generation software uses the Open Multi-
Processing (OpenMP) application interface to generate C/C++ code that runs in parallel
on multiple cores on the target hardware.

For more information, see parfor and Accelerate MATLAB Algorithms That Use Parallel
for-loops (parfor).

Persistent variables in parfor-loops


You can now generate code from parallel algorithms that use persistent variables.

For more information, see parfor.

Random number generator functions in parfor-loops


You can now generate code from parallel algorithms that use the random number
generators rand, randn, randi, randperm, and rng.

For more information, see parfor.

External code integration using coder.ExternalDependency


You can define the interface to external code using the new
coder.ExternalDependency class. Methods of this class update the compile and
build information required to integrate the external code with MATLAB code. In
your MATLAB code, you can call the external code without needing to update build
information. See coder.ExternalDependency.

Updating build information using coder.updateBuildInfo


You can use the new function coder.updateBuildInfo to update build information.
For example:
coder.updateBuildInfo('addLinkFlags','/STACK:1000000');
adds a stack size option to the linker command line. See coder.updateBuildInfo.

7-3
R2013b

Generation of simplified code using built-in C types


By default, MATLAB Coder now uses built-in C types in the generated code. You have
the option to use predefined types from rtwtypes.h. To control the data type in the
generated code:

• In a project, on the Project Settings dialog box Code Appearance tab, use the Data
Type Replacement setting.
• At the command line, use the configuration object parameter
DataTypeReplacement.

The built-in C type that the code generation software uses depends on the target
hardware.

For more information, see Specify Data Type Used in Generated Code.

Compatibility Considerations
If you use the default configuration or project settings, the generated code has built-in
C types such as double or char. Code generated prior to R2013b has predefined types
from rtwtypes.h, such as real_T or int32_T.

Conversion of MATLAB expressions into C constants using coder.const


You can use the new function coder.const to convert expressions and function calls to
constants at compile time. See coder.const and Constant Folding.

Highlighting of constant function arguments in the compilation report


The compilation report now highlights constant function arguments and displays them
in a distinct color. You can display the constant argument data type and value by placing
the cursor over the highlighted argument. You can export the constant argument value to
the base workspace where you can display detailed information about the argument.

For more information, see Viewing Variables in Your MATLAB Code.

Code Generation Support for int64, uint64 data types


You can now use int64 and uint64 data types for code generation.

7-4
Check bug reports for issues and fixes

C99 long long integer data type for code generation


If your target hardware and compiler support the C99 long long integer data type, you
can use this data type for code generation. Using long long results in more efficient
generated code that contains fewer cumbersome operations and multiword helper
functions. To specify the long long data type for code generation:

• In a project, on the Project Settings dialog box Hardware tab, use the following
production and test hardware settings:

• Enable long long: Specify that your C compiler supports the long long data type.
Set to Yes to enable Sizes: long long.
• Sizes: long long: Describe length in bits of the C long long data type supported by
the hardware.
• At the command line, use the following hardware implementation configuration object
parameters:

• ProdLongLongMode: Specify that your C compiler supports the long long data
type. Set to true to enable ProdBitPerLongLong.
• ProdBitPerLongLong: Describes the length in bits of the C long long data type
supported by the production hardware.
• TargetLongLongMode: Specifies whether your C compiler supports the long long
data type. Set to true to enable TargetBitPerLongLong.
• TargetBitPerLongLong: Describes the length in bits of the C long long data type
supported by the test hardware.

For more information, see the class reference information for


coder.HardwareImplementation.

Change to passing structures by reference


In R2013b, the option to pass structures by reference to entry-point functions in the
generated code applies to function outputs and function inputs. In R2013a, this option
applied only to inputs to entry-point functions.

Compatibility Considerations
If you select the pass structures by reference option, and a MATLAB entry-point function
has a single output that is a structure, the generated C function signature in R2013b

7-5
R2013b

differs from the signature in R2013a. In R2013a, the generated C function returns
the output structure. In R2013b, the output structure is a pass by reference function
parameter.

If you have code that calls one of these functions generated in R2013a, and then you
generate the function in R2013b, you must change the call to the function. For example,
suppose S is a structure in the following MATLAB function foo.

function S = foo()
If you generate this function in R2013a, you call the function this way:

S = foo();

If you generate this function in R2013b, you call the function this way:

foo(&S);

coder.runTest new syntax


Use the syntax coder.runTest(test_fcn, MEX_name_ext) to run test_fcn
replacing calls to entry-point functions with calls to the corresponding MEX functions in
the MEX file named MEX_name_ext. MEX_name_ext includes the platform-specific file
extension. See coder.runTest.

coder.target syntax change


The new syntax for coder.target is:

tf = coder.target('target')
For example, coder.target('MATLAB') returns true when code is running in
MATLAB. See coder.target.

You can use the old syntax, but consider changing to the new syntax. The old syntax will
be removed in a future release.

Changes for complex values with imaginary part equal to zero


In R2013b, complex values with an imaginary part equal to zero become real when:

• They are returned by a MEX function.

7-6
Check bug reports for issues and fixes

• They are passed to an extrinsic function.

See Expressions With Complex Operands Yield Complex Results.

Compatibility Considerations
MEX functions generated in R2013b return a real value when a complex result has an
imaginary part equal to zero. MEX functions generated prior to R2013b return a complex
value when a complex result has an imaginary part equal to zero.

In R2013b, complex values with imaginary part equal to zero become real when passed to
an extrinsic function. In previous releases, they remain complex.

Subfolder for code generation interface files


Previously, interface files for MEX code generation appeared in the code generation
output folder. In R2013b, these interface files have the prefix _coder, appear in a
subfolder named interface, and appear for all code generation output types.

Support for LCC compiler on Windows 64-bit machines


The LCC-win64 compiler is shipping with MATLAB Coder for Microsoft® Windows 64-
bit machines. For Windows 64-bit machines that do not have a third-party compiler
installed, MEX code generation uses LCC by default.

You cannot use LCC for code generation of C/C++ static libraries, C/C++ dynamic
libraries, or C/C++ executables. For these output types, you must install a compiler. See
http://www.mathworks.com/support/compilers/current_release/.

Fixed-Point conversion enhancements


These capabilities require a Fixed-Point Designer license.

Fixed-Point conversion option for codegen

You can now convert floating-point MATLAB code to fixed-point code, and then generate
C/C++ code at the command line using the option -float2fixed with the codegen
command. See codegen and Convert Floating-Point MATLAB Code to Fixed-Point C Code
Using codegen.

7-7
R2013b

Fixed-point conversion using derived ranges on Mac platforms

You can now convert floating-point MATLAB code to fixed-point C code using the Fixed-
Point Conversion tool in MATLAB Coder projects on Mac platforms.

For more information, see Automated Fixed-Point Conversion and Propose Fixed-Point
Data Types Based on Derived Ranges.

Derived ranges for complex variables in MATLAB Coder projects

Using the Fixed-Point Conversion tool in MATLAB Coder projects, you can derive ranges
for complex variables. For more information, see Propose Fixed-Point Data Types Based
on Derived Ranges

Fixed-point conversion workflow supports designs that use enumerated types

Using the Fixed-Point Conversion tool in MATLAB Coder projects, you can propose data
types for enumerated data types using derived and simulation ranges.

For more information, see Propose Fixed-Point Data Types Based on Derived Ranges and
Propose Fixed-Point Data Types Based on Simulation Ranges.

Fixed-point conversion of variable-size data using simulation ranges

Using the Fixed-Point Conversion tool in MATLAB Coder projects, you can propose data
types for variable-size data using simulation ranges.

For more information, see Propose Fixed-Point Data Types Based on Simulation Ranges.

Fixed-point conversion test file coverage results

The Fixed-Point Conversion tool now provides test file coverage results. After simulating
your design using a test file, the tool provides an indication of how often the code is
executed. If you run multiple test files at once, the tool provides the cumulative coverage.
This information helps you determine the completeness of your test files and verify that
they are exercising the full operating range of your algorithm. The completeness of the
test file directly affects the quality of the proposed fixed-point types.

For more information, see Code Coverage.

7-8
Check bug reports for issues and fixes

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.

7-9
R2013a
Version: 2.4

New Features

Bug Fixes

Compatibility Considerations
R2013a

Automatic fixed-point conversion during code generation (with Fixed-


Point Designer)
You can now convert floating-point MATLAB code to fixed-point C code using the fixed-
point conversion capability in MATLAB Coder projects. You can choose to propose data
types based on simulation range data, static range data, or both.

Note: You must have a Fixed-Point Designer license.

During fixed-point conversion, you can:

• Propose fraction lengths based on default word lengths.


• 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 used by each variable.

For more information, see Propose Fixed-Point Data Types Based on Simulation Ranges
and Propose Fixed-Point Data Types Based on Derived Ranges.

File I/O function support


The following file I/O functions are now supported for code generation:

• fclose
• fopen
• fprintf

To view implementation details, see Functions Supported for Code Generation —


Alphabetical List.

8-2
Check bug reports for issues and fixes

Support for nonpersistent handle objects


You can now generate code for local variables that contain references to handle objects
or System objects. In previous releases, generating code for these objects was limited to
objects assigned to persistent variables.

Structures passed by reference to entry-point functions


You can now specify to pass structures by reference to entry-point functions in the
generated code. This optimization is available for standalone code generation only; it is
not available for MEX functions. Passing structures by reference reduces the number of
copies at entry-point function boundaries in your generated code. It does not affect how
structures are passed to functions other than entry-point functions.

To pass structures by reference:

• In a project, on the Project Settings dialog box All Settings tab, under Advanced,
set Pass structures by reference to entry-point functions to Yes.
• At the command line, create a code generation configuration object and set the
PassStructByReference parameter to true. For example:

cfg = coder.config('lib');
cfg.PassStructByReference=true;

Include custom C header files from MATLAB code


The coder.cinclude function allows you to specify in your MATLAB code which
custom C header files to include in the generated C code. Each header file that you
specify using coder.cinclude is included in every C/C++ file generated from your
MATLAB code. You can specify whether the #include statement uses double quotes for
application header files or angle brackets for system header files in the generated code.

For example, the following code for function foo specifies to include the application
header file mystruct.h in the generated code using double quotes.

function y = foo(x1, x2)


%#codegen
coder.cinclude('mystruct.h');

...

8-3
R2013a

For more information, see coder.cinclude.

Load from MAT-files


MATLAB Coder now supports a subset of the load function for loading run-time
values from a MAT-file while running a MEX function. It also provides a new function,
coder.load, for loading compile-time constants when generating MEX or standalone
code. This support facilitates code generation from MATLAB code that uses load to load
constants into a function. You no longer have to manually type in constants that were
stored in a MAT-file.

To view implementation details for the load function, see Functions Supported for Code
Generation — Alphabetical List.

For more information, see coder.load.

coder.opaque function enhancements


When you use coder.opaque to declare a variable in the generated C code, you can now
also specify the header file that defines the type of the variable. Specifying the location
of the header file helps to avoid compilation errors because the MATLAB Coder software
can find the type definition more easily.

You can now compare coder.opaque variables of the same type. This capability helps
you verify, for example, whether an fopen command succeeded.

null = coder.opaque('FILE*','NULL','HeaderFile','stdio.h');
ftmp = null;
ftmp = coder.ceval('fopen',fname,permission);
if ftmp == null
% Error - file open failed
end

For more information, see coder.opaque.

Automatic regeneration of MEX functions in projects


When you run a test file from a MATLAB Coder project to verify the behavior of the
generated MEX function, the project now detects when to rebuild the MEX function.
MATLAB Coder rebuilds the MEX function only if you have modified the original

8-4
Check bug reports for issues and fixes

MATLAB algorithm since the previous build, saving you time during the verification
phase.

MEX function signatures include constant inputs


When you generate a MEX function for a MATLAB function that takes constant inputs,
by default, the MEX function signature now contains the constant inputs. If you are
verifying your MEX function in a project, this behavior allows you to use the same test
file to run the original MATLAB algorithm and the MEX function.

Compatibility Considerations
In previous releases, MATLAB Coder removed the constants from the MEX function
signature. To use these existing scripts with MEX functions generated using R2013a
software, do one of the following:

• Update the scripts so that they no longer remove the constants.


• Configure MATLAB Coder to remove the constant values from the MEX function
signature.

To configure MATLAB Coder to remove the constant values:

• In a project, on the Project Settings dialog box All Settings tab, under Advanced,
set Constant Inputs to Remove from MEX signature.
• At the command line, create a code generation configuration object, and, set the
ConstantInputs parameter to 'Remove'. For example:

cfg = coder.config;
cfg.ConstantInputs='Remove';

Custom toolchain registration


MATLAB Coder software enables you to register third-party software build tools for
creating executables and libraries.

• The software automatically detects supported tool chains on your system.


• You can manage and customize multiple tool chain definitions.
• Before generating code, you can select any one of the definitions using a drop-down
list.

8-5
R2013a

• The software generates simplified makefiles for improved readability.

For more information:

• See Custom Toolchain Registration.


• See the Adding a Custom Toolchain example.

Compatibility Considerations
If you open a MATLAB Coder project or use a code generation configuration object from
R2012b, the current version of MATLAB Coder software automatically tries to use the
toolchain approach. If an existing project or configuration object does not use default
target makefile settings, MATLAB Coder might not be able to upgrade to use a toolchain
approach and will emit a warning. For more information, see Project or Configuration is
Using the Template Makefile.

Complex trigonometric functions


Code generation support has been added for complex acosD, acotD, acscD, asecD, asinD,
atanD, cosD, cscD, cotD, secD, sinD, and tanD functions.

parfor function reduction improvements and C support


When generating MEX functions for parfor-loops, you can now use intersect and
union as reduction functions, and the following reductions are now supported:

• Concatenations
• Arrays
• Function handles

By default, when MATLAB Coder generates a MEX function for MATLAB code that
contains a parfor-loop, MATLAB Coder no longer requires C++ and now honors the
target language setting.

Support for integers in number theory functions


Code generation supports integer inputs for the following number theory functions:

• cumprod

8-6
Check bug reports for issues and fixes

• cumsum
• factor
• factorial
• gcd
• isprime
• lcm
• median
• mode
• nchoosek
• nextpow2
• primes
• prod

To view implementation details, see Functions Supported for Code Generation —


Alphabetical List.

Enhanced support for class property initial values


If you initialize a class property, you can now assign a different type to the property
when you use the class. For example, class foo has a property prop1 of type double.

classdef foo %#codegen


properties
prop1= 0;
end
methods
...
end
end
Function bar assigns a different type to prop1.

fumction bar %#codegen


f=foo;
f.prop1=single(0);
...
In R2013a, MATLAB Coder ignores the initial property definition and uses the
reassigned type. In previous releases, MATLAB Coder did not support this reassignment
and code generation failed.

8-7
R2013a

Compatibility Considerations
In previous releases, if the reassigned property had the same type as the initial value
but a different size, the property became variable-size in the generated code. In R2013a,
MATLAB Coder uses the size of the reassigned property, and the size is fixed. If you
have existing MATLAB code that relies on the property being variable-size, you cannot
generate code for this code in R2013a. To fix this issue, do not initialize the property in
the property definition block.

For example, you can no longer generate code for the following function bar.

Class foo has a property prop1 which is a scalar double.

classdef foo %#codegen


properties
prop1= 0;
end
methods
...
end
end
Function bar changes the size of prop1.

fumction bar %#codegen


f=foo;
f.prop1=[1 2 3];
% Use f
disp(f.prop1);
f.prop1=[1 2 3 4 5 6 ];

Optimized generated code for x=[x c] when x is a vector


MATLAB Coder now generates more optimized code for the expression x=[x c], if:

• x is a row or column vector.


• x is not in c.
• x is not aliased.
• There are no function calls in c.

In previous releases, the generated code contained multiple copies of x. In R2013a, it


does not contain multiple copies of x.

8-8
Check bug reports for issues and fixes

This enhancement reduces code size and execution time. It also improves code
readability.

Default use of Basic Linear Algebra Subprograms (BLAS) libraries


MATLAB Coder now uses BLAS libraries whenever they are available. There is no longer
an option to turn off the use of these libraries.

Compatibility Considerations
If existing configuration settings disable BLAS, MATLAB Coder now ignores these
settings.

Changes to compiler support


MATLAB Coder supports these new compilers.

• On Microsoft Windows platforms, Visual C++® 11.


• On Mac OS X platforms, Apple Xcode 4.2 with Clang.

MATLAB Coder no longer supports the gcc compiler on Mac OS X platforms.

MATLAB Coder no longer supports Watcom for standalone code generation. Watcom is
still supported for building MEX functions.

Compatibility Considerations
• Because Clang is the only compiler supported on Mac OS X platforms, and Clang does
not support Open MP, parfor is no longer supported on Mac OS X platforms.
• MATLAB Coder no longer supports Watcom for standalone code generation.
Use Watcom only for building MEX functions. Use an alternative compiler for
standalone code generation. For a list of supported compilers, see http://
www.mathworks.com/support/compilers/current_release/.

New toolbox functions supported for code generation


To view implementation details, see Functions Supported for Code Generation —
Alphabetical List.

8-9
R2013a

Bitwise Operation Functions

• flintmax

Computer Vision System Toolbox Classes and Functions

• binaryFeatures
• insertMarker
• insertShape

Data File and Management Functions

• computer
• fclose
• fopen
• fprintf
• load

Image Processing Toolbox Functions

• conndef
• imcomplement
• imfill
• imhmax
• imhmin
• imreconstruct
• imregionalmax
• imregionalmin
• iptcheckconn
• padarray

Interpolation and Computational Geometry

• interp2

MATLAB Desktop Environment Functions

• ismac

8-10
Check bug reports for issues and fixes

• ispc
• isunix

Functions being removed


These functions have been removed from MATLAB Coder software.

Function Name What Happens When You Use This


Function?
emlc Errors in R2013a.
emlmex Errors in R2013a.

Compatibility Considerations
emlc and emlmex have been removed. Use codegen instead. If you have existing code
that calls emlc or emlmex, use coder.upgrade to help convert your code to the new
syntax.

8-11
R2013a

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.

8-12
R2012b
Version: 2.3

New Features

Bug Fixes
R2012b

parfor function support for MEX code generation, enabling execution


on multiple cores
You can use MATLAB Coder software to generate MEX functions from MATLAB code
that contains parfor-loops. The generated MEX functions can run on multiple cores on
a desktop. For more information, see parfor and Acceleration of MATLAB Algorithms
Using Parallel for-loops (parfor).

Code generation readiness tool


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
needed to make the MATLAB code suitable for code generation.

For more information, see coder.screener and Code Generation Readiness Tool.

Reduced data copies and lightweight run-time checks for generated MEX
functions
MATLAB Coder now eliminates data copies for built-in, non-complex data types. It also
performs faster bounds checks. These enhancements result in faster generated MEX
functions.

Additional string function support for code generation


The following string functions are now supported for code generation. To view
implementation details, see Functions Supported for Code Generation — Alphabetical
List.

• deblank
• hex2num
• isletter
• isspace
• isstrprop
• lower

9-2
Check bug reports for issues and fixes

• num2hex
• strcmpi
• strjust
• strncmp
• strncmpi
• strtok
• strtrim
• upper

Visualization functions in generated MEX functions


The MATLAB Coder software now detects calls to many common visualization
functions, such as plot, disp, and figure. For MEX code generation, MATLAB
Coder automatically calls out to MATLAB for these functions. For standalone code
generation, MATLAB Coder does not generate code for these visualization functions. This
capability reduces the amount of time that you spend making your code suitable for code
generation. It also removes the requirement to declare these functions extrinsic using the
coder.extrinsic function.

Input parameter type specification enhancements


The updated project user interface facilitates input parameter type specification.

9-3
R2012b

Project import and export capability


You can now export project settings to a configuration object stored as a variable in the
base workspace. You can then use the configuration object to import the settings into
a different project or to generate code at the command line with the codegen function.
This capability allows you to:

• Share settings between the project and command-line workflow


• Share settings between multiple projects
• Standardize on settings for code generation projects

For more information, see Share Build Configuration Settings.

9-4
Check bug reports for issues and fixes

Package generated code in zip file for relocation


The packNGo function packages generated code files into a compressed zip file so that
you can relocate, unpack, and rebuild them in another development environment. This
capability is useful if you want to relocate files so that you can recompile them for a
specific target environment or rebuild them in a development environment in which
MATLAB is not installed.

For more information, see Package Code For Use in Another Development Environment.

Fixed-point instrumentation and data type proposals


MATLAB Coder projects provide the following fixed-point conversion support:

• Option to generate instrumented MEX functions


• Use of instrumented MEX functions to provide simulation minimum and maximum
results
• Fixed-point data type proposals based on simulation minimum and maximum values
• Option to propose fraction lengths or word lengths

You can use these proposed fixed-point data types to create a fixed-point version of your
original MATLAB entry-point function.

Note: Requires a Fixed-Point Toolbox™ license.

For more information, see Fixed-Point Conversion.

New toolbox functions supported for code generation


To view implementation details, see Functions Supported for Code Generation —
Alphabetical List.

Computer Vision System Toolbox

• integralImage

Image Processing Toolbox

• bwlookup

9-5
R2012b

• bwmorph

Interpolation and Computational Geometry

• interp2

Trigonometric Functions

• atan2d

New System objects supported for code generation


The following System objects are now supported for code generation. To see the list of
System objects supported for code generation, see System Objects Supported for Code
Generation.

Communications System Toolbox

• comm.ACPR
• comm.BCHDecoder
• comm.CCDF
• comm.CPMCarrierPhaseSynchronizer
• comm.GoldSequence
• comm.LDPCDecoder
• comm.LDPCEncoder
• comm.LTEMIMOChannel
• comm.MemorylessNonlinearity
• comm.MIMOChannel
• comm.PhaseNoise
• comm.PSKCarrierPhaseSynchronizer
• comm.RSDecoder

DSP System Toolbox

• dsp.AllpoleFilter
• dsp.CICDecimator
• dsp.CICInterpolator

9-6
Check bug reports for issues and fixes

• dsp.IIRFilter
• dsp.SignalSource

9-7
R2012b

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.

9-8
R2012a
Version: 2.2

New Features

Compatibility Considerations
R2012a

Code Generation for MATLAB Classes


In R2012a, there is preliminary support for code generation for MATLAB classes
targeted at supporting System objects defined by users. For more information about
generating code for MATLAB classes, see Code Generation for MATLAB Classes.
For more information about generating code for System objects, see the DSP System
Toolbox, Computer Vision System Toolbox or the Communications System Toolbox
documentation.

Dynamic Memory Allocation Based on Size


By default, dynamic memory allocation is now enabled for variable-size arrays whose
size exceeds a configurable threshold. This behavior allows for finer control over stack
memory usage. Also, you can generate code automatically for more MATLAB algorithms
without modifying the original MATLAB code.

Compatibility Considerations
If you use scripts to generate code and you do not want to use dynamic memory
allocation, you must disable it. For more information, see Controlling Dynamic Memory
Allocation.

C/C++ Dynamic Library Generation


You can now use MATLAB Coder to build a dynamically linked library (DLL) from
the generated C code. These libraries are useful for integrating into existing software
solutions that expect dynamically linked libraries.

For more information, see Generating C/C++ Dynamically Linked Libraries from
MATLAB Code.

Automatic Definition of Input Parameter Types


MATLAB Coder software can now automatically define input parameter types by
inferring these types from test files that you supply. This capability facilitates input type
definition and reduces the risk of introducing errors when defining types manually.

To learn more about automatically defining types:

10-2
Check bug reports for issues and fixes

• In MATLAB Coder projects, see Autodefining Input Types.


• At the command line, see the coder.getArgTypes function reference pagehttp://
www.mathworks.com/help/releases/R2012a/toolbox/coder/ref/coder.getargtypes.html.

Verification of MEX Functions


MATLAB Coder now provides support for test files to verify the operation of generated
MEX functions. This capability enables you to verify that the MEX function is
functionally equivalent to your original MATLAB code and to check for run-time errors.

To learn more about verifying MEX function behavior:

• In MATLAB Coder projects, see How to Verify MEX Functions in a Project.


• At the command line, see the coder.runTest function reference pagehttp://
www.mathworks.com/help/releases/R2012a/toolbox/coder/ref/coder.runtest.html.

Enhanced Project Settings Dialog Box


The Project Settings dialog box now groups configuration parameters so that you can
easily identify the parameters associated with code generation objectives such as speed,
memory, and code appearance. The dialog boxes for code generation configuration objects,
coder.MexCodeConfig, coder.CodeConfig, and coder.EmbeddedCodeConfig, also
use the same new groupings.

To view the updated Project Settings dialog box:

1 In a project, click the Build tab.


2 On the Build tab, click the More settings link to open the Project Settings dialog
box.

For information about the parameters on each tab, click the Help button.

To view the updated dialog boxes for the code generation configuration objects:

1 At the MATLAB command line, create a configuration object. For example, create a
configuration object for MEX code generation.

mex_cfg = coder.config;
2 Open the dialog box for this object.

10-3
R2012a

open mex_cfg
For information about the parameters on each tab, click the Help button.

Projects Infer Input Types from assert Statements in Source Code


MATLAB Coder projects can now infer input data types from assert statements that
define the properties of function inputs in your MATLAB entry-point files. For more
information, see Defining Inputs Programmatically in the MATLAB File.

Code Generation from MATLAB


For details about new toolbox functions and System objects supported for code
generation, see the Code Generation from MATLAB Release Notes.

New Demo
The following demo has been added:

Demo... Shows How You Can...


coderdemo_reverb Generate a MEX function for an algorithm that uses
MATLAB classes.

10-4
Check bug reports for issues and fixes

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.

10-5
R2011b
Version: 2.1

New Features
R2011b

Support for Deletion of Rows and Columns from Matrices


You can now generate C/C++ code from MATLAB code that deletes rows or columns from
matrices. For example, the following code deletes the second column of matrix X:

X(:,2) = [];
For more information, see Diminishing the Size of a Matrix in the MATLAB
documentation.

Code Generation from MATLAB


For details of new toolbox functions and System objects supported for code generation,
see Code Generation from MATLAB Release Notes.

11-2
Check bug reports for issues and fixes

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.

11-3
R2011a
Version: 2.0

New Features

Compatibility Considerations
R2011a

New User Interface for Managing Projects


The new MATLAB Coder user interface simplifies the MATLAB to C/C++ code
generation process. Using this user interface, you can:

• 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++ 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

To Get Started

You launch a MATLAB Coder project by doing one of the following:

• From the MATLAB main menu, select File > New > Code Generation Project
• Enter coder at the MATLAB command line

To learn more about working with MATLAB Coder, see Generating C Code from
MATLAB Code Using the MATLAB Coder Project Interface.

Migrating from Real-Time Workshop emlc Function


In MATLAB Coder, the codegen function replaces emlc with the following differences:

New codegen Options

Old emlc Option New codegen Option


-eg -args
emlcoder.egc coder.Constant
emlcoder.egs coder.typeof(a,b,1) specifies a variable-
size input with the same class and complexity

12-2
Check bug reports for issues and fixes

Old emlc Option New codegen Option


as a and same size and upper bounds as the size
vector b.

Creates coder.Type objects for use with the


codegen -args option. For more information,
see coder.typeof.
-F Nocodegen option available. Instead, use the
default fimath. For more information, see the
Fixed-Point Toolbox documentation.
-global -globals

Note: -global continues to work with codegen


-N This option is no longer supported. Instead, set
up numerictype in MATLAB.
-s -config

Use with the new configuration objects, see


“New Code Generation Configuration Objects”
on page 12-4.
-T rtw:exe -config:exe

Use this option to generate a C/C++ executable


using default build options. Otherwise,
use -config with a coder.CodeConfig or
coder.EmbeddedCodeConfig configuration object.
-T mex -config:mex

Use this option to generate a MEX function


using default build options. Otherwise,
use -config with a coder.MexCodeConfig
configuration object.

12-3
R2011a

Old emlc Option New codegen Option


-T rtw -config:lib
-T rtw:lib
Use either of these options to generate a C/C++
library using default build options. Otherwise,
use -config with a coder.CodeConfig or
coder.EmbeddedCodeConfig configuration object.

New Code Generation Configuration Objects

The codegen function uses new configuration objects that replace the old emlc objects
with the following differences:

Old emlc Configuration Object New codegen Configuration Object


emlcoder.MEXConfig coder.MexCodeConfig
emlcoder.RTWConfig coder.CodeConfig
emlcoder.RTWConfig('grt')
The SupportNonFinite property is now available without an
Embedded Coder license.

The following property names have changed:

• RTWCompilerOptimization is now
CCompilerOptimization
• RTWCustomCompilerOptimization is now
CCustomCompilerOptimization
• RTWVerbose is now Verbose
emlcoder.RTWConfig('ert')coder.EmbeddedCodeConfig

The following property names have changed:

• MultiInstanceERTCode is now MultiInstanceCode


• RTWCompilerOptimization is now
CCompilerOptimization
• RTWCustomCompilerOptimization is now
CCustomCompilerOptimization
• RTWVerbose is now Verbose

12-4
Check bug reports for issues and fixes

Old emlc Configuration Object New codegen Configuration Object


emlcoder. coder.HardwareImplementation
HardwareImplementation

The codegen Function Has No Default Primary Function Input Type

In previous releases, if you used the emlc function to generate code for a MATLAB
function with input parameters, and you did not specify the types of these inputs, by
default, emlc assumed that these inputs were real, scalar, doubles. In R2011a, the
codegen function does not assume a default type. You must specify at least the class of
each primary function input. For more information, see Specifying Properties of Primary
Function Inputs in a Project.

Compatibility Considerations
If your existing script calls emlc to generate code for a MATLAB function that has inputs
and does not specify the input types, and you migrate this script to use codegen, you
must modify the script to specify inputs.

The codegen Function Processes Compilation Options in a Different Order

In previous releases, the emlc function resolved compilation options from left to right so
that the right-most option prevailed. In R2011a, the codegen function gives precedence
to individual command-line options over options specified using a configuration object. If
command-line options conflict, the right-most option prevails.

Compatibility Considerations
If your existing script calls emlc specifying a configuration object as well as other
command-line options, and you migrate this script to use codegen, codegen might not
use the same configuration parameter values as emlc.

New coder.Type Classes


MATLAB Coder includes the following new classes to specify input parameter
definitions:

• coder.ArrayType

12-5
R2011a

• coder.Constant
• coder.EnumType
• coder.FiType
• coder.PrimitiveType
• coder.StructType
• coder.Type

New coder Package Functions


The following new package functions let you work with objects and types for C/C++ code
generation:

Function Purpose
coder.config Create MATLAB Coder code generation
configuration objects
coder.newtype Create a new coder.Type object
coder.resize Resize a coder.Type object
coder.typeof Convert a MATLAB value into its canonical
type

Script to Upgrade MATLAB Code to Use MATLAB Coder Syntax


The coder.upgrade script helps you upgrade to MATLAB Coder by searching your
MATLAB code for old commands and options and replacing them with their new
equivalents. For more information, at the MATLAB command prompt, enter help
coder.upgrade.

Embedded MATLAB Now Called Code Generation from MATLAB


MathWorks is no longer using the term Embedded MATLAB to refer to the language
subset that supports code generation from MATLAB algorithms. This nomenclature
incorrectly implies that the generated code is used in embedded systems only. The new
term is code generation from MATLAB. This terminology better reflects the full extent of
the capability for translating MATLAB algorithms into readable, efficient, and compact
MEX and C/C++ code for deployment to both desktop and embedded systems.

12-6
Check bug reports for issues and fixes

MATLAB Coder Uses rtwTargetInfo.m to Register Target Function Libraries


In previous releases, the emlc function also recognized the customization file,
sl_customization.m. In R2011a, the MATLAB Coder software does not recognize
this customization file, you must use rtwTargetInfo.m to register a Target Function
Library (TFL). To register a TFL, you must have Embedded Coder software. For more
information, see Use the rtwTargetInfo API to Register a CRL with MATLAB Coder
Software in the Embedded Coder documentation.

New Getting Started Tutorial Video


To learn how to generate C code from MATLAB code, see the “Generating C Code from
MATLAB Code” video in the MATLAB Coder Getting Started demos.

New Demos
The following demos have been added:

Demo... Shows How You Can...


Hello World Generate and run a MEX function from a simple
MATLAB program
Working with Persistent Variables Compute the average for a set of values by using
persistent variables
Working with Structure Arrays Shows how to build a scalar template before growing
it into a structure array, a requirement for code
generation from MATLAB.
Balls Simulation Simulates bouncing balls and shows that you should
specify only the entry function when you compile the
application into a MEX function.
General Relativity with MATLAB Uses Einstein's theory of general relativity to
Coder calculate geodesics in curved space-time.
Averaging Filter Generate a standalone C library from MATLAB code
using codegen
Edge Detection on Images Generate a standalone C library from MATLAB code
that implements a Sobel filter

12-7
R2011a

Demo... Shows How You Can...


Read Text File Generate a standalone C library from MATLAB code
that uses the coder.ceval, coder.extrinsic
and coder.opaque functions.
“Atoms” Simulation Generate a standalone C library and executable
from MATLAB code using a code generation
configuration object to enable dynamic memory
allocation
Replacing Math Functions and Use target function libraries (TFLs) to replace
Operators operators and functions in the generated code

Note: To run this demo, you need Embedded Coder


software.
Kalman Filter • Generate a standalone C library from a MATLAB
version of a Kalman filter
• Accelerate the Kalman filter algorithm by
generating a MEX function

Functionality Being Removed in a Future Version


This function will be removed in a future version of MATLAB Coder software.

Function Name What Happens When You Compatibility Considerations


Use This Function?
emlc Still runs in R2011a None

Function Elements Being Removed in a Future Release


Function or Element Name What Happens When You Use Use This Element Instead
the Function or Element?
%#eml Still runs %#codegen
eml.allowpcode Still runs coder.allowpcode
eml.ceval Still runs coder.ceval
eml.cstructname Still runs coder.cstructname

12-8
Check bug reports for issues and fixes

Function or Element Name What Happens When You Use Use This Element Instead
the Function or Element?
eml.extrinsic Still runs coder.extrinsic
eml.inline Still runs coder.inline
eml.nullcopy Still runs coder.nullcopy
eml.opaque Still runs coder.opaque
eml.ref Still runs coder.ref
eml.rref Still runs coder.rref
eml.target Still runs coder.target
eml.unroll Still runs coder.unroll
eml.varsize Still runs coder.varsize
eml.wref Still runs coder.wref

12-9
R2011a

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.

12-10

You might also like