MATLAB Coder Documentation (PDFDrive)
MATLAB Coder Documentation (PDFDrive)
R2016a
How to Contact MathWorks
Phone: 508-647-7000
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
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
viii Contents
Comparing C Code and MATLAB Code Using Tiling in the
MATLAB Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
ix
1
Product Overview
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
• 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
1-3
1 Product Overview
See Also
1-4
Code Generation for Embedded Software Applications
• 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
1-6
Installing Prerequisite 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
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”.
1-7
1 Product Overview
Related Products
• Embedded Coder
• Simulink® Coder
1-8
Setting Up the C or C++ Compiler
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
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
Learning Objectives
In this tutorial, you learn how to:
Tutorial Prerequisites
Required Products
• MATLAB
• MATLAB Coder
2-2
C Code Generation Using the MATLAB Coder App
• C compiler
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”.
Description
You do not have to be familiar with the algorithm in the example to complete the
tutorial.
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 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
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)';
Reference
Haykin, Simon. Adaptive Filter Theory. Upper Saddle River, NJ: Prentice-Hall, Inc.,
1996.
2-5
2 Tutorials
Throughout this tutorial, you work with MATLAB files that contain a simple Kalman
filter algorithm.
• Test files that:
Location of Files
2-6
C Code Generation Using the MATLAB Coder App
• 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.
• 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
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
2-8
C Code Generation Using the MATLAB Coder App
• 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.
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
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.
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”.
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:
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”.
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
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.
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
On the MATLAB Toolstrip Apps tab, under Code Generation, click the MATLAB
Coder app icon.
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.
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:
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).
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.
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.
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
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.
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.
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.
edit kalman01.m
2 Add a for-loop around the filter code.
for i=1:size(z,2)
b After the comment
end
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)';
element of input z.
Change
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.
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:
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
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
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.
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
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.
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.
• 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:
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.
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
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
To complete this tutorial, you should have basic familiarity with MATLAB software.
2-31
2 Tutorials
Required Products
• MATLAB
• MATLAB Coder
• 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”.
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 Kalman filter uses the previously estimated state, x_est, to predict the current
state, x_prd. The predicted state and covariance are calculated in:
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)';
Reference
Haykin, Simon. Adaptive Filter Theory. Upper Saddle River, NJ: Prentice-Hall, Inc.,
1996.
2-34
C Code Generation at the Command Line
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:
Location of Files
2-35
2 Tutorials
• 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.
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
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
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
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
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
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:
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
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”.
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.
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.
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.
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.
Note that:
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
In this part of the tutorial, you test the MEX function to verify that it provides the same
functionality as the original MATLAB code.
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;
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.
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.
• 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
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 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.
2-47
2 Tutorials
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.
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.
2-48
C Code Generation at the Command Line
% Estimation
S = H * p_prd' * H' + R;
B = H * p_prd';
klm_gain = (S \ B)';
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.
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.
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.
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.
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.
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
2-51
2 Tutorials
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.
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.
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.
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.
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
• 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.
build04
2 View the generated C code as before.
• 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:
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.
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
Use the MATLAB Compare Against option to compare two MATLAB files to examine
differences between files.
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.
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.
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
Learning Objectives
In this tutorial, you will learn how to:
Tutorial Prerequisites
• “What You Need to Know” on page 2-58
• “Required Products” on page 2-58
To complete this tutorial, you should have basic familiarity with MATLAB software.
Required Products
2-58
MEX Function Generation at the Command Line
• MATLAB
• MATLAB Coder
• 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”.
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
( 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:
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.
2-60
MEX Function Generation at the Command Line
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:
Location of Files
2-61
2 Tutorials
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
Copy the tutorial files to a local solutions folder and create a local working 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.
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:
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)
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:
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.
You can use mex -setup to change the default compiler. See “Change Default
Compiler”.
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:
You can use codegen to check for issues at code generation time. codegen checks that
your MATLAB code is suitable for code generation.
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.
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.
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.
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
You are ready to begin the next task in this tutorial, “Validating the MEX Function” on
page 2-69.
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
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.
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.
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 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
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.
2-71
2 Tutorials
You use the test script test01.m to test the MEX function euclidean03_mex.
2-72
MEX Function Generation at the Command Line
end
axis([0 1 0 1 0 1]);grid;
pause(.5);
Running the Test Script
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.
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
2-73
2 Tutorials
x2=x(1:2,:);
x2d=x2(:,47);
cb2d=cb(1:2,1:6:216);
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.
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.
test03
This time, the MEX function runs and outputs the vector y in matrix cb that is
closest to x2d in two dimensions.
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.
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
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.
test04
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.
1 Provide a new input parameter, N, to specify the number of elements to consider. The
new function signature is:
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.
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.
test05
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.
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
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
For more information and a complete list of compilation options, see codegen.
3-2
Testing MEX Functions in MATLAB
3-3
3 Best Practices for Working with MATLAB Coder
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
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.
N = 73113;
• 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:
3-5
3 Best Practices for Working with MATLAB Coder
3-6
Separating Your Test Bench from Your Function Code
3-7
3 Best Practices for Working with MATLAB Coder
3-8
File Naming Conventions
For example, the file naming convention in the Generating MEX Functions getting
started tutorial is:
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
Phone: 508-647-7000
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
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
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
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
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
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
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
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
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
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
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
xvii
Specify Type Proposal Options . . . . . . . . . . . . . . . . . . . . . . 15-36
xviii Contents
Handling Non-Constant mpower Exponents . . . . . . . . . . 15-114
xix
Expensive Fixed-Point Operations . . . . . . . . . . . . . . . . . . 15-136
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
xxi
Built-In Function Returns Double-Precision . . . . . . . . . . . 17-30
xxii Contents
Define Constant Input Parameters Using the App . . . . . . 18-23
xxiii
Check Code With the Code Analyzer . . . . . . . . . . . . . . . . . . 19-6
xxiv Contents
Collect and View Line Execution Counts for Your MATLAB
Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-28
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
xxvi Contents
Run the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-43
xxvii
Disable Creation of the Code Generation Report . . . . . . . 21-79
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
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-176
Run-time Stack Overflow . . . . . . . . . . . . . . . . . . . . . . . . 21-176
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
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
xxxi
Prevent Circular Data Dependencies with One-Pass or
Single-Pass Linkers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-24
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
xxxiii
Edge Detection on Images . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-7
xxxiv Contents
Accelerating Simulation of Bouncing Balls . . . . . . . . . . . . 26-39
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
xxxvi Contents
Minimize Dynamic Memory Allocation . . . . . . . . . . . . . . . . 29-20
xxxvii
memset Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-54
memset Optimization for an Integer Constant . . . . . . . . . . 29-54
memset Optimization for Float or Double Zero . . . . . . . . . 29-55
xxxviii Contents
Specify Generation of Reentrant Code Using the Command-
Line Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-12
xxxix
1
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
• 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-3
1 About MATLAB Coder
1-4
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
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
2-4
Prerequisites for C/C++ Code Generation from MATLAB
2-5
2 Design Considerations for C/C++ Code Generation
• 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.
• 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
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.
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:
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();
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.
2-10
Differences in Behavior After Compiling MATLAB Code
element at a time.
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.
2-11
2 Design Considerations for C/C++ Code Generation
Complex Numbers
See “Code Generation for Complex Data” on page 6-4.
2-12
MATLAB Language Features Supported for C/C++ Code Generation
• 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
• 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
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.
3-2
Code Generation for System Objects
whether you are writing simple functions, working interactively in the command window,
or creating large applications.
3-3
4
• “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
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”.
4-2
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-3
4 Functions, Classes, and System Objects Supported for Code Generation
4-4
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-5
4 Functions, Classes, and System Objects Supported for Code Generation
4-6
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
Specifying constants
Specifying constants
4-7
4 Functions, Classes, and System Objects Supported for Code Generation
4-8
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-9
4 Functions, Classes, and System Objects Supported for Code Generation
4-10
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
Specifying constants
4-11
4 Functions, Classes, and System Objects Supported for Code Generation
Specifying constants
4-12
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
Specifying constants
Specifying constants
4-13
4 Functions, Classes, and System Objects Supported for Code Generation
4-14
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-15
4 Functions, Classes, and System Objects Supported for Code Generation
4-16
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-17
4 Functions, Classes, and System Objects Supported for Code Generation
Specifying constants
Specifying constants
Specifying constants
4-18
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
Specifying constants
Specifying constants
4-19
4 Functions, Classes, and System Objects Supported for Code Generation
Specifying constants
Specifying constants
4-20
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-21
4 Functions, Classes, and System Objects Supported for Code Generation
4-22
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-23
4 Functions, Classes, and System Objects Supported for Code Generation
4-24
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-25
4 Functions, Classes, and System Objects Supported for Code Generation
4-26
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-27
4 Functions, Classes, and System Objects Supported for Code Generation
4-28
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-29
4 Functions, Classes, and System Objects Supported for Code Generation
4-30
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-31
4 Functions, Classes, and System Objects Supported for Code Generation
4-32
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
4-33
4 Functions, Classes, and System Objects Supported for Code Generation
4-34
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
• detectCheckerboardPoints(I1)
• detectCheckerobarPoints(I1,I2)
4-35
4 Functions, Classes, and System Objects Supported for Code Generation
• 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
4-37
4 Functions, Classes, and System Objects Supported for Code Generation
4-38
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
4-39
4 Functions, Classes, and System Objects Supported for Code Generation
4-40
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-41
4 Functions, Classes, and System Objects Supported for Code Generation
4-42
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-43
4 Functions, Classes, and System Objects Supported for Code Generation
4-44
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-45
4 Functions, Classes, and System Objects Supported for Code Generation
4-46
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-47
4 Functions, Classes, and System Objects Supported for Code Generation
Specifying constants
4-48
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
Specifying constants
4-49
4 Functions, Classes, and System Objects Supported for Code Generation
4-50
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-51
4 Functions, Classes, and System Objects Supported for Code Generation
4-52
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-53
4 Functions, Classes, and System Objects Supported for Code Generation
Specifying constants
4-54
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
4-55
4 Functions, Classes, and System Objects Supported for Code Generation
Specifying constants
Specifying constants
Specifying constants
4-56
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
4-57
4 Functions, Classes, and System Objects Supported for Code Generation
Specifying constants
Specifying constants
4-58
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
4-59
4 Functions, Classes, and System Objects Supported for Code Generation
4-60
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
else
% fopen successful, okay to call fread
A = fread(fid);
...
• The behavior of the generated code for fread
is compiler-dependent if you:
4-61
4 Functions, Classes, and System Objects Supported for Code Generation
4-62
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-63
4 Functions, Classes, and System Objects Supported for Code Generation
4-64
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
• 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
4-66
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-67
4 Functions, Classes, and System Objects Supported for Code Generation
Specifying constants
4-68
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-69
4 Functions, Classes, and System Objects Supported for Code Generation
4-70
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
Specifying constants
4-71
4 Functions, Classes, and System Objects Supported for Code Generation
• 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
4-73
4 Functions, Classes, and System Objects Supported for Code Generation
4-74
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
4-75
4 Functions, Classes, and System Objects Supported for Code Generation
4-76
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-77
4 Functions, Classes, and System Objects Supported for Code Generation
4-78
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-79
4 Functions, Classes, and System Objects Supported for Code Generation
4-80
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-81
4 Functions, Classes, and System Objects Supported for Code Generation
4-82
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-83
4 Functions, Classes, and System Objects Supported for Code Generation
4-84
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-85
4 Functions, Classes, and System Objects Supported for Code Generation
4-86
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-87
4 Functions, Classes, and System Objects Supported for Code Generation
4-88
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-89
4 Functions, Classes, and System Objects Supported for Code Generation
4-90
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-91
4 Functions, Classes, and System Objects Supported for Code Generation
4-92
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
4-93
4 Functions, Classes, and System Objects Supported for Code Generation
4-94
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-95
4 Functions, Classes, and System Objects Supported for Code Generation
4-96
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-97
4 Functions, Classes, and System Objects Supported for Code Generation
Specifying constants
4-98
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-99
4 Functions, Classes, and System Objects Supported for Code Generation
Specifying constants
• UT
• LT
• UHESS = true (the TRANSA can be either
true or false)
• SYM = true and POSDEF = true
4-100
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-101
4 Functions, Classes, and System Objects Supported for Code Generation
4-102
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-103
4 Functions, Classes, and System Objects Supported for Code Generation
Specifying constants
4-104
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-105
4 Functions, Classes, and System Objects Supported for Code Generation
4-106
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
size(coefs,j) = d(j)
size(coefs,m+1) = npieces
4-107
4 Functions, Classes, and System Objects Supported for Code Generation
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:
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.
4-108
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-109
4 Functions, Classes, and System Objects Supported for Code Generation
4-110
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-111
4 Functions, Classes, and System Objects Supported for Code Generation
4-112
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-113
4 Functions, Classes, and System Objects Supported for Code Generation
4-114
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-115
4 Functions, Classes, and System Objects Supported for Code Generation
4-116
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
4-117
4 Functions, Classes, and System Objects Supported for Code Generation
4-118
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-119
4 Functions, Classes, and System Objects Supported for Code Generation
4-120
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
4-121
4 Functions, Classes, and System Objects Supported for Code Generation
4-122
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-123
4 Functions, Classes, and System Objects Supported for Code Generation
4-124
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-125
4 Functions, Classes, and System Objects Supported for Code Generation
4-126
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-127
4 Functions, Classes, and System Objects Supported for Code Generation
4-128
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-129
4 Functions, Classes, and System Objects Supported for Code Generation
4-130
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-131
4 Functions, Classes, and System Objects Supported for Code Generation
4-132
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-133
4 Functions, Classes, and System Objects Supported for Code Generation
4-134
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-135
4 Functions, Classes, and System Objects Supported for Code Generation
4-136
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
4-137
4 Functions, Classes, and System Objects Supported for Code Generation
4-138
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
4-139
4 Functions, Classes, and System Objects Supported for Code Generation
4-140
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
4-141
4 Functions, Classes, and System Objects Supported for Code Generation
4-142
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-143
4 Functions, Classes, and System Objects Supported for Code Generation
4-144
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-145
4 Functions, Classes, and System Objects Supported for Code Generation
4-146
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-147
4 Functions, Classes, and System Objects Supported for Code Generation
Specifying constants
4-148
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-149
4 Functions, Classes, and System Objects Supported for Code Generation
4-150
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-151
4 Functions, Classes, and System Objects Supported for Code Generation
4-152
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-153
4 Functions, Classes, and System Objects Supported for Code Generation
4-154
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-155
4 Functions, Classes, and System Objects Supported for Code Generation
4-156
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-157
4 Functions, Classes, and System Objects Supported for Code Generation
4-158
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-159
4 Functions, Classes, and System Objects Supported for Code Generation
4-160
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-161
4 Functions, Classes, and System Objects Supported for Code Generation
4-162
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-163
4 Functions, Classes, and System Objects Supported for Code Generation
4-164
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
4-165
4 Functions, Classes, and System Objects Supported for Code Generation
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
4-167
4 Functions, Classes, and System Objects Supported for Code Generation
4-168
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-169
4 Functions, Classes, and System Objects Supported for Code Generation
4-170
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
4-171
4 Functions, Classes, and System Objects Supported for Code Generation
4-172
Functions and Objects Supported for C and C++ Code Generation — Alphabetical List
Specifying constants
4-173
4 Functions, Classes, and System Objects Supported for Code Generation
4-174
Functions and Objects Supported for C and C++ Code Generation — Category List
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.
4-177
4 Functions, Classes, and System Objects Supported for Code Generation
4-178
Functions and Objects Supported for C and C++ Code Generation — Category List
4-179
4 Functions, Classes, and System Objects Supported for Code Generation
Casting in MATLAB
4-180
Functions and Objects Supported for C and C++ Code Generation — Category List
4-181
4 Functions, Classes, and System Objects Supported for Code Generation
4-182
Functions and Objects Supported for C and C++ Code Generation — Category List
4-183
4 Functions, Classes, and System Objects Supported for Code Generation
4-184
Functions and Objects Supported for C and C++ Code Generation — Category List
4-185
4 Functions, Classes, and System Objects Supported for Code Generation
4-186
Functions and Objects Supported for C and C++ Code Generation — Category List
4-187
4 Functions, Classes, and System Objects Supported for Code Generation
4-188
Functions and Objects Supported for C and C++ Code Generation — Category List
4-189
4 Functions, Classes, and System Objects Supported for Code Generation
4-190
Functions and Objects Supported for C and C++ Code Generation — Category List
4-191
4 Functions, Classes, and System Objects Supported for Code Generation
4-192
Functions and Objects Supported for C and C++ Code Generation — Category List
• detectCheckerboardPoints(I1)
• detectCheckerobarPoints(I1,I2)
4-193
4 Functions, Classes, and System Objects Supported for Code Generation
4-194
Functions and Objects Supported for C and C++ Code Generation — Category List
4-195
4 Functions, Classes, and System Objects Supported for Code Generation
4-196
Functions and Objects Supported for C and C++ Code Generation — Category List
4-197
4 Functions, Classes, and System Objects Supported for Code Generation
else
% fopen successful, okay to call fread
A = fread(fid);
...
• The behavior of the generated code for fread is compiler-dependent if
you:
4-198
Functions and Objects Supported for C and C++ Code Generation — Category List
4-199
4 Functions, Classes, and System Objects Supported for Code Generation
• 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
4-201
4 Functions, Classes, and System Objects Supported for Code Generation
4-202
Functions and Objects Supported for C and C++ Code Generation — Category List
4-203
4 Functions, Classes, and System Objects Supported for Code Generation
4-204
Functions and Objects Supported for C and C++ Code Generation — Category List
4-205
4 Functions, Classes, and System Objects Supported for Code Generation
4-206
Functions and Objects Supported for C and C++ Code Generation — Category List
4-207
4 Functions, Classes, and System Objects Supported for Code Generation
4-208
Functions and Objects Supported for C and C++ Code Generation — Category List
4-209
4 Functions, Classes, and System Objects Supported for Code Generation
4-210
Functions and Objects Supported for C and C++ Code Generation — Category List
Exponents in MATLAB
Function Remarks and Limitations
exp —
expm —
4-211
4 Functions, Classes, and System Objects Supported for Code Generation
• Be real.
• Be sorted in ascending order.
4-212
Functions and Objects Supported for C and C++ Code Generation — Category List
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:
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.
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.
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.
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.
• 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
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.
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 CC struct return value does not include the PixelIdxList field.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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'.
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.
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.
4-240
Functions and Objects Supported for C and C++ Code Generation — Category List
4-241
4 Functions, Classes, and System Objects Supported for Code Generation
4-242
Functions and Objects Supported for C and C++ Code Generation — Category List
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
size(coefs,1) = prod(d)*npieces
size(coefs,2) = order
The second dimension must be fixed length.
The code generation software does not remove the singleton dimensions.
However, MATLAB might remove singleton dimensions.
4-244
Functions and Objects Supported for C and C++ Code Generation — Category List
• UT
• LT
4-245
4 Functions, Classes, and System Objects Supported for Code Generation
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.
4-247
4 Functions, Classes, and System Objects Supported for Code Generation
4-248
Functions and Objects Supported for C and C++ Code Generation — Category List
4-249
4 Functions, Classes, and System Objects Supported for Code Generation
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
4-251
4 Functions, Classes, and System Objects Supported for Code Generation
4-252
Functions and Objects Supported for C and C++ Code Generation — Category List
4-253
4 Functions, Classes, and System Objects Supported for Code Generation
4-254
Functions and Objects Supported for C and C++ Code Generation — Category List
4-255
4 Functions, Classes, and System Objects Supported for Code Generation
4-256
Functions and Objects Supported for C and C++ Code Generation — Category List
4-257
4 Functions, Classes, and System Objects Supported for Code Generation
4-258
Functions and Objects Supported for C and C++ Code Generation — Category List
4-259
4 Functions, Classes, and System Objects Supported for Code Generation
4-260
Functions and Objects Supported for C and C++ Code Generation — Category List
4-261
4 Functions, Classes, and System Objects Supported for 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
4-263
4 Functions, Classes, and System Objects Supported for Code Generation
4-264
Functions and Objects Supported for C and C++ Code Generation — Category List
4-265
4 Functions, Classes, and System Objects Supported for Code Generation
4-266
Functions and Objects Supported for C and C++ Code Generation — Category List
Polynomials in MATLAB
4-267
4 Functions, Classes, and System Objects Supported for Code Generation
4-268
Functions and Objects Supported for C and C++ Code Generation — Category List
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
4-270
Functions and Objects Supported for C and C++ Code Generation — Category List
4-271
4 Functions, Classes, and System Objects Supported for Code Generation
4-272
Functions and Objects Supported for C and C++ Code Generation — Category List
4-273
4 Functions, Classes, and System Objects Supported for Code Generation
• 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-274
Functions and Objects Supported for C and C++ Code Generation — Category List
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.
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.
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.
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.
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.
4-280
Functions and Objects Supported for C and C++ Code Generation — Category List
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
4-282
Functions and Objects Supported for C and C++ Code Generation — Category List
4-283
4 Functions, Classes, and System Objects Supported for Code Generation
4-284
Functions and Objects Supported for C and C++ Code Generation — Category List
4-285
4 Functions, Classes, and System Objects Supported for Code Generation
4-286
Functions and Objects Supported for C and C++ Code Generation — Category List
4-287
4 Functions, Classes, and System Objects Supported for Code Generation
4-288
Functions and Objects Supported for C and C++ Code Generation — Category List
4-289
4 Functions, Classes, and System Objects Supported for Code Generation
4-290
Functions and Objects Supported for C and C++ Code Generation — Category List
4-291
4 Functions, Classes, and System Objects Supported for Code Generation
4-292
Functions and Objects Supported for C and C++ Code Generation — Category List
4-293
4 Functions, Classes, and System Objects Supported for Code Generation
4-294
Functions and Objects Supported for C and C++ Code Generation — Category List
4-295
4 Functions, Classes, and System Objects Supported for Code Generation
Trigonometry in MATLAB
4-296
Functions and Objects Supported for C and C++ Code Generation — Category List
4-297
4 Functions, Classes, and System Objects Supported for Code Generation
4-298
Functions and Objects Supported for C and C++ Code Generation — Category List
4-299
5
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
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.
...
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
...
...
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);
...
5-5
5 Defining MATLAB Variables for C/C++ Code Generation
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
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.
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.
5-7
5 Defining MATLAB Variables for C/C++ Code Generation
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:
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
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”.
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
persistent PROD_X;
The definition should appear at the top of the function body, after the header and
comments, but before the first use of the variable. During code generation, the value of
the persistent variable is initialized to an empty matrix by default. You can assign your
own value after the definition by using the isempty statement, as in this example:
if isempty(PROD_X)
PROD_X = 1;
end
PROD_X = PROD_X * inputvalue;
end
5-10
Reuse the Same Variable with Different Properties
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).
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
5-12
Reuse the Same Variable with Different Properties
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 outside the if statement.
• 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
To avoid this error, use the workarounds provided in the following table.
5-15
5 Defining MATLAB Variables for C/C++ Code Generation
5-16
Supported Variable Types
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
6-2
Data Definition for Code Generation
6-3
6 Defining Data for Code Generation
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
function x = test1( )
x = zeros(3,3)+ 0i; %x is complex
for k = 1:numel(x)
x(k) = 3 + 4i;
end
end
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 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:
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
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.
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.
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
• 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.
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
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.
• 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
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
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.
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
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.
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
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
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
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
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
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.
Use the coder.typeof construct with the -args option on the codegen command line
(requires a MATLAB Coder license). For example:
7-6
Specify Variable-Size Data Without Dynamic Memory Allocation
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:
In this example, the input to function foo is a vector of real doubles without an upper
bound.
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:
Use the coder.varsize function to specify the upper bounds for all instances of a local
variable in a function. For example:
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:
7-8
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
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
7-10
Define Variable-Size Data for Code Generation
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
7-11
7 Code Generation for Variable-Size Data
When dynamic memory allocation is used, MATLAB does not check for upper bounds; it
assumes variable-size data is unbounded.
When static allocation is used, this function infers that y is a matrix with three
dimensions, where:
7-12
Define Variable-Size Data for Code Generation
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:
In this case, the code generation report represents the size of matrix y like this:
• Define B as a variable-size 2-by-2 matrix, where each dimension has an upper bound
of 64:
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
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:
For more information about the syntax, see the coder.varsize reference page.
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:
7-14
Define Variable-Size Data for Code Generation
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
7-15
7 Code Generation for Variable-Size Data
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:
for i = 1:numel(data)
data(i).color = rand-0.5;
data(i).values = 1:i;
end
y = 0;
for i = 1:numel(data)
if data(i).color > 0
y = y + sum(data(i).values);
end;
end
• coder.varsize('data.A(:).B')
In this example, data is a scalar variable that contains matrix A. Each element of
matrix A contains a variable-size field B.
• coder.varsize('data(:).A(:).B')
This expression defines field B inside each element of matrix A inside each element of
matrix data to be variable sized.
7-16
C Code Interface for Arrays
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.
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.
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);
}
7-18
C Code Interface for Arrays
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:
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:
7-19
7 Code Generation for Variable-Size Data
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.
7-20
C Code Interface for Arrays
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
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:
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:
7-23
7 Code Generation for Variable-Size Data
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:
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:
You can define variable-size data by assigning a variable to a matrix with nonconstant
dimensions. For example:
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
• 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:
7-25
7 Code Generation for Variable-Size Data
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
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.
7-27
7 Code Generation for Variable-Size Data
y(:) = z;
Workaround
For example, if the shape of array A is :?x:?x:? and size(A,3)==1, size(A) returns:
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:
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.
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
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
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
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.
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:
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
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
• 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}].
7-34
Variable-Sizing Restrictions for Code Generation of Toolbox Functions
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.
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.
7-36
Variable-Sizing Restrictions for Code Generation of Toolbox Functions
7-37
7 Code Generation for Variable-Size Data
7-38
Variable-Sizing Restrictions for Code Generation of Toolbox Functions
7-39
7 Code Generation for Variable-Size Data
7-40
8
8-2
Structure Operations Allowed for Code Generation
• 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
...
S = struct('a', 0, 'b', 1, 'c', 2);
p = S;
...
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
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
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.”.
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;
...
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.
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
For example, the following function defines structure X to be persistent and initializes its
fields a and b:
if isempty(X)
X.a = 1;
X.b = 2;
end
8-8
Index Substructures and Fields
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:
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.
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
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);
8-11
8 Code Generation for MATLAB Structures
You cannot assign mxArrays to structure elements; convert mxArrays to known types
before code generation (see “Working with mxArrays” on page 14-17).
8-12
Pass Structure Arguments 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.
To open the Generate dialog box, on the Generate Code page, click the Generate
arrow.
• Source Code
• Static Library
• Dynamic Library
• Executable
On the All Settings tab, set the Pass structures by reference to entry-point
functions option to:
8-13
8 Code Generation for MATLAB Structures
For example:
cfg.PassStructByReference = true;
To create a folder and get copies of the example files, click Open This Example.
function y = my_struct_in(s)
%#codegen
y = s.f;
Generate code. Specify that the input argument has the type of the variable str.
codegen -config cfg -args {str} my_struct_in
/*
* File: my_struct_in.c
*
8-14
Pass Structure Arguments by Reference or by Value
/* 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]
*/
Generate code. Specify that the input argument has the type of the variable str.
codegen -config cfg -args {str} my_struct_in
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]
*/
8-16
Pass Structure Arguments by Reference or by Value
function s = my_struct_out(x)
%#codegen
s.f = x;
a = 1:4;
cfg = coder.config('lib');
cfg.PassStructByReference = true;
Generate code. Specify that the input argument has the type of the variable a.
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]
*/
cfg.PassStructByReference = false;
Generate code. Specify that the input argument has the type of the variable a.
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]
*/
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
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);
cfg = coder.config('lib');
cfg.PassStructByReference = false;
Generate code. Specify that the first input has the type of a and the second input has the
type of str.
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
/*
* File trailer for my_struct_inout.c
*
* [EOF]
*/
8-21
9
• 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.
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
More About
• “Cell Array Requirements and Limitations for Code Generation” on page 9-10
9-3
9 Code Generation for Cell Arrays
• 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
9-5
9 Code Generation for Cell Arrays
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
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
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
To see the types that the code generation software specified for c:
9-8
Name the Structure Type That Represents a Cell Array
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
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.
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
When the for-loop has constant bounds, it is unrolled. For large cell arrays, the
unrolling can increase compile time and generate inefficient code.
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.
X = {1 2};
for i=1:n
X{end + 1} = 3;
end
X = {1 'a' 2 'b'};
for i=1:n
X{end + 1} = 3;
end
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
More About
• “Differences in Behavior After Compiling MATLAB Code” on page 2-8
9-13
9 Code Generation for Cell Arrays
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.
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
10-2
Enumerated Types Supported for Code Generation
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:
• 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:
The base type determines the representation of the enumerated type in generated C/C++
code.
10-4
Enumerated Types Supported for Code Generation
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
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.
10-6
Generate Code for Enumerated Data from MATLAB Algorithms
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
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
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 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.
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
Assignment Operator, =
Example Result
xon = LEDcolor.GREEN xon =
xoff = LEDcolor.RED
GREEN
xoff =
RED
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
10-11
10 Code Generation for Enumerated Data
10-12
Include Enumerated Data in Control Flow Statements
• 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.
This definition must reside on the MATLAB path in a file with the same name as the
class, sysMode.m.
This definition must reside on the MATLAB path in a file called LEDcolor.m.
10-13
10 Code Generation for Enumerated Data
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.
if state == sysMode.ON
led = LEDcolor.GREEN;
else
led = LEDcolor.RED;
end
1 Generate a MEX function for displayState. Use the -args option to pass one of
the allowable values for the enumerated data input as a sample value.
displayState_mex(sysMode.OFF)
ans =
RED
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.
This definition must reside on the MATLAB path in a file with the same name as the
class, VCRButton.m.
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;
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
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.
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
function initialize()
% Perform initialization.
function boot()
% Boot the device.
1 Generate a MEX executable for Setup. Use the -args option to pass one of the
allowable values for the enumerated data input as a sample value.
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
10-19
10 Code Generation for Enumerated Data
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:
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.
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.
10-21
10 Code Generation for Enumerated Data
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
};
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
To create a working folder and get copies of the example files, click Open This
Example.
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
if state == sysMode.ON
led = LEDcolor.GREEN;
else
10-23
10 Code Generation for Enumerated Data
led = LEDcolor.RED;
end
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.
/*
* 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
#endif /*typedef_LEDcolor*/
#ifndef enum_sysMode
#define enum_sysMode
enum sysMode
{
OFF,
ON
};
#endif /*enum_sysMode*/
#ifndef typedef_sysMode
#define typedef_sysMode
#endif /*typedef_sysMode*/
#endif
/*
* File trailer for displayState_types.h
*
* [EOF]
*/
10-25
10 Code Generation for Enumerated Data
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
1 Define the enumerated type sysMode. Store it in sysMode.m on the MATLAB path.
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.
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
};
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.
methods(Static)
function y=addClassNameToEnumNames()
y=true;
end
end
end
8 Clear existing class instances.
clear classes
9 Generate code.
10-28
Control Names of Enumerated Type Values in Generated Code
enum LEDcolor
{
LEDcolor_GREEN = 1,
LEDcolor_RED
};
10-29
10 Code Generation for Enumerated Data
10-30
Restrictions on Use of Enumerated Data 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.
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
• 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
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
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:
• 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
• 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');
11-5
11 Code Generation for MATLAB Classes
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
11-6
MATLAB Classes Definition for Code Generation
elseif nargin == 2
a = varargin{1};
b = varargin{2};
end
end
11-7
11 Code Generation for MATLAB Classes
11-8
Generate Code for MATLAB Value Classes
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.
11-9
11 Code Generation for MATLAB Classes
11-10
Generate Code for MATLAB Value Classes
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
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.
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
11-15
11 Code Generation for MATLAB Classes
11-16
MATLAB Classes in Code Generation Reports
The report displays an alphabetical hierarchical list of the classes used in the your
MATLAB code. For each class, you can:
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”.
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.
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
obj.mymethod().myprop=...
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
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
function usehandle1
p = mycls;
for i = 1:10
p.prop = mycls;
end
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.
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
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
• 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
• 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
function addval(m)
%#codegen
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.
m = zeros(3);
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.
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
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);
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;
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.
You cannot pass function handles as inputs to or outputs from primary functions. For
example, consider this function:
function x = plotFcn(fhandle, data)
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
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:
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
%#codegen
function [x,y,z] = fcn(a,b,c)
[x,y,z] = subfcn(a,b,c);
You can use the following index expressions. The exp arguments must be constant
expressions or depend on a loop index variable.
Expression Description
varargin varargin{exp} Read the value of element 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
[cmlen,cmwth,cmhgt] = inch_2_cm(inlen,inwth,inhgt);
In the following example, the function fcn cannot detect a logical relationship between
the index expression j and the index variable i:
%#codegen
function [x,y,z] = fcn(a,b,c)
[x,y,z] = subfcn(a,b,c);
13-4
Apply Operations to a Variable Number of Arguments
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);
[cmlen,cmwth,cmhgt] = inch_2_cm(inlen,inwth,inhgt);
• 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
• 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
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.
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);
13-7
13 Defining Functions for Code Generation
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.
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.
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
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
No No
Generate
C code
Function
on Yes
MATLAB
path?
No
Generate error
14-3
14 Calling Functions for Code Generation
• Searches two paths, the code generation path and the MATLAB path
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
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”).
14-5
14 Calling Functions for Code Generation
14-6
Resolution of File Types on Code Generation Path
Start
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
....
14-8
Call Local Functions
The following example illustrates how to define and call a local function mean:
len = length(vals);
mean = avg(vals, len);
stdev = sqrt(sum(((vals-avg(vals,len)).^2))/len);
plot(vals,'-+');
14-9
14 Calling Functions for Code Generation
14-10
Call MATLAB Functions
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).
14-11
14 Calling Functions for Code Generation
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.
c = sqrt(a^2 + b^2);
create_plot(a, b, color);
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.
14-12
Call MATLAB Functions
The report highlights the patch and axis functions to indicate that they are
supported only within the MATLAB environment.
14-13
14 Calling Functions for Code Generation
• 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).
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:
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.
function y = foo
coder.extrinsic('rat');
[N D] = rat(pi);
y = 0;
y = feval('min', N, D);
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.
14-17
14 Calling Functions for Code Generation
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.
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.
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:
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:
14-18
Call MATLAB Functions
• 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
14-19
15
Fixed-Point Conversion
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.
• 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
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.
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.
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
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
Prerequisites
• 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”.
15-9
15 Fixed-Point Conversion
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 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;
15-10
Propose Fixed-Point Data Types Based on Simulation Ranges
xlabel('Time (s)')
figure(gcf)
disp('Test complete.')
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-11
15 Fixed-Point 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.
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
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.
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.
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.
15-18
Propose Fixed-Point Data Types Based on Simulation Ranges
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.
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
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
Prerequisites
• 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”.
15-23
15 Fixed-Point Conversion
% 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 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;
end
subplot(2,1,2)
plot(1:len,y_out)
xlabel('Time')
ylabel('Amplitude')
title('Output Signal (DTI)')
disp('Test complete.');
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
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
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).
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.
15-27
15 Fixed-Point Conversion
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.
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:
15-30
Propose Fixed-Point Data Types Based on Derived Ranges
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
15-34
Propose Fixed-Point Data Types Based on Derived Ranges
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
15-36
Specify Type Proposal Options
15-37
15 Fixed-Point Conversion
15-38
Specify Type Proposal Options
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”.
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
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
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
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-43
15 Fixed-Point Conversion
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
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).
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
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.
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.
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
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
Prerequisites
• 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”.
x = linspace(-10,10,1e3);
for itr = 1e3:-1:1
y(itr) = my_fcn( x(itr) );
end
plot( x, y );
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-50
Replace the exp Function with a Lookup Table
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
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.
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
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 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.
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.
15-56
Replace the exp Function with a Lookup Table
function y = my_fcn_fixpt(x)
fm = get_fimath();
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
Prerequisites
• 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”.
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 );
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-60
Replace a Custom Function with a Lookup Table
The app screens call_custom_fcn.m for code violations and code generation
readiness issues. The app opens the Review Code Generation Readiness page.
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
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.
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 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
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.
15-66
Replace a Custom Function with a Lookup Table
function y = call_custom_fcn_fixpt(x)
fm = get_fimath();
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
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
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
• 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”.
15-69
15 Fixed-Point Conversion
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.';
h = h + update;
h(8) = 1;
ho = h;
end
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;
% build Titles
floatTitle = [ escapedFcnName ' > ' 'float : ' escapedVarName ];
fixedTitle = [ escapedFcnName ' > ' 'fixed : ' escapedVarName ];
data = load('filterData.mat');
switch varName
case 'y'
x_vec = data.symbols;
otherwise
% Plot only output 'y' for this example, skip the rest
15-71
15 Fixed-Point Conversion
end
end
hold on
scatter(real(x_plot),imag(x_plot), 'bo');
hold on
scatter(real(y_plot),imag(y_plot), 'rx');
title(figTitle);
end
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.
15-72
Visualize Differences Between Floating-Point and Fixed-Point Results
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
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)).
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.
15-74
Visualize Differences Between Floating-Point and Fixed-Point Results
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 .
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.
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
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
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
•
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
To revert to the types proposed by the automatic conversion, in the histogram window,
click .
15-81
15 Fixed-Point Conversion
• Variable
Variable name. Variables are classified and sorted as inputs, outputs, persistent, or
local variables.
• Type
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.
• 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:
• 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.
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
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”.
• 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
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
15-88
Automated Fixed-Point Conversion
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.
15-90
Automated Fixed-Point Conversion
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.
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
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.
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.
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:
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));
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.
• 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
•
On the Convert to Fixed Point page, click the Simulate arrow .
15-102
Automated Fixed-Point Conversion
• 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
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.
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 your original algorithm uses scaled doubles, the app also provides overflow information
for these expressions.
See Also
15-106
Convert Fixed-Point Conversion Project to MATLAB Scripts
Prerequisites
To obtain these files, complete the example “Propose Fixed-Point Data Types Based on
Simulation Ranges” on page 15-9, including these steps:
• 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 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.
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.
addpath c:\coder\ex_2ndOrder_filter\codegen\ex_2ndOrder_filter\fixpt
2 Run the script:
ex_2ndOrder_filter_script
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
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
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
15-110
Generated Fixed-Point Code
For example, here is the fixed-point code generated for the constant expression x = 1/
sqrt(2) when the selected word length is 14.
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
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
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)
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
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
% 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
• 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);
%% 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
15-114
Generated Fixed-Point Code
SpecifyPrecision in the generated code. With this setting , the output data type can
be determined at compile time.
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
• 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.
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
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.
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
15-119
15 Fixed-Point Conversion
• 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.
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.
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.
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.
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.
For more information, see “Specify Type Proposal Options” on page 15-36.
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 .
• 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.
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.
15-124
Automated Fixed-Point Conversion Best Practices
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.
HDL
15-125
15 Fixed-Point Conversion
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.
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.
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.
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
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.
15-127
15 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.
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
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
For fixed-point conversion, there is no programmatic interface for the Simulation Data
Inspector.
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:
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.
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
• All runs, data, and properties from the Runs and Comparisons panes.
• Check box selection state for data in the Runs pane.
15-132
Custom Plot Functions
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.
• A structure that holds the name of the variable and the function that uses it.
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.
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
15-134
Data Type Issues in Generated Code
When conversion is complete, open the fixed-point conversion HTML report to view the
highlighting. Click View report in the Type Validation Output tab.
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.
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.
Multiword Operations
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
Create a fixed-point configuration object and configure the test file name. For example:
fixptcfg = coder.config('fixpt');
fixptcfg.TestBenchName = 'fun_with_matlab_test';
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:
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
• 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.
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
Prerequisites
• 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”.
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 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;
16-6
Propose Fixed-Point Data Types Based on Simulation Ranges
legend('Input','Output')
end
xlabel('Time (s)')
figure(gcf)
disp('Test complete.')
Create a fixed-point configuration object and configure the test file name.
fixptcfg = coder.config('fixpt');
fixptcfg.TestBenchName = 'ex_2ndOrder_filter_test';
Create a code configuration object to generate a C static library. Enable the code
generation report.
cfg = coder.config('lib');
cfg.GenerateReport = true;
fixptcfg.ComputeSimulationRanges = true;
fixptcfg.DefaultWordLength = 16;
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.
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
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);
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
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
Prerequisites
• 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”.
16-11
16 Automated Fixed-Point Conversion Using Programmatic Workflow
% 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 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;
end
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.')
Create a fixed-point configuration object and configure the test file name.
fixptcfg = coder.config('fixpt');
fixptcfg.TestBenchName = 'dti_test';
Specify design range information for the dti function input parameter u_in.
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;
Create a code configuration object to generate a C static library. Enable the code
generation report.
cfg = coder.config('lib');
cfg.GenerateReport = true;
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;
16-14
Propose Fixed-Point Data Types Based on Derived Ranges
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.
Click the link to the type proposal report for the dti function, dti_report.html.
16-15
16 Automated Fixed-Point Conversion Using Programmatic Workflow
% 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
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
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
• MATLAB
• MATLAB Coder
• Fixed-Point Designer
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
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
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
fixptcfg = coder.config('fixpt');
Set the test bench name. In this example, the test bench function name is
overflow_test.
fixptcfg.TestBenchName = 'overflow_test';
fixptcfg.DefaultWordLength = 16;
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'')'];
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.
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
Prerequisites
• 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”.
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
16-24
Replace the exp Function with a Lookup Table
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);
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.
function y = my_fcn_fixpt(x)
fm = get_fimath();
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
Prerequisites
• 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
function y = call_custom_fcn(x)
y = custom_fcn(x);
end
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 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);
function y = call_custom_fcn_fixpt(x)
fm = get_fimath();
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
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.
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
Prerequisites
• 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”.
16-29
16 Automated Fixed-Point Conversion Using Programmatic Workflow
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.';
h = h + update;
h(8) = 1;
ho = h;
end
% load data
data = load('filterData.mat');
d = data.symbols;
16-30
Visualize Differences Between Floating-Point and Fixed-Point Results
% 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;
% build Titles
floatTitle = [ escapedFcnName ' > ' 'float : ' escapedVarName ];
fixedTitle = [ escapedFcnName ' > ' 'fixed : ' escapedVarName ];
data = load('filterData.mat');
switch varName
case 'y'
x_vec = data.symbols;
16-31
16 Automated Fixed-Point Conversion Using Programmatic Workflow
otherwise
% Plot only output 'y' for this example, skip the rest
end
end
hold on
scatter(real(x_plot),imag(x_plot), 'bo');
hold on
scatter(real(y_plot),imag(y_plot), 'rx');
title(figTitle);
end
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;
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
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
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”.
17-2
Generate Single-Precision C Code at the Command Line
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
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;
disp('Test complete.')
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.
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.
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.
The code generation report displays the generated code for ex_2ndOrder_filter.c.
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
17-7
17 Single-Precision Conversion
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”.
17-8
Generate Single-Precision C Code Using the MATLAB Coder App
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
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;
disp('Test complete.')
17-10
Generate Single-Precision C Code Using the MATLAB Coder App
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.
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.
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.
17-12
Generate Single-Precision C Code Using the MATLAB Coder App
MATLAB Coder builds the project and generates a C static library and supporting
files in the default subfolder, codegen/lib/ex_2ndOrder_filter.
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
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”.
17-14
Generate Single-Precision MATLAB Code
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
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;
disp('Test complete.')
17-16
Generate Single-Precision MATLAB Code
17-17
17 Single-Precision Conversion
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.
17-19
17 Single-Precision Conversion
17-20
Generate Single-Precision MATLAB Code
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.
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
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
17-24
Single-Precision Conversion Best Practices
For best results, the test file must exercise the algorithm over its full operating range.
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.
17-25
17 Single-Precision Conversion
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.
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 the MATLAB Coder app, perform the Check for Run-Time Issues step with
single-precision conversion enabled.
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:
When you repeat the code generation in the same MATLAB session, this practice saves
you time.
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
function c = mysine(a)
c = sin(a);
end
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.
17-28
Warnings from Conversion to Single-Precision C/C++ Code
To address this warning, specify use of the C99 (ISO) standard math library.
Consider the function geterf that calls the built-in function erf.
function y = geterf(x)
y = erf(x);
end
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.
To address this warning, rewrite your code so that it does not use the function that is
implemented in double precision.
Consider the function mysum that calls the built-in function sum.
function y = mysum(x)
y = sum(int32(x));
end
17-30
Warnings from Conversion to Single-Precision C/C++ Code
A = 1:10;
codegen -singleC -config:lib -args {A} mysum -report
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.
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
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.
function c = dut(a,b)
c = int32(a) + b;
end
17-32
MATLAB Language Features Supported for Single-Precision Conversion
• 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
• Class properties
• Constructors
• Methods
• Specializations
• 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
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.
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
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
18-3
18 Setting Up a MATLAB Coder Project
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.
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
18-5
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:
zeros(1,4,'uint16')
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:
18-6
Define Input Parameters by Example 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 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')
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.
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
• 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).
{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
• 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.
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.
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
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
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
For more information about defining other types, see the following table.
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:
18-13
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 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 .
• 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.
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
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.
18-15
18 Setting Up a MATLAB Coder Project
Property Description
project settings dialog box Custom Code
tab.
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.
Default: 0
Select the name field of the structure that you want to rename. Enter the new name.
1
To the right of the structure, click
2 Enter the field name. Specify the class, size, and complexity of the field.
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.
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:
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
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.
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.
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.
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.
Default: 0
18-21
18 Setting Up a MATLAB Coder Project
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.
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
The app uses the value of the specified MATLAB expression as a compile-time
constant.
18-23
18 Setting Up a MATLAB Coder Project
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
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
For MEX functions, if you use global data, you must also specify whether to synchronize
this data between MATLAB and the MEX function.
• 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.
18-26
Specify Global Variable Type and Initial Value Using the App
18-27
18 Setting Up a MATLAB Coder Project
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.
18-29
18 Setting Up a MATLAB Coder Project
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
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
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
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
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.
18-34
Code Generation Readiness Screening in the MATLAB Coder App
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
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
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
• “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
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
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
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
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
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.
19-8
Code Generation Readiness Tool
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.
• 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
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.
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
19-15
19 Preparing MATLAB Code for C/C++ Code Generation
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
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));
On the MATLAB Toolstrip Apps tab, under Code Generation, click the MATLAB
Coder app icon.
1 On the Select Source Files page, type or select the name of the entry-point
function mcadd.
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:
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.
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.
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
The Finish Workflow page indicates that code generation succeeded. It provides a
project summary and links to the generated output.
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
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
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
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.
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
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
• 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.
19-24
Design Considerations When Writing MATLAB Code for Code Generation
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
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.
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.
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
Color Indicates
Green One of the following situations:
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
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.
20-2
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
20-4
Running MEX Functions
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.
20-5
20 Testing MEX Functions in MATLAB
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
More About
• “Why Test MEX Functions in MATLAB?” on page 20-2
20-7
20 Testing MEX Functions in MATLAB
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
20-9
20 Testing MEX Functions in MATLAB
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.
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:
20-10
Debug Run-Time Errors
This example shows the run-time stack trace for MEX function mlstack_mex:
mlstack_mex(-1)
Error in ==>mlstack>mayfail at 31
y = x(u);
• The function call sequence prior to the failure.
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
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.
20-12
Using MEX Functions That MATLAB Coder Generates
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
20-14
21
21-2
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
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.
21-4
Generating C/C++ Static Libraries from MATLAB Code
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.
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));
On the MATLAB Toolstrip Apps tab, under Code Generation, click the MATLAB
Coder app icon.
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.
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:
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.
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
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.
The Finish Workflow page indicates that code generation succeeded. It provides a
project summary and links to generated output.
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
• 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.
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
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));
On the MATLAB Toolstrip Apps tab, under Code Generation, click the MATLAB
Coder app icon.
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.
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:
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.
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.
The Finish Workflow page indicates that code generation succeeded. It provides a
project summary and links to generated output.
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:
21-12
Generating C/C++ Dynamically Linked Libraries from MATLAB Code
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
In the same local writable folder, create a MATLAB file, coderand_test.m, that calls
coderand.
function y = coderand_test()
y = coderand();
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
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.
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.
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 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.
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.
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
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
/*
* Arguments : int argc
* const char * const argv[]
* Return Type : int
*/
int main(int argc, const char * const argv[])
{
(void)argc;
(void)argv;
/*
* File trailer for main.c
*
* [EOF]
*/
2 Modify main.c so that it prints the results of a coderand call:
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;
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()
{
/*
* 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
/* 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:
#include <stdio.h>
• Change the declaration of main to
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]
*/
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.
21-22
Generating Standalone C/C++ Executables from MATLAB Code
system('coderand')
1 Write a MATLAB function, coderand, that generates a random scalar value from
the standard uniform distribution on the open interval (0,1):
/*
** 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
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.
• 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
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.
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:
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
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.
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
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.
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.
21-27
21 Generating C/C++ Code from MATLAB Code
21-28
Configure Build Settings
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.
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.
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
21-29
21 Generating C/C++ Code from MATLAB Code
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.
By default, if the name of the first entry-point MATLAB file is fcn1, the output file name
is:
Command-Line Alternative
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:
Command-Line Alternative
21-31
21 Generating C/C++ Code from MATLAB Code
You can specify build configuration parameters from the MATLAB Coder project settings
dialog box, the command line, or configuration object dialog boxes.
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.
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.
21-33
21 Generating C/C++ Code from MATLAB Code
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:
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
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
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
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:
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
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
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.
cfg = coder.config('lib');
2 To use built-in C types, set the DataTypeReplacement property to 'CBuiltIn'.
cfg.DataTypeReplacement = 'CBuiltIn';
21-38
Standard Math Libraries
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
• 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
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.
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
You can convert a project using the MATLAB Coder app or the command-line interface.
For example, to convert the project, myproject.prj to the script named myscript.m
use this command:
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.
myscript
21-43
21 Generating C/C++ Code from MATLAB Code
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.
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
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.
21-45
21 Generating C/C++ Code from MATLAB Code
• 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
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
ans =
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
Supported Classes
The following table presents the class names supported by MATLAB Coder.
• 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.
21-49
21 Generating C/C++ Code from MATLAB Code
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.
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
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
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:
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:
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)}
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
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)}
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:
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.
1 Write a function that computes the average of every n elements of a vector A and
stores them in a vector 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.
21-54
Specify Cell Array Inputs at the Command Line
• 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.
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.
21-55
21 Generating C/C++ Code from MATLAB Code
For example:
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:
The input argument is a 1x2 heterogeneous cell array whose first element is 1x1 char
and whose second element is 1x1 double.
For example:
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
t = coder.typeof({1 [2 3]})
t =
coder.CellType
1x2 heterogeneous cell
f0: 1x1 double
f1: 1x2 double
t = makeHomogeneous(t)
t =
coder.CellType
1x2 homogeneous cell
base: 1x:2 double
t = makeHomogeneous(coder.typeof({1 [2 3]}))
t =
coder.CellType
1x2 homogeneous cell
base: 1x:2 double
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
t = coder.typeof({1 2 3})
t =
coder.CellType
1x3 homogeneous cell
base: 1x1 double
t = makeHeterogeneous(t)
t =
coder.CellType
1x3 heterogeneous cell
f0: 1x1 double
f1: 1x1 double
f2: 1x1 double
t = makeHeterogeneous(coder.typeof({1 2 3}))
t =
coder.CellType
1x3 heterogeneous cell
f0: 1x1 double
f1: 1x1 double
f2: 1x1 double
21-58
Specify Cell Array Inputs at the Command Line
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.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.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
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
21-60
Specify Cell Array Inputs at the Command Line
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
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.
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
21-63
21 Generating C/C++ Code from MATLAB Code
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';
identity_mex(50)
ans =
42
Configure ConstantInputs so that the MEX function does not include the constant
input.
cfg.ConstantInputs = 'Remove';
identity_mex()
ans =
42
See Also
• “Specify Constant Inputs at the Command Line” on page 21-52
21-65
21 Generating C/C++ Code from MATLAB Code
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.
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.
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
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.
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]));
...
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
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.
• 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]));
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
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)
Specifies that the input parameter param is real. To specify that input U is real, call:
...
assert(isreal(U));
...
Specifies that the input parameter param is complex. To specify that input U is complex,
call:
...
assert(~isreal(U));
...
21-70
Define Input Properties Programmatically in the MATLAB File
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.
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');
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
...
• 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:
21-72
Define Input Properties Programmatically in the MATLAB File
%#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]));
...
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);
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
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
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'));
...
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.
21-76
Define Input Properties Programmatically in the MATLAB File
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)
21-77
21 Generating C/C++ Code from MATLAB Code
Speed Up Compilation
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.
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
• 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.
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
• Spaces (Spaces can lead to code generation failures in certain operating system
configurations)
• Tabs
• \, $, #, *, ?
• Non-7-bit ASCII characters, such as Japanese characters
21-80
Paths and File Infrastructure Setup
Naming Conventions
MATLAB Coder enforces naming conventions for MATLAB functions and generated files.
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
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
21-82
Paths and File Infrastructure Setup
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)')
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.
The following table describes how MATLAB Coder names generated files. MATLAB
Coder follows MATLAB conventions by providing platform-specific extensions for MEX
files.
21-84
Paths and File Infrastructure Setup
21-85
21 Generating C/C++ Code from MATLAB Code
• 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.
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;
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));
On the MATLAB Toolstrip Apps tab, under Code Generation, click the MATLAB
Coder app icon.
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.
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:
21-87
21 Generating C/C++ Code from MATLAB Code
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.
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.
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.
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.
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:
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
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.
For information on viewing entry-point functions in the code generation report, see “Code
Generation Reports” on page 22-10.
MEX_Function('entry_point_function_name',
... entry_point_function_param1,
... , entry_point_function_paramn)
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.
sharedmex('ep1', u)
sharedmex('ep2', u, v)
21-90
Generate Code for Multiple Entry-Point Functions
• 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
Workflow
To generate C/C++ code from MATLAB code that uses global data:
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.
21-92
Generate Code for Global Data
y = AR * 2;
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
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
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.
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:
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
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.
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
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
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.
• 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:
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.
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.
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
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.
The code generation report provides the following information about a constant global
variable:
21-100
Generate Code for Global Data
21-101
21 Generating C/C++ Code from MATLAB Code
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:
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.
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:
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:
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
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
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.
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.
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 :
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.
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
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:
For example:
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:
21-109
21 Generating C/C++ Code from MATLAB Code
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.
The Code Analyzer detects that variable B might change size in the for-loop. It issues
this warning:
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
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.
The -args option specifies the class, complexity, and size of each input to function
myuniquetol:
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.
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.
21-112
Generate Code for Variable-Size Data
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:
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.
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.
21-113
21 Generating C/C++ Code from MATLAB Code
B = [B A(i)];
k = i;
end
end
• Generate code.
The code generation software statically allocates the memory for B. It stores the size
of B in int B_size[2].
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.
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.
Prerequisites
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.
coderdemo_setup('coderdemo_atoms');
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
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);
'-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
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 =
x
y
vx
vy
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 =
21-117
21 Generating C/C++ Code from MATLAB Code
x
y
vx
vy
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
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
/* Free memory */
emxDestroyArray_Atom(atoms);
return(0);
21-119
21 Generating C/C++ Code from MATLAB Code
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)
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);
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
21-120
Generate Code for Variable-Size Data
Clean Up
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
21-123
21 Generating C/C++ Code from MATLAB Code
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.
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.
21-124
How MATLAB Coder Partitions Generated Code
mexcfg = coder.config('mex');
mexcfg.FilePartitionMethod = 'MapMFileToCFile';
2 Using the -config option, pass the configuration object to codegen:
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.
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:
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
MATLAB Coder generates source, header, and object files for foo and identity in your
output folder.
21-126
How MATLAB Coder Partitions Generated Code
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 = 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:
cfg = coder.config('lib')
cfg.TargetLang='C++'
2 Generate the C++ library:
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.
...
/* Function Definitions */
double foo(double u, double v)
{
return (double)(float)u + v;
}
...
21-128
How MATLAB Coder Partitions Generated Code
%#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).
%#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:
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
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
By default, MATLAB Coder generates the following files for MEX function (mex) targets.
By default, MATLAB Coder generates the following files for C/C++ static library targets.
By default, MATLAB Coder generates the following files for C/C++ dynamic library
targets.
By default, MATLAB Coder generates the following files for C/C++ executable targets.
21-131
21 Generating C/C++ Code from MATLAB Code
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:
You can change the name and location of generated files by using the codegen options -
o and -d.
21-132
How MATLAB Coder Partitions Generated Code
21-133
21 Generating C/C++ Code from MATLAB Code
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.
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.
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
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.
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.
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
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
21-137
21 Generating C/C++ Code from MATLAB Code
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
21-138
Customize the Post-Code-Generation Build Process
• 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.
addCompileFlags
groups is optional.
• Arguments:
buildinfo
21-139
21 Generating C/C++ Code from MATLAB Code
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
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.
21-141
21 Generating C/C++ Code from MATLAB Code
In addition to the required buildinfo and macrodefs arguments, you can use an
optional groups argument to group your options.
addIncludeFiles
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.
21-142
Customize the Post-Code-Generation Build Process
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 choose to specify groups, but omit paths, specify a null string ('') for paths.
addIncludePaths
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.
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
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.
addLinkFlags
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
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
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.
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.
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
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.
21-149
21 Generating C/C++ Code from MATLAB Code
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
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.
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:
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 choose to specify groups, but omit paths, specify a null string ('') for paths.
addSourceFiles
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.
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 choose to specify groups, but omit paths, specify a null string ('') for paths.
addSourcePaths
groups is optional.
• Arguments:
buildinfo
21-154
Customize the Post-Code-Generation Build Process
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
• 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
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
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.
21-157
21 Generating C/C++ Code from MATLAB Code
findIncludeFiles
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
• 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
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:
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.
getDefines
21-159
21 Generating C/C++ Code from MATLAB Code
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:
• 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
21-160
Customize the Post-Code-Generation Build Process
getFullFileList
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.
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
buildinfo
Build information stored in RTW.BuildInfo.
concatenatePaths
The logical value true or false.
replaceMatlabroot
The logical value true or false.
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
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.
getIncludePaths
buildinfo
Build information stored in RTW.BuildInfo.
replaceMatlabroot
The logical value true or false.
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:
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.
getLinkFlags
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:
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.
getNonBuildFiles
buildinfo
Build information stored in RTW.BuildInfo.
concatenatePaths
The logical value true or false.
replaceMatlabroot
The logical value true or false.
getSourceFiles
• Purpose: Get source files from project's build information.
• Syntax: srcfiles=getSourceFiles(buildinfo, concatenatePaths,
replaceMatlabroot, includeGroups, excludeGroups)
buildinfo
Build information stored in RTW.BuildInfo.
concatenatePaths
The logical value true or false.
21-166
Customize the Post-Code-Generation Build Process
replaceMatlabroot
The logical value true or false.
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:
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
getSourcePaths
buildinfo
Build information stored in RTW.BuildInfo.
replaceMatlabroot
The logical value true or false.
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:
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.
packNGo
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.
21-169
21 Generating C/C++ Code from MATLAB Code
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.
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 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:
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:
• 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
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 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.
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
cfg = coder.config('lib');
21-173
21 Generating C/C++ Code from MATLAB Code
cfg.PostCodeGenCommand = 'ScriptName';
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.
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.
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
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:
21-175
21 Generating C/C++ Code from MATLAB Code
Troubleshooting
21-176
22
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:
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”.
1 To open the Generate dialog box, on the Generate Code page, click the Generate
arrow .
22-2
Generation of Traceable Code
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:
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
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:
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”.
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”.
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
/* '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
/* '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;
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
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.
22-9
22 Verify Generated C/C++ Code
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
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.
22-10
Code Generation Reports
22-11
22 Verify Generated C/C++ Code
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.
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.
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:
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:
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.
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.
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
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
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.
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.
To open the MATLAB source code file associated with a generated C/C++ function, click
the link at the top of the code pane.
To see the definition for a generated C/C++ data type, click the data type in the
generated C/C++ code pane.
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
• 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/.
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
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.
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.
You can view information about the variables in your MATLAB code:
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
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
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
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.
22-22
Code Generation Reports
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.
• 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
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”.
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:
Loop Unrolling
The report does not display full information for unrolled loops. It displays data types of
one arbitrary iteration.
Dead Code
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.
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
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
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:
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
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;
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 };
/* 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);
}
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
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
• 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.
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
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.
23-4
Code Replacement Libraries
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
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:
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
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
1 Make sure that you have installed required software. Required software is:
• MATLAB
• MATLAB Coder
• C compiler
If you are not sure which library to use, explore available libraries.
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
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 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 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
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.
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
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
24-2
Custom Toolchain Registration
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
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:
Typical Workflow
The typical workflow for creating and using a custom toolchain definition is:
24-4
Custom Toolchain Registration
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
24-5
24 Custom Toolchain Registration
About coder.make.ToolchainInfo
The following properties in coder.make.ToolchainInfo represent your custom
toolchain:
24-6
About coder.make.ToolchainInfo
24-7
24 Custom Toolchain Registration
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 =
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.
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.
24-9
24 Custom Toolchain Registration
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');
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';
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
C Compiler
% ------------------------------
% 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');
C++ Compiler
% ------------------------------
% C++ Compiler
% ------------------------------
24-12
Toolchain Definition File with Commentary
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');
Linker
% ------------------------------
% Linker
% ------------------------------
tool = tc.getBuildTool('Linker');
tool.setDirective('Library','-L');
tool.setDirective('LibrarySearchPath','-I');
tool.setDirective('OutputFlag','-out:');
tool.setDirective('Debug','');
tool.setFileExtension('Executable','.exe');
tool.setFileExtension('Shared Library','.dll');
Archiver
% ------------------------------
24-13
24 Custom Toolchain Registration
% Archiver
% ------------------------------
tool = tc.getBuildTool('Archiver');
tool.setDirective('OutputFlag','-out:');
tool.setFileExtension('Static Library','.lib');
Builder
% ------------------------------
% Builder
% ------------------------------
tc.setBuilderApplication(tc.Platform);
Build Configurations
% --------------------------------------------
% BUILD CONFIGURATIONS
% --------------------------------------------
24-14
Toolchain Definition File with Commentary
debugFlag.Archiver = '$(ARDEBUG)';
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)');
24-15
24 Custom Toolchain Registration
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.
tc.validate
Next, register the custom toolchain, as described in “Register the Custom Toolchain” on
page 24-17.
24-16
Register the Custom Toolchain
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
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>'};
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: '*'
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
Before using the custom toolchain, register the custom toolchain, as described in
“Register the Custom Toolchain” on page 24-17.
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:
With the “Adding a Custom Toolchain” example, this would look like:
cfg.Toolchain = 'Intel v12.1 | nmake makefile (64-bit Windows)';
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
Consider the following two lines from an example toolchain definition file:
tool.setCommand('abc');
tool.setPath('/toolchain/');
To correct this issue:
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.
Otherwise, replace '' with the absolute path of the command file.
• 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.
24-21
24 Custom Toolchain Registration
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.
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);
To correct this issue, update the toolchain definition file and re-register the updated
toolchain. For more information, see:
24-23
24 Custom Toolchain Registration
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');
24-24
25
• 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"
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:
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
Suppose you have a MATLAB file absval.m that contains the following function:
function y = absval(u) %#codegen
y = abs(u);
end
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
y = -2.75;
y = coder.ceval('absval',y);
25-4
Call a C/C++ Static Library Function from MATLAB Code
25-5
25 Deploying Generated Code
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.
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.
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.
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
25-8
Use a C Dynamic Library in a Microsoft Visual Studio Project
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.
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
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:
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;
}
25-11
25 Deploying Generated Code
25-12
Specify External File Locations
• 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.
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:
For example:
cc = coder.config('lib');
2 Set one or more of the custom code properties.
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
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
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.
25-15
25 Deploying Generated Code
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:
For more information on the internal representation of MATLAB data, see “MATLAB
Data” in the MATLAB External Interfaces document.
• 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:
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
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.
25-18
Incorporate Generated Code Using an Example Main Function
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.
• 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
25-19
25 Deploying Generated Code
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
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
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
25-23
25 Deploying Generated Code
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.
25-25
25 Deploying Generated Code
This image is the same as the image created using the MATLAB function.
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.
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.
/*
* 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;
return result;
}
25-28
Use an Example C Main in an Application
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.
25-29
25 Deploying Generated Code
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:
• 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.
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);
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();
fclose(fd);
return 0;
}
For the Sobel filter application, modify the function to read the grayscale image data
from a binary file into the emxArray.
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
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.
int b_j0;
int b_j1;
double element;
25-33
25 Deploying Generated Code
}
}
return result;
}
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.
1 Define the function saveImage that takes the address of emxArray edgeImage as
an input and has output type void.
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.
if (fd == NULL) {
exit(-1);
}
25-34
Use an Example C Main in an Application
fclose(fd);
Function saveImage
25-35
25 Deploying Generated Code
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.
1 Replace the input arguments to the function with the arguments FILE *fd and
double threshold.
originalImage = argInit_d1024xd1024_real_T(fd);
3 Replace the threshold value input in the function call to sobel with threshold.
saveImage(edgeImage);
25-36
Use an Example C Main in an Application
saveImage(edgeImage);
emxDestroyArray_uint8_T(edgeImage);
emxDestroyArray_real_T(originalImage);
}
To match the changes that you made to the function definitions, make the following
changes to the function declarations:
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
#include "rt_nonfinite.h"
#include "sobel.h"
#include "main.h"
#include "sobel_terminate.h"
#include "sobel_emxAPI.h"
#include "sobel_initialize.h"
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 */
int b_j0;
int b_j1;
double element;
return result;
25-39
25 Deploying Generated Code
/*
* Arguments : void
* Return Type : double
*/
static double argInit_real_T(void)
{
return 0.0;
}
25-40
Use an Example C Main in an Application
saveImage(edgeImage);
emxDestroyArray_uint8_T(edgeImage);
emxDestroyArray_real_T(originalImage);
}
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();
fclose(fd);
return 0;
}
25-41
25 Deploying Generated Code
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.
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.
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
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.
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.
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.)
load('c:\work\codegen\lib\foo\buildInfo.mat')
4 Create the zip file.
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.
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.
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:
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
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.
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.
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.
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
• 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
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
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
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
When you choose a section of MATLAB code to accelerate, the following practices are
recommended.
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”.
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.
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
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.
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
Prerequisites
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.
coderdemo_setup('coderdemo_edge_detection');
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
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
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.
im = imread('hello.jpg');
image(im);
26-8
Edge Detection on Images
Convert the color image (shown above) to an equivalent grayscale image with normalized
values (0.0 for black, 1.0 for white).
26-9
26 Accelerating MATLAB Algorithms
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);
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
26-13
26 Accelerating MATLAB Algorithms
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
26-15
26 Accelerating MATLAB Algorithms
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.
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.
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.
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)
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.
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
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.
• 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.
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)
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
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
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
MATLAB Coder does not inline functions into parfor-loops, including functions
that use coder.inline('always').
• Unrolling loops
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
26-24
Control Compilation of parfor-Loops
• 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
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
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
26-27
26 Accelerating MATLAB Algorithms
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.
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.
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
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.
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
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
This loop is equivalent to the following, where each d(i) is calculated by a different
iteration:
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.
If operation <op> takes two inputs, it should meet one of the following criteria:
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.
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.
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.
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.
26-33
26 Accelerating MATLAB Algorithms
parfor i=1:10
r = r + i;
foo(r);
end
end
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)
f(a,b) = f(b,a)
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
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
26-35
26 Accelerating MATLAB Algorithms
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
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
26-38
Accelerating Simulation of Bouncing Balls
Prerequisites
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.
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');
26-39
26 Accelerating MATLAB Algorithms
The 'run_balls' function calls other MATLAB functions, but you need to specify only the
entry-point function when calling 'codegen'.
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
Clean Up
26-43
27
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.
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.
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.
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.
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);
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.
27-4
External Function Calls from Generated Code
buffer = strip_cr(buffer);
27-5
27 Calling C/C++ Functions from Generated Code
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
• 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
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:
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:
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
• 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.
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.
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:
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.
Note: If you are not using dynamic memory allocation, arrays in structures translate into
single-dimension arrays, not pointers.
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
27-14
28
Call the external code and specify the file locations in one of the following ways:
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
In your MATLAB code, you can call the external code without providing build
information.
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
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
function tf = isSupportedContext(ctx)
if ctx.isMatlabHostTarget()
tf = true;
else
error('MyLibrary is not available for this target');
end
end
...
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
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
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.
%================================================================
methods (Static)
function tf = isSupportedContext(ctx)
if ctx.isMatlabHostTarget()
tf = true;
else
error('adder library not available for this target');
end
end
% Header files
28-6
Encapsulate Interface to an External C Library
% 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
coder.ceval('adder_initialize');
c = 0;
c = coder.ceval('adder', a, b);
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.
Generate a MEX function for adder_main. The MEX Function exercises the
coder.ExternalDependency methods.
Copy the library to the current folder using the file extension for your platform.
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
See Also
coder.updateBuildInfo
28-9
28 External Code Integration
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
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 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
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
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:
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
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
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
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)
29-10
Inline Code
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
• 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;
29-12
Control Inlining
• 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;
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;
29-13
29 Generate Efficient and Reusable Code
Related Examples
• “Inline Code” on page 29-10
29-14
Fold Function Calls into Constants
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.
Generate code for AddShift using the codegen command. Open the Code Generation
Report.
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:
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
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:
See Also
coder.const
29-16
Control Stack Space Usage
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.
cfg.StackUsageMax=400000;
More About
• “Stack Allocation and Performance” on page 29-18
29-17
29 Generate Efficient and Reusable Code
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
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.
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:
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
If you know the maximum size of a variable-size array, you can avoid dynamic memory
allocation. Follow these steps:
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
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 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
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 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.
If the size of an array during initialization is not a compile-time constant, you can
expand it by concatenating additional elements:
29-22
Provide Maximum Size for Variable-Size Arrays
function avg=RunningAverage(N)
% Initialize average:
% These will also be the first two elements of the function output
avg=[0 0];
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.
29-23
29 Generate Efficient and Reusable Code
coder.varsize('avg',[1 8]);
with:
coder.varsize('avg');
4 Generate code for RunningAverage with input argument of type double:
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:
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
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
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.
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
• 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
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;
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
• 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
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.
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
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.
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)
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:
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
29-34
Minimize Redundant Operations in Loops
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.
function C=SeriesFunc(A,B,n)
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)
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.
function y = getrand(n)
% Turn off inlining to make
% generated code easier to read
coder.inline('never');
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:
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:
The generated C code for getrand(50) does not unroll the for-loop because the
number of iterations is greater than 10:
29-38
Unroll for-Loops
29-39
29 Generate Efficient and Reusable Code
• 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.
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:
29-40
Support for Integer Overflow and Non-Finites
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:
cfg.SupportNonFinite = false;
29-41
29 Generate Efficient and Reusable Code
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).
ExternalLib_API.m
classdef ExternalLib_API < coder.ExternalDependency
%#codegen
methods (Static)
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
end
if(coder.target('MATLAB'))
C=A*B;
else
29-43
29 Generate Efficient and Reusable Code
29-44
Integrate External/Custom Code
29-45
29 Generate Efficient and Reusable Code
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.
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.
Matrix_Multiply_mex(eye(2,'single'),eye(2,'single'))
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
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
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
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.
The code generated from this MATLAB code evaluates the sum and product in a single
loop.
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.
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.
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.
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.
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:
• 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.
• At the command line, set the code configuration object property MemcpyThreshold.
• In the MATLAB Coder app, set Memcpy threshold (bytes).
More About
• “memset Optimization” on page 29-54
• “MATLAB Coder Optimizations in Generated Code” on page 29-48
29-52
memcpy Optimization
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;
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
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
• 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.
29-56
Reuse Large Arrays and Structures
• 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
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;
...
}
29-58
LAPACK Calls in Generated Code
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
The callback class must derive from the abstract class coder.LAPACKCallback. Use the
following example callback class as a template.
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
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');
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';
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]);
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
• 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.
Prerequisites
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
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
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:
• primary_function_nameStackData
Contains the user allocated memory. Pass a pointer to this structure as the first
parameter to functions that use it:
30-4
Generate Reentrant C Code from MATLAB Code
• 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;
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;
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;
}
free(sd1);
free(sd2);
printf("Finished Execution!\n");
exit(EXIT_SUCCESS);
}
30-6
Generate Reentrant C Code from MATLAB Code
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
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.
If you do not specify reentrant code, MATLAB Coder generates code that uses statically
allocated memory for:
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:
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
• 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.
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
• 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:
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
• primary_function_name_initialize.
• primary_function_name.
• primary_function_name_terminate.
30-15
30 Generating Reentrant C Code from MATLAB Code
• primary_function_name_initialize.
• primary_function_name.
• primary_function_name_terminate.
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)
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.
#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
int main() {
pthread_t thread1, thread2;
int iret1, iret2;
IODATA data1;
IODATA data2;
int32_T i;
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);
}
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);
% Compiling
codegen -config cfg main.c matrix_exp.m -report -args ones(160,160)
This script:
30-19
30 Generating Reentrant C Code from MATLAB Code
addLinkFlags(buildInfo, linkFlags);
/*
* 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
30-20
Call Reentrant Code with No Persistent or Global Data (UNIX Only)
30-21
30 Generating Reentrant C Code from MATLAB Code
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.
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)
typedef struct {
real_T in[NUMELEMENTS];
real_T out[NUMELEMENTS];
real_T numTimes;
matrix_expStackData* spillData;
} IODATA;
void main() {
HANDLE thread1, thread2;
IODATA data1;
IODATA data2;
int32_T i;
30-23
30 Generating Reentrant C Code from MATLAB Code
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);
}
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)
% Compiling
codegen -config cfg main.c -report matrix_exp.m -args ones(160,160)
This script:
• 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
30-26
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.
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
typedef struct {
real_T in[NUMELEMENTS];
real_T out[NUMELEMENTS];
real_T numTimes;
matrix_expStackData* spillData;
} IODATA;
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)
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);
}
free(sd1);
free(sd2);
free(pd1);
free(pd2);
30-29
30 Generating Reentrant C Code from MATLAB Code
printf("Finished Execution!\n");
return(0);
% Compiling
codegen -config cfg main.c -report matrix_exp.m -args ones(160,160)
This script:
30-30
Call Reentrant Code — Multithreaded with Persistent Data (UNIX Only)
• 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
30-32
MATLAB® Coder™
Reference
R2016a
How to Contact MathWorks
Phone: 508-647-7000
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
Function Reference
2
Class Reference
3
vii
1
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.
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.
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
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
2-4
codegen
• 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')
mex_cfg = coder.config
% or
mex_cfg = coder.config('mex')
2-5
2 Function Reference
2-6
codegen
2-7
2 Function Reference
fixptcfg.TestBenchName = 'myadd_test';
specifies that myadd_test is the test file for the
floating-point to fixed-point configuration object
fixptcfg.
2-8
codegen
2-9
2 Function Reference
-globals {'g', 5}
2-10
codegen
2-11
2 Function Reference
2-12
codegen
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
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.
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.
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.
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.
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.
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
Generate a MEX function for a function, displayState, that has an input parameter
that is an enumerated type.
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:
2-17
2 Function Reference
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
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
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 -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.
If the project includes automated fixed-point conversion, coder generates two scripts:
• 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.
2-22
coder
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.
Examples
Open an existing MATLAB Coder project
Open the MATLAB Coder app using the existing MATLAB Coder project named
my_coder_project.
Open the MATLAB Coder app and create a project named my_coder_project.
2-23
2 Function Reference
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.
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
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.
Examples
Generate optimized embeddable code from protected MATLAB code:
1 Write an function p_abs that returns the absolute value of its input:
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');
2-28
coder.approximation
logAppx = coder.approximation('Function','log','InputRange',[0.1,1000],...
'FunctionNamePrefix','log_replace_');
Create a function replacement configuration object that specifies to replace the custom
function, saturateExp, with an optimized 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
Name of function to replace, specified as a string. The function must be one of the listed
functions.
Example: 'sqrt'
Data Types: char
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
'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.
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
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_’
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]
2-31
2 Function Reference
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.
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
2-32
coder.approximation
More About
• “Replacing Functions Using Lookup Table Approximations”
See Also
Classes
coder.FixptConfig
Functions
codegen
2-33
2 Function Reference
coder.ceval
Package: coder
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('-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
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.
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
#include <stdio.h>
#include <stdlib.h>
#include "foo.h"
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.
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.
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"
#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
/* Function Definitions */
double myfunc(void)
{
/* Running in generated code */
return myMult2(21.0);
}
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
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
See Also
codegen | coder.ceval | coder.config | coder.target
Introduced in R2013a
2-42
coder.config
coder.config
Package: coder
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.
2-43
2 Function 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).
2-44
coder.config
cfg.GenerateReport = true;
4 Generate a MEX function in the current folder specifying the configuration object
using the -config option.
cfg = coder.config('lib')
% Returns a coder.EmbeddedCodeConfig object if the Embedded
% Coder product is installed.
% Otherwise, returns a coder.CodeConfig object.
cfg = coder.config('dll')
% Returns a coder.EmbeddedCodeConfig object if the Embedded
% Coder product is installed.
% Otherwise, returns a coder.CodeConfig object.
cfg = coder.config('lib','ecoder',false)
% Returns a coder.CodeConfig object even if the Embedded
% Coder product is installed.
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.
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.
Generate code for AddShift using the codegen command. Open the Code Generation
Report.
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:
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.
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:
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.
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.
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 [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.
The code generation software generates code for creating the vectors.
[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.
<params>
<param name="hello" value="17"/>
<param name="world" value="42"/>
2-50
coder.const
</params>
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
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.
Generate code for MyFunc using the codegen command. Open the Code Generation
Report.
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
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)
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:
Output Arguments
out — Value of expression
value of the evaluated expression
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
• “Constant Folding”
Introduced in R2013b
2-53
2 Function Reference
coder.cstructname
Package: coder
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.
2-54
coder.cstructname
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
var
2-56
coder.cstructname
'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.
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.
Output Arguments
newt
2-57
2 Function Reference
Examples
Apply coder.cstructname to Top-Level 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 }
Assign the name MyStruct to the structure var. Pass the structure to a C function
use_struct.
2-58
coder.cstructname
#else
#include "rtwtypes.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include "use_struct.h"
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.
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;
2-60
coder.cstructname
typedef struct
{
lowerType lower;
/* Definition of c appears here */
} topType;
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 C header file, MyFile.h, containing the definition of a structure type, mytype.
typedef struct {
/* Field definitions */
double a;
float b;
} mytype;
T = coder.typeof(struct('a',double(0),'b',single(0)));
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.
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.
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
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
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
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
Syntax
coder.extrinsic('function_name');
coder.extrinsic('-sync:on', 'function_name');
coder.extrinsic('-sync:off','function_name');
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
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.
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.
Examples
The following code declares the MATLAB function patch as extrinsic in the MATLAB
local function create_plot.
c = sqrt(a^2 + b^2);
create_plot(a, b, color);
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
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,'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
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
structure_of_types
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.
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 =
Generate a MEX function for my_fun using these input types as example inputs.
In the current folder, codegen generates a MEX function, my_fun_mex, that accepts
inputs of type single.
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.
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 =
Generate a MEX function for my_fun1 and my_fun2 using these input types as example
inputs.
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.
See Also
codegen | coder.resize | coder.runTest | coder.typeof
Introduced in R2012a
2-72
coder.inline
coder.inline
Package: coder
Syntax
coder.inline('always')
coder.inline('never')
coder.inline('default')
Description
coder.inline('always') forces inlining of the current function in generated code.
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.
Examples
• “Preventing Function Inlining” on page 2-74
• “Using coder.inline In Control Flow Statements” on page 2-74
2-73
2 Function Reference
function y = foo(x)
coder.inline('never');
y = x;
end
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:
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.
2-76
coder.load
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.
k = [1 2 1; 0 0 0; -1 -2 -1];
save sobel.mat k
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);
cfg = coder.config('lib');
2-77
2 Function Reference
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.
k = [1 2 1; 0 0 0; -1 -2 -1];
save sobel.dat k -ascii
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);
cfg = coder.config('lib');
Input Arguments
filename — Name of file
string
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
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
Output Arguments
S — Loaded variables or data
structure array | m-by-n array
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
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.
2-81
2 Function Reference
Input Arguments
numeric_class
struct_fields
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.
'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.
'sparse'
Set sparse to true to create a coder.Type object representing sparse data. The type
must support sparse data.
Default: false
2-83
2 Function Reference
Output Arguments
t
Examples
Create a type for use in code generation.
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
Create a type for a matrix of doubles, first dimension unbounded, second dimension with
variable size with an upper bound of 3
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
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 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
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.
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 = 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
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 .
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
cfg = coder.config('lib');
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>.
% Declare 'f' as an opaque type 'FILE *' with intial value 'NULL"
%Specify the header file that contains the type definition of 'FILE *';
buffer = strip_cr(buffer);
2-91
2 Function Reference
cfg = coder.config('lib');
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.
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)]);
if ftmp == null
%error condition
end
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.
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));
nsizet = cast(n,'like',coder.opaque('size_t','0'));
%--------------
function sc = cstr(s)
% NULL terminate a MATLAB string for C
sc = [s, char(0)];
castopaque_mex('abc','abc')
ans =
2-93
2 Function Reference
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.
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:
2-94
coder.opaque
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
Name of header file, specified as a string constant, that contains the definition of type.
If you omit the angle brackets or double quotes, the code generation software generates
double quotes.
Example: 'foo.h' generates #include "foo.h"
2-95
2 Function Reference
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)]);
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');
x = coder.opaque('size_t','0');
x1 = cast(x, 'like', int32(0));
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:
See Also
coder.ceval | coder.ref | coder.rref | coder.wref
Introduced in R2011a
2-97
2 Function Reference
coder.ref
Package: coder
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
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
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.
2-100
coder.resize
Input Arguments
limits
sz
variable_dims
'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
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
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
See Also
codegen | coder.typeof | coder.newtype
Introduced in R2011a
2-103
2 Function Reference
coder.rref
Package: coder
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.
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.
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 the same folder, create a test function, mytest1, that calls myfun.
function mytest1
c = myfun(10,20);
disp(c);
end
30
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.
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.
2-107
2 Function Reference
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
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.
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 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
mytest2
10
30
Generate a MEX function for myfun1 and myfun2. Use the -o option to specify the name
of the generated MEX function.
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
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
2-110
coder.runTest
Generate this MEX function using the MATLAB Coder app or the codegen function.
Example: 'mymex'
Data Types: char
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:
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.
Input Arguments
fcn
fcn_1,...,fcn_n
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.
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:
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
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.
The coder.screener function identifies data types that code generation does not
support.
Analyze the MATLAB function foo3 that uses unsupported data types.
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.
The coder.screener function identifies calls to functions that code generation does not
support. It checks the entry-point functions foo4 and foo5.
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
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.
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
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.
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
Example: tf = coder.target('MATLAB')
Data Types: char
See Also
coder.ceval
Introduced in R2011a
2-125
2 Function Reference
coder.typeof
Package: coder
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.
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.
2-126
coder.typeof
Input Arguments
sz
coder.Type object
MATLAB expression that describes the set of values represented by this type.
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 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
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
2-129
2 Function Reference
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.
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
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.
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
Input Arguments
flag
2-132
coder.unroll
range
Examples
To limit the number of times to copy the body of a for-loop in generated code:
function y = getrand(n)
% Turn off inlining to make
% generated code easier to read
coder.inline('never');
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 :
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:
The generated C code for getrand(50) does not unroll the for-loop because the
number of iterations is greater than 10:
2-134
coder.unroll
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.
2-136
coder.updateBuildInfo
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( ___ ,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.
You can see the added compiler options under the Target Build Log tab in the Code
Generation Report.
Add a source file to the project build information while generating code for a function,
calc_factorial.
fact.h will be included as a header file in generated code. This inclusion ensures
that the function is declared before it is called.
#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;
}
}
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.
In the Code Generation Report, on the C Code tab, you can see the added source file
fact.c.
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 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);
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.
Open the Code Generation Report. The header file adder.h is included in the
generated code.
Input Arguments
options — Build options
string
Depending on the leading argument, options specifies the relevant build options to be
added to the project’s build information.
2-141
2 Function Reference
The group option assigns a group name to the parameters in the second argument.
Depending on the leading argument, filename specifies the relevant file to be added to
the project’s build information.
The function adds the file name to the end of a file name vector.
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
The function adds the path to the end of a path name vector.
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.
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.
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.
More About
• “Customize the Post-Code-Generation Build Process”
Introduced in R2013b
2-144
coder.varsize
coder.varsize
Package: coder
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.
2-145
2 Function Reference
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
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
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
2-147
2 Function Reference
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.
Write a function struct_example that declares an array data, where each element is a
structure that contains a variable-size field:
2-148
coder.varsize
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
Run struct_example.
Each time you run struct_example you get a different answer because the function
loads the array with random numbers.
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
2-149
2 Function Reference
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.
See Also
codegen | size | varargin
Introduced in R2011a
2-151
2 Function Reference
coder.wref
Package: coder
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));
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.
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.
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
test_parfor_mex
Specify the maximum number of threads when generating a MEX function for a parfor-
loop.
Generate a MEX function for specify_num_threads. Use -args 0 to specify the type
of the input. At the MATLAB command line, enter:
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.
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
Input Arguments
LoopVar — Loop index
integer
2-156
parfor
Loop index variable whose initial value is InitVal and final value is EndVal.
Initial value for loop index variable, Loopvar. With EndVal, specifies the parfor range
vector, which must be of the form M:N.
Final value for loop index variable, LoopVar. With InitVal, specifies the parfor range
vector, which must be of the form M:N.
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
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:
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”.
More About
Tips
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.
See Also
Functions
codegen
Introduced in R2012b
2-159
2 Function Reference
addOption
Class: coder.make.BuildConfiguration
Package: coder.make
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
2-160
addOption
Examples
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
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
Output Arguments
OptionValue — Value of option
coder.make.BuildItem object
2-163
2 Function Reference
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
Syntax
h.info
OutputInfo = h.info
Description
h.info displays information about the coder.make.BuildConfiguration object in
the MATLAB Command Window.
Input Arguments
h — BuildConfiguration handle
object handle
Output Arguments
OutputInfo — Build configuration information
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
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
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
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
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
Columns 6 through 10
2-170
setOption
setOption
Class: coder.make.BuildConfiguration
Package: coder.make
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
2-171
2 Function Reference
Examples
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)');
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
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
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
Columns 3 through 4
Columns 5 through 6
Columns 7 through 8
Columns 9 through 10
2-175
2 Function Reference
getMacro
Class: coder.make.BuildItem
Package: coder.make
Syntax
h.getMacro
Description
h.getMacro returns the macro name of an existing build item.
Input Arguments
buildItemHandle — BuildItem handle
object handle
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
Syntax
h.getValue
Description
h.getValue returns the value of an existing build item.
Input Arguments
buildItemHandle — BuildItem handle
object handle
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
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
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
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
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
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
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
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
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
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.
Input Arguments
h — Object handle
variable
2-188
getCommand
'macro'
Output Arguments
c_out — Command value or macro
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
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
Output Arguments
value — Value of directive
string
2-190
getDirective
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
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
Output Arguments
value — Value of file extension
string
2-192
getFileExtension
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
Syntax
toolname = h.getName
Description
toolname = h.getName returns the name of the coder.make.BuildTool object.
Input Arguments
h — Object handle
variable
Output Arguments
toolname — Name of 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
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
2-196
getPath
Output Arguments
btpath — Path of build tool object
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
Syntax
h.info
Description
h.info returns information about the coder.make.BuildTool object.
Input Arguments
h — Object handle
variable
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
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
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:
2-200
setCommandPattern
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.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');
See Also
coder.make.ToolchainInfo.addBuildTool |
coder.make.BuildTool.setCommandPattern
2-201
2 Function Reference
setCommand
Class: coder.make.BuildTool
Package: coder.make
Syntax
h.setCommand(commandvalueinput)
Description
h.setCommand(commandvalueinput) sets the value of the
coder.make.BuildTool.Command property.
Input Arguments
h — Object handle
variable
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.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');
See Also
coder.make.BuildTool.getCommand
2-203
2 Function Reference
setDirective
Class: coder.make.BuildTool
Package: coder.make
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
2-204
setDirective
Examples
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');
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
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
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.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');
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
Syntax
h.setName(name)
Description
h.setName(name) sets the name of the coder.make.BuildTool.Name property.
Input Arguments
h — Object handle
variable
2-209
2 Function Reference
Examples
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');
ans =
C Compiler
tool.setName('X Compiler')
tool.getName
ans =
X Compiler
2-210
setPath
setPath
Class: coder.make.BuildTool
Package: coder.make
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
2-211
2 Function Reference
Examples
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');
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
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
Output Arguments
validtool — Validity of coder.make.BuildTool object
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>>
See Also
coder.make.ToolchainInfo.validate
2-215
2 Function Reference
addAttribute
Class: coder.make.ToolchainInfo
Package: coder.make
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.
All attributes are optional. You can add attributes for the toolchain to use. The following
attributes are used during the build process:
2-216
addAttribute
Input Arguments
h — ToolchainInfo object handle
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 =
ans =
# -------------------
# "Attributes" List
# -------------------
CustomAttribute = true
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
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.
Input Arguments
h — ToolchainInfo object handle
2-220
addBuildConfiguration
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
##############################################
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
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.
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
2-223
2 Function Reference
Output Arguments
bldtl_handle — BuildTool object handle
Examples
Refer to the coder.make.BuildTool “Example” on page 3-134 for a complete example of
how to create a addBuildTool.
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
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.
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
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
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.
Tips
Use setMacro to update the value of a macro in
coder.make.ToolchainInfo.Macros.
Input Arguments
h — ToolchainInfo object handle
Name of macro.
2-228
addMacro
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
Syntax
h.addPostbuildTool(bldtl_name)
h.addPostbuildTool(bldtl_name, bldtl_handle)
Description
h.addPostbuildTool(bldtl_name) adds a BuildTool object to PostbuildTools.
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
2-230
addPostbuildTool
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
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
2-233
2 Function Reference
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
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
Examples
Refer to the coder.make.BuildTool “Example” on page 3-134 for an example of to create
a BuildTool.
2-236
addPostExecuteTool
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
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.
Input Arguments
h — ToolchainInfo object handle
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
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.
Input Arguments
h — ToolchainInfo object handle
Output Arguments
success — Indication whether cleanup completed
2-240
cleanup
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
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
Output Arguments
att_value — Value of attribute
true (default)
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
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
Output Arguments
names — List of names
Examples
h.addAttribute('FirstAttribute')
2-244
getAttributes
h.addAttribute('SecondAttribute')
h.addAttribute('ThirdAttribute')
names = h.getAttributes
names =
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
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
Output Arguments
bldcfg_handle — BuildConfiguration object handle
2-246
getBuildConfiguration
Examples
bldcfg_handle = h.getBuildConfiguration('Debug')
bldcfg_handle =
##############################################
# Build Configuration : Debug
# Description : Default debug settings for compiling/linking code
##############################################
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
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
Output Arguments
bldtl_handle — BuildTool object handle
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
Syntax
value = h.getMacro(macroname)
Description
value = h.getMacro(macroname) returns the value of the specified macro.
Input Arguments
h — ToolchainInfo object handle
Name of macro.
Output Arguments
macrovalue — Value of macro
string | cell
If the value contains MATLAB functions or other macros, ToolchainInfo interprets the
value of functions and macros.
2-251
2 Function Reference
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
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
Output Arguments
bldtl_handle — BuildTool object handle
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
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
Output Arguments
bldtl_handle — BuildTool object handle
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
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
Output Arguments
lng_list — List of supported languages
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 =
See Also
coder.make.ToolchainInfo
More About
• “About coder.make.ToolchainInfo”
2-260
isAttribute
isAttribute
Class: coder.make.ToolchainInfo
Package: coder.make
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
Output Arguments
truefalse — Logical value
boolean
2-261
2 Function Reference
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
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
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
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
Syntax
h.removeBuildTool(bldtl_name)
Description
h.removeBuildTool(bldtl_name) removes the named build tool from BuildTools.
Input Arguments
h — ToolchainInfo object handle
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
Syntax
h.removeIntrinsicMacros(intrnsc_macronames)
Description
h.removeIntrinsicMacros(intrnsc_macronames) removes the named intrinsic
macro from Macros.
Input Arguments
h — ToolchainInfo object handle
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
Syntax
h.removeMacro(macroname)
Description
h.removeMacro(macroname) removes a macro from
coder.make.ToolchainInfo.Macros.
Input Arguments
h — ToolchainInfo object handle
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
Syntax
h.removePostbuildTool(bldtl_name)
Description
h.removePostbuildTool(bldtl_name) removes the named build tool from
PostbuildTools.
Input Arguments
h — ToolchainInfo object handle
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
Syntax
h.removePrebuildTool(bldtl_name)
Description
h.removePrebuildTool(bldtl_name) removes the named build tool from
PrebuildTools.
Input Arguments
h — ToolchainInfo object handle
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
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
2-277
2 Function Reference
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
##############################################
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
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
2-280
setBuildConfigurationOption
Examples
To update a specific BuildConfiguration object or objects:
h = coder.make.ToolchainInfo
h.setBuildConfigurationOption('Faster Runs','C Compiler','-c -g')
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
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
• WIN32
2-282
setBuilderApplication
• WIN64
• MACI64
• GLNXA64
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
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
2-284
setBuildTool
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
Syntax
h.setMacro(macroname, value)
Description
h.setMacro(macroname, value) sets the value of a macro.
Input Arguments
h — ToolchainInfo object handle
Name of macro.
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
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
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
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
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
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 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
Output Arguments
success — Response indicating whether setup completed
double
2-292
setup
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.
Input Arguments
h — ToolchainInfo object handle
2-294
validate
Output Arguments
success — Response indicating whether validate passed
double
Information about which properties are invalid. Only available when the method returns
0.
Examples
h = coder.make.ToolchainInfo;
[success,report] = h.validate
success =
report =
Validation report:
2-295
2 Function Reference
2-296
validate
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
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
See Also
coder.HardwareImplementation
2-298
getStdLibInfo
getStdLibInfo
Class: coder.BuildConfig
Package: coder
Syntax
[linkLibPath,linkLibExt,execLibExt,libPrefix]=
bldcfg.getStdLibInfo()
Description
[linkLibPath,linkLibExt,execLibExt,libPrefix]=
bldcfg.getStdLibInfo() returns strings representing the:
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
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
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
See Also
coder.make.ToolchainInfo
2-302
isCodeGenTarget
isCodeGenTarget
Class: coder.BuildConfig
Package: coder
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
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
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
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
isHeterogeneous(t)
ans =
2-306
isHeterogeneous
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
Pass tc to make_varsize.
tc1 = assign_name(tc, 'myname')
Pass tc to make_varsize.
tc1 = assign_name(tc, 'myname')
tc1 =
coder.CellType
1x2 heterogeneous cell myname
f0: 1x1 char
f1: 1x1 double
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
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
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
isHomogeneous(t)
ans =
2-309
2 Function Reference
function c = make_varsize(t, n)
assert(isHomogeneous(t));
c = coder.typeof(t, [n n], [1 1]);
end
tc = coder.typeof({'a', 1});
Pass tc to make_varsize.
tc1 = make_varsize(tc, 5)
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
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
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
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.
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
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.
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
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.
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
t =
coder.CellType
1x2 homogeneous cell
base: 1x:2 double
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
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
You can use this information when you want to return different names based on the build
context.
Output Arguments
extname
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 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
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
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.
2-320
coder.ExternalDependency.isSupportedContext
2-321
2 Function Reference
coder.ExternalDependency.updateBuildInfo
Class: coder.ExternalDependency
Package: coder
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
bldcfg
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
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
2-324
addDesignRangeSpecification
Examples
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
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
Examples
Specify Function Replacement in Fixed-Point Conversion Configuration Object
Suppose that:
2-326
addFunctionReplacement
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');
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
Syntax
clearDesignRangeSpecifications()
Description
clearDesignRangeSpecifications() clears all design range specifications.
Examples
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
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
Output Arguments
designMin — Minimum value allowed for this parameter
scalar
2-329
2 Function Reference
Examples
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
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
2-331
2 Function Reference
Output Arguments
hasDesignRange — Parameter has design range
true | false
Examples
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
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
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
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);
You can now generate fixed-point code using the codegen function.
See Also
codegen | coder.config | coder.FixptConfig
More About
• “Replacing Functions Using Lookup Table Approximations”
2-336
addFunctionReplacement
addFunctionReplacement
Class: coder.SingleConfig
Package: coder
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
2-337
2 Function Reference
Examples
Specify Function Replacement in Single-Precision Conversion Configuration Object
Suppose that:
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');
See Also
codegen | coder.config
Introduced in R2015b
2-338
coder.LAPACKCallback.getHeaderFilename
coder.LAPACKCallback.getHeaderFilename
Class: coder.LAPACKCallback
Package: coder
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.
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.
2-339
2 Function Reference
External Websites
• www.netlib.org/lapack
2-340
coder.LAPACKCallback.updateBuildInfo
coder.LAPACKCallback.updateBuildInfo
Class: coder.LAPACKCallback
Package: coder
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.
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
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.
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 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');
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
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
SizeVector
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
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:
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.
%================================================================
methods (Static)
function tf = isSupportedContext(ctx)
if ctx.isMatlabHostTarget()
tf = true;
else
error('adder library not available for this target');
end
end
% 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
coder.ceval('adder_initialize');
c = 0;
c = coder.ceval('adder', a, b);
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
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.
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.
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.
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.
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.
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.
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.
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
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
Create a Cell Array Type for a Cell Array Whose Elements Have Different Classes
a = 'a';
b = 1;
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
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 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
coder.CellType
1x2 heterogeneous cell
f0: 1x1 double
3-13
3 Class Reference
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.
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
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.
3-15
3 Class Reference
Properties
BuildConfiguration
CodeReplacementLibrary
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.
• 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.
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.
CustomHeaderCode
Specify code to appear near the top of each C/C++ header file generated from your
MATLAB algorithm code.
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:
CustomInitializer
Specify code to appear in the initialize function of the generated .c or .cpp file.
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.
CustomLibrary
Specify a space-separated list of static library or object files to link with the generated
code.
CustomSource
Specify a space-separated list of source files to compile and link with the generated code.
3-18
coder.CodeConfig class
CustomSourceCode
Specify code to appear near the top of the generated .c or .cpp file, outside of a function.
CustomTerminator
Specify code to appear in the terminate function of the generated .c or .cpp file.
CustomToolchainOptions
Specify custom settings for each tool in the selected toolchain, as a cell array.
Dependencies:
These values derive from the toolchain definition file and the third-party compiler
options. See “Custom Toolchain Registration”.
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'.
3-19
3 Class Reference
Description
DynamicMemoryAllocation
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:
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:
EnableAutoExtrinsicCalls
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.
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
Dependency:
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').
GenCodeOnly
Default: false
GenerateComments
Dependency:
• Enables MATLABSourceComments.
Default: true
GenerateExampleMain
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.
GenerateMakefile
Default: true
GenerateReport
Default: false
HardwareImplementation
InitFltsAndDblsToZero
• InitFltsAndDblsToZero is true.
3-23
3 Class Reference
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.
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.
LaunchReport
Specify whether to display a report after code generation is complete or an error occurs.
Default: true
MATLABSourceComments
Dependency:
Default: false
MaxIdLength
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.
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.
Default: integer, 64
MultiInstanceCode
Default: false
Name
OutputType
PassStructByReference
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.
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.
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.
ReservedNameArray
Enter a space-separated list of names that MATLAB Coder is not to use for naming
functions or variables.
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.
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.
SupportNonFinite
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.
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.
Toolchain
Specify the toolchain to use. If you do not specify a toolchain, MATLAB Coder
automatically locates an installed toolchain.
Verbose
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).
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.
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).
/*
** 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
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
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.
Input Arguments
v
Properties
Value
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.
cfg = coder.config('mex');
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';
3-33
3 Class Reference
ans =
42
Configure ConstantInputs so that the MEX function does not include the constant
input.
cfg.ConstantInputs = 'Remove';
ans =
42
This example shows how to generate C code for a function specialized to the case where
an input has a constant value.
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
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.
y = g;
end
cfg = coder.config('mex');
Define a cell array globals that declares that g is a constant global variable with value
5.
Generate a MEX function for myfunction using the -globals option to specify the
global data.
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.
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
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;
}
CodeExecutionProfiling
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.
CodeReplacementLibrary
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.
• 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.
CommentStyle
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.
ConvertIfToSwitch
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
CustomHeaderCode
Specify code to appear near the top of each C/C++ header file generated from your
MATLAB algorithm code.
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:
CustomInitializer
Specify code to appear in the initialize function of the generated .c or .cpp file.
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.
CustomLibrary
Specify a space-separated list of static library files to link with the generated code.
3-42
coder.EmbeddedCodeConfig class
CustomSource
Specify a space-separated list of source files to compile and link with the generated code.
CustomSourceCode
Specify code to appear near the top of the generated .c or .cpp file, outside of a function.
CustomSymbolStrEMXArray
Customize generated identifiers for EMX Array types (Embeddable mxArray types). See
“Settings” on page 3-60.
CustomSymbolStrEMXArrayFcn
CustomSymbolStrFcn
CustomSymbolStrField
Customize generated field names in global type identifiers. See “Settings” on page
3-60.
CustomSymbolStrGlobalVar
3-43
3 Class Reference
CustomSymbolStrMacro
CustomSymbolStrTmpVar
CustomSymbolStrType
CustomTerminator
Specify code to appear in the terminate function of the generated .c or .cpp file.
CustomToolchainOptions
Specify custom settings for each tool in the selected toolchain, as a cell array.
Dependencies:
rtwdemo_sil_topmodel;
set_param(gcs, 'BuildConfiguration', 'Specify')
opt = get_param(gcs, 'CustomToolchainOptions')
3-44
coder.EmbeddedCodeConfig class
These values derive from the toolchain definition file and the third-party compiler
options. See “Custom Toolchain Registration”.
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'.
Description
DynamicMemoryAllocation
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:
3-45
3 Class Reference
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:
EnableAutoExtrinsicCalls
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.
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
Dependency:
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').
GenerateCodeMetricsReport
Generate a static code metrics report including generated file information, number of
lines, and memory usage.
Default: false
GenCodeOnly
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
Dependencies:
• Enables CommentStyle.
• Enables MATLABFcnDesc.
• Enables MATLABSourceComments.
Default: true
GenerateExampleMain
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.
3-49
3 Class Reference
GenerateMakefile
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:
HardwareImplementation
Dependency:
3-50
coder.EmbeddedCodeConfig class
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
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
• 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.
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.
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.
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:
Default: true
MATLABSourceComments
Dependencies:
Default: false
MaxIdLength
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.
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
Default: integer, 64
MultiInstanceCode
Default: false
Name
OutputType
ParenthesesLevel
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;
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));
PassStructByReference
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.
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.
PurelyIntegerCode
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.
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.
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
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.
SupportNonFinite
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.
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.
Toolchain
Specify the toolchain to use. If you do not specify a toolchain, MATLAB Coder
automatically locates an installed toolchain.
3-59
3 Class Reference
Verbose
Default: false
VerificationMode
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.
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.
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
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).
Input Arguments
enum_value
Enumeration value defined in a file on the MATLAB path.
3-62
coder.EnumType class
sz
variable_dims
Logical vector that specifies whether each dimension is variable size (true) or fixed size
(false).
enum_name
Properties
ClassName
SizeVector
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
t = coder.typeof(MyColors.red);
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
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:
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 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.
%================================================================
methods (Static)
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
% 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
coder.ceval('adder_initialize');
c = 0;
c = coder.ceval('adder', a, b);
3-67
3 Class Reference
coder.ceval('adder_terminate');
end
end
end
end
Write a function adder_main that calls the external library function adder.
Generate a MEX function for adder_main. The MEX Function exercises the
coder.ExternalDependency methods.
Copy the library to the current folder using the file extension for your platform.
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
Introduced in R2013b
3-69
3 Class Reference
coder.FiType class
Package: coder
Superclasses: coder.ArrayType
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.
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
sz
variable_dims
Logical vector that specifies whether each dimension is variable size (true) or fixed size
(false).
'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'
3-71
3 Class Reference
Properties
ClassName
Complex
Indicates whether fixed-point arrays in the set are real (false) or complex (true).
Fimath
NumericType
SizeVector
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 =
% Returns
% coder.FiType
% 1x2 embedded.fi
% DataTypeMode: Fixed-point: binary point scaling
% Signedness: Signed
% WordLength: 16
% FractionLength: 15
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
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
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.
DefaultFractionLength
3-74
coder.FixptConfig class
DefaultSignedness
DefaultWordLength
DetectFixptOverflows
fimath
FixPtFileNameSuffix
LaunchNumericTypesReport
View the numeric types report after the software has proposed fixed-point types.
LogIOForComparisonPlotting
Enable simulation data logging to plot the data differences introduced by fixed-point
conversion.
3-75
3 Class Reference
OptimizeWholeNumber
Optimize the word lengths of variables whose simulation min/max logs indicate that they
are always whole numbers.
PlotFunction
• 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
ProposeFractionLengthsForDefaultWordLength
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.
ProposeWordLengthsForDefaultFractionLength
ProposeTypesUsing
Propose data types based on simulation range data, derived ranges, or both.
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.
StaticAnalysisQuickMode
StaticAnalysisTimeoutMinutes
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
TestNumerics
Methods
Examples
Generate Fixed-Point C Code from Floating-Point MATLAB Code
fixptcfg = coder.config('fixpt');
Set the test bench name. In this example, the test bench function name is dti_test.
fixptcfg.TestBenchName = 'dti_test';
cfg = coder.config('lib');
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';
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);
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.
Set the test bench name. In this example, the test bench function name is dti_test.
fixptcfg.TestBenchName = 'dti_test';
3-79
3 Class Reference
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 Also
coder.codeConfig | codegen | coder | coder.config
3-80
coder.HardwareImplementation class
coder.HardwareImplementation class
Package: coder
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
Name
3-81
3 Class Reference
ProdBitPerChar
Describe length in bits of the C char data type that the deployment hardware supports.
Dependencies:
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.
Dependencies:
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.
Dependencies:
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:
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.
Dependencies:
integer, 16
ProdEndianess
Describe significance of the first byte of a data word for the deployment hardware.
ProdEqTarget
Specify whether the test hardware differs from the deployment hardware.
Dependencies:
true, false
Specify manufacturer and type of hardware that you use to implement the production
version of the system.
3-84
coder.HardwareImplementation class
ProdIntDivRoundTo
Describe how your compiler rounds the result of dividing one signed integer by another to
produce a signed integer quotient.
ProdLargestAtomicFloat
Specify the largest floating-point data type that can be atomically loaded and stored on
the deployment hardware.
Dependencies:
string, 'None'
ProdLargestAtomicInteger
Specify the largest integer data type that can be atomically loaded and stored on the
deployment hardware.
Dependencies:
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:
true, false
ProdShiftRightIntArith
Describe whether your compiler implements a signed integer right shift as an arithmetic
right shift.
true, false
ProdWordSize
Dependencies:
integer, 64
TargetBitPerChar
Describe length in bits of the C char data type that the test hardware supports.
3-86
coder.HardwareImplementation class
Dependencies:
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.
Dependencies:
integer, 32
TargetBitPerLong
Describe length in bits of the C long data type that the test hardware supports.
3-87
3 Class Reference
Dependencies:
integer, 32
TargetBitPerLongLong
Describe length in bits of the C long long data type that the test hardware supports.
Dependencies:
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.
Dependencies:
3-88
coder.HardwareImplementation class
integer, 16
TargetEndianess
Describe significance of the first byte of a data word for the test hardware.
Specify manufacturer and type of the hardware that you use to test the generated code.
TargetIntDivRoundTo
Describe how your compiler rounds the result of two signed integers for the test
hardware.
TargetLargestAtomicFloat
Specify the largest floating-point data type that can be atomically loaded and stored on
the test hardware.
Dependencies:
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:
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:
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
Dependencies:
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.
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:
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.
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
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');
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
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
Properties
ConstantFoldingTimeout
ConstantInputs
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.
CustomHeaderCode
Specify code to appear near the top of each C/C++ header file generated from your
MATLAB algorithm code.
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"'
CustomInitializer
Specify code to appear in the initialize function of the generated .c or .cpp file.
CustomLibrary
Specify a space-separated list of static library files to link with the generated code.
3-97
3 Class Reference
CustomSource
Specify a space-separated list of source files to compile and link with the generated code.
CustomSourceCode
Specify code to appear near the top of the generated .c or .cpp file, outside of a function.
CustomTerminator
Specify code to appear in the terminate function of the generated .c or .cpp file.
Description
Description of object.
DynamicMemoryAllocation
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:
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:
EchoExpressions
Specify whether or not actions that do not terminate with a semicolon appear in the
MATLAB Command Window.
Default: true
EnableAutoExtrinsicCalls
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.
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
Dependency:
Default: true
ExtrinsicCalls
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').
GenCodeOnly
Control whether to compile the generated MEX function C/C++ code to produce a MEX
function.
Default: false
GenerateComments
Default: true
GenerateReport
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
• 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.
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.
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.
IntegrityChecks
Detect violations of memory integrity in code generated for MATLAB functions and stops
execution with a diagnostic message.
Default: true
LaunchReport
Specify whether to automatically display HTML reports after code generation is complete
or an error occurs.
Default: true
MATLABSourceComments
Dependencies:
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.
Default: integer, 64
Name
PostCodeGenCommand
Specify command to customize build processing after MEX function generation using
codegen.
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.
ReservedNameArray
Enter a list of names that MATLAB Coder is not to use for naming functions or variables.
ResponsivenessChecks
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.
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.
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.
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
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.
3-109
3 Class Reference
Input Arguments
v
sz
Size for corresponding dimension of type object. Size must be a valid size vector.
variable_dims
Logical vector that specifies whether each dimension is variable size (true) or fixed size
(false).
numeric_class
'complex'
Default: false
3-110
coder.PrimitiveType class
'sparse'
Default: false
Properties
ClassName
Complex
Indicates whether the values in this set are real (false) or complex (true)
SizeVector
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
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
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.
3-113
3 Class Reference
Input Arguments
struct_v
sz
variable_dims
Logical vector that specifies whether each dimension is variable size (true) or fixed size
(false).
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.
ClassName
Extern
Fields
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.
SizeVector
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
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.
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
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.
Enable simulation data logging to plot the data differences introduced by single-precision
conversion.
3-118
coder.SingleConfig class
• 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.
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.
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
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;
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
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
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
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
Output Arguments
ConfigObj — Object handle for configuration
variable
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
##############################################
Attributes:
GetAccess public
SetAccess public
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'
config =
3-124
coder.make.BuildConfiguration class
##############################################
# Build Configuration : BldConfigName
# Description :
##############################################
Attributes:
GetAccess public
SetAccess public
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.
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
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
Output Arguments
buildItemHandle — BuildItem handle
object handle
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
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 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
Output Arguments
h — Object handle
variable
Properties
Command — Build tool command or command macro
The macro name and system call appear together in the generated makefile. For
example: CC = gcc
• coder.make.BuildTool.getCommand
• coder.make.BuildTool.setCommand
3-132
coder.make.BuildTool class
Attributes:
GetAccess public
SetAccess public
Defines any tool-specific directives, such as -D for preprocessor defines. Assigning a value
to this property is optional.
• coder.make.BuildTool.addDirective
• coder.make.BuildTool.getDirective
• coder.make.BuildTool.setDirective
Attributes:
GetAccess public
SetAccess public
• coder.make.BuildTool.addFileExtension
• coder.make.BuildTool.getFileExtension
• coder.make.BuildTool.setFileExtension
Attributes:
GetAccess public
SetAccess public
3-133
3 Class Reference
• coder.make.BuildTool.getName
• coder.make.BuildTool.setName
Attributes:
GetAccess public
SetAccess public
Defines any tool-specific paths. If the command is on the system path, this value is
optional.
• 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.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');
The following examples show the same “get and define” approach in more detail:
addBuildToolToToolchainInfo.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Adding a build tool to ToolchainInfo
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3-135
3 Class Reference
createBuildTool_1.m
function buildToolObj = createBuildTool_1()
toolinfo.Command.Macro = 'CC';
toolinfo.Command.Value = 'gcc';
toolinfo.Path.Macro = 'CC_PATH';
toolinfo.Path.Value = '';
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';
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 = {'*'};
% Create a build tool object and populate it with the above data
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
Description
Use coder.make.ToolchainInfo to define and register a new set of software build
tools (toolchain) with MathWorks code generation products.
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:
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.
Input Arguments
SupportedLanguages
3-142
coder.make.ToolchainInfo class
Output Arguments
h — ToolchainInfo object handle
Properties
Attributes — Custom attributes of toolchain
Add custom attributes required by the toolchain and specify their default values.
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
• 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
The type of makefile (build artifact) MATLAB Coder uses during the software build
process.
For example:
h = coder.make.ToolchainInfo('BuildArtifact','nmake');
The values can be:
h = coder.make.ToolchainInfo;
h.BuildArtifact
ans =
3-144
coder.make.ToolchainInfo class
gmake makefile
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');
Attributes:
GetAccess public
SetAccess protected
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('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
ans =
# ----------------------------
# "BuildConfigurations" List
# ----------------------------
Debug = <coder.make.BuildConfiguration>
Faster Builds = <coder.make.BuildConfiguration>
Faster Runs = <coder.make.BuildConfiguration>
• coder.make.ToolchainInfo.getBuildConfiguration
• coder.make.ToolchainInfo.removeBuildConfiguration
• coder.make.ToolchainInfo.setBuildConfiguration
Attributes:
GetAccess public
SetAccess public
• 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.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');
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>
• 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
Properties of the build tool that runs the makefile or build artifact
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');
##############################################
# 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
Attributes:
GetAccess public
SetAccess public
Specify inlined commands to insert verbatim into the makefile. The default value is
empty.
For example, to display and then update the value of the InlinedCommands property,
use the MATLAB Command Window to enter:
h.InlinedCommands
ans =
''
3-149
3 Class Reference
!include <ntwin32.mak>
The “Adding a Custom Toolchain” example does not include the InlinedCommands
property.
Attributes:
GetAccess public
SetAccess public
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.
Attributes:
GetAccess public
SetAccess public
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.
Attributes:
GetAccess public
SetAccess public
h = coder.make.ToolchainInfo;
h.Macros
ans =
# ---------------
# "Macros" List
# ---------------
(empty)
• It writes macros that are used by the current build to the makefile as variables. For
example:
Command = 'cl2000'
3-152
coder.make.ToolchainInfo class
Path = '$(TI_C2000_TOOLS)'
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 =
• 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
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:
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 =
Attributes:
GetAccess public
SetAccess public
3-154
coder.make.ToolchainInfo class
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.
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
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.
• coder.make.ToolchainInfo.addPostbuildTool
• coder.make.ToolchainInfo.getPostbuildTool
• coder.make.ToolchainInfo.removePostbuildTool
• coder.make.ToolchainInfo.setPostbuildTool
Attributes:
Download public
Execute public
The list of tools used before compiling the source files into object files.
ans =
3-156
coder.make.ToolchainInfo class
# ----------------------
# "PrebuildTools" List
# ----------------------
(empty)
The “Adding a Custom Toolchain” example does not include the PrebuildTools
property.
• coder.make.ToolchainInfo.addPrebuildTool
• coder.make.ToolchainInfo.getPrebuildTool
• coder.make.ToolchainInfo.removePrebuildTool
• coder.make.ToolchainInfo.setPrebuildTool
Attributes:
GetAccess public
SetAccess public
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.
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
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
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
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
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 =
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
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 “Adding a Custom Toolchain” example does not include the SupportedLanguages
property.
Attributes:
GetAccess public
SetAccess public
3-161
3 Class Reference
This property does not have any associated methods. Assign the value directly to the
SupportedVersion.
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
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.
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.
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.
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.
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.
Examples
Display Contents of Code Replacement Library
crviewer('ARM Cortex-A')
4-5
4 Tools — Alphabetical List
crviewer(clr_table_ne10)
4-6
Code Replacement Viewer
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
Phone: 508-647-7000
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
v
MATLAB Coder App Line Execution Count: See how well test
exercises MATLAB code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8
vi Contents
R2015aSP1
Bug Fixes
R2015b
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
viii Contents
Check bug reports for issues and fixes . . . . . . . . . . . . . . . . . . 3-2
R2015a
ix
Improved recognition of compile-time constants . . . . . . . . . 4-8
x Contents
R2014b
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
R2014a
xii Contents
Automatic C/C++ compiler setup . . . . . . . . . . . . . . . . . . . . . . . 6-4
xiii
R2013b
C99 long long integer data type for code generation . . . . . . 7-5
xiv Contents
Support for LCC compiler on Windows 64-bit machines . . . 7-7
R2013a
xv
Default use of Basic Linear Algebra Subprograms (BLAS)
libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-9
R2012b
xvi Contents
R2012a
R2011b
xvii
R2011a
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:
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}”.
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.
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
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”.
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.
Starting with R2016a, MATLAB Coder is included in the MATLAB Primary and
Secondary School Suite.
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.
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.
Generate MEX for myconcat. Use the -args option to indicate that the input arguments
have the types defined by IN1 and IN2.
R1 = zeros(0,5);
R2 = magic(3)
1-4
Check Bug Reports for Issues and Fixes
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.
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.
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(~)
In R2016a, MATLAB Coder invokes the memset optimization for more cases than in
previous releases.
1-6
Check Bug Reports for Issues and Fixes
S->f1[i] = 0.0;
For information about settings that affect the memset optimization, see “memset
Optimization”.
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.
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
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
1-12
Check Bug Reports for Issues and Fixes
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
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.
• airy
• besseli
• besselj
Trigonometry in MATLAB
• deg2rad
1-14
Check Bug Reports for Issues and Fixes
• rad2deg
• interpn
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”.
See “Communications System Toolbox” in “Functions and Objects Supported for C and C
++ Code Generation — Category List”.
1-15
R2016a
See “DSP System Toolbox” in “Functions and Objects Supported for C and C++ Code
Generation — Category List”.
See “Phased Array System Toolbox” in “Functions and Objects Supported for C and C++
Code Generation — Category List”.
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
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
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.
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.
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.
• 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.
By default, run-time error detection is enabled for MEX. By default, run-time error
detection is disabled for standalone libraries and executables.
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.
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/.
See Image Processing Toolbox in Functions and Objects Supported for C and C++ Code
Generation — Category List.
• 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.
See Statistics and Machine Learning Toolbox in Functions and Objects Supported for C
and C++ Code Generation — Category List.
3-5
R2015b
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:
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.
3-7
R2015b
•
Use the icon to change the numerictype properties.
You can use tab completion to specify entry-point functions and test files.
The app uses colors that are compatible with the Desktop tool colors preference in the
MATLAB preferences. For information about MATLAB preferences, see Preferences.
When you perform the Check for Run-Time Issues step, you can see progress
indicators.
3-8
Check bug reports for issues and fixes
•
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.
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.
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).
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.
• 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.
• iscellstr
• strjoin
See String Functions in MATLAB in Functions and Objects Supported for C and C++
Code Generation — Category List.
comm.CoarseFrequencyCompensator
See Communications System Toolbox in Functions and Objects Supported for C and C++
Code Generation — Category List.
• dsp.IIRHalfbandDecimator
• dsp.IIRHalfbandInterpolator
• dsp.AllpassFilter
See DSP System Toolbox in Functions and Objects Supported for C and C++ Code
Generation — Category List.
• 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.
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.
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.
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 .
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.
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
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
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
• 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
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:
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';
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.
4-4
Check bug reports for issues and fixes
function x = foo(x,N)
assert(all(size(x) == [1 100]))
x(x>N) = N;
• bweuler
• bwlabel
• bwperim
• regionprops
• watershed
• cameraMatrix
• cameraParameters
• extrinsics
• opticalFlow
• opticalFlowHS
• opticalFlowLK
• opticalFlowLKDoG
• reconstructScene
• rectifyStereoImages
• stereoParameters
• triangulate
• undistortImage
4-5
R2015a
• comm.CarrierSynchronizer
• comm.FMBroadcastDemodulator
• comm.FMBroadcastModulator
• comm.FMDemodulator
• comm.FMModulator
• comm.SymbolSynchronizer
• iirparameq
• dsp.HighpassFilter
• dsp.LowpassFilter
• pilotcalib
• phased.UCA
• phased.MFSKWaveform
4-6
Check bug reports for issues and fixes
• bandwidth
• isbanded
• isdiag
• istril
• istriu
• lsqnonneg
Statistics in MATLAB
• cummin
• cummax
See Functions and Objects Supported for C and C++ Code Generation — Alphabetical
List.
4-7
R2015a
To convert a project to a script using the MATLAB Coder app, on the workflow bar, click
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.
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.
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
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:
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:
The function that frees dynamic memory that emxInitArray_cstruct0_T allocates is:
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.
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');
x = coder.opaque('size_t','0');
x1 = cast(x, 'like', int32(0));
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:
Without this casting, it is possible to receive compiler warnings during code generation.
yt = coder.opaque('size_t', '42');
yt = coder.ceval('foo');
y = cast(yt, 'int32');
Because y is a MATLAB numeric type, you can use y as you would normally use a
variable in your MATLAB code.
It is possible that the explicit cast in the generated code prevents a compiler warning.
4-11
R2015a
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.
4-12
Check bug reports for issues and fixes
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:
cfg = coder.config('lib');
cfg.PassStructByReference = false;
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
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:
In R2015a, if you specify that a generated enumerated type value name includes the
class name prefix, the generated type value name:
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:
4-14
Check bug reports for issues and fixes
methods (Static)
function p = addClassNameToEnumNames()
p = true;
end
end
end
Fixed-point conversion now supports multiple entry-point functions. You can generate C/
C++ library functions to integrate with larger applications.
You can now convert MATLAB algorithms that contain global variables to fixed-point
code without modifying your MATLAB code.
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.
• 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.
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
4-16
Check bug reports for issues and fixes
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
For the list of Image Processing Toolbox functions supported for code generation, see
Image Processing 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.
• iqcoef2imbal
• iqimbal2coef
• comm.IQImbalanceCompensator
For the list of Communications System Toolbox™ functions supported for code
generation, see Communications 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.
• 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:
5-3
R2014b
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
};
5-4
Check bug reports for issues and fixes
RED(2)
end
methods(Static)
function y = addClassNameToEnumNames()
y = true;
end
end
end
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.
• feof
• frewind
5-5
R2014b
• ishermitian
• issymmetric
str2double
See Functions and Objects Supported for C and C++ Code Generation — Alphabetical
List.
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.
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.
5-7
R2014b
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
If you do not specify the -script option, coder writes the scripts to the Command
Window.
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.
5-8
Check bug reports for issues and fixes
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.
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.
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
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.
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.
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:
5-10
Check bug reports for issues and fixes
• 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.
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.
5-12
Check bug reports for issues and fixes
The checks for the data type issues are disabled by default.
1 In the Fixed-Point Conversion Tool, click Advanced to view the advanced settings.
2 Set Highlight potential data type issues to Yes.
fxptcfg.HighlightPotentialDataTypeIssues = true;
5-13
R2014b
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
• detectHarrisFeatures
• detectMinEigenFeatures
• estimateGeometricTransform
• findpeaks
• db2pow
• pow2db
6-2
Check bug reports for issues and fixes
• comm.OFDMModulator
• comm.OFDMDemodulator
• fminsearch
• optimget
• optimset
• interp3
• mkpp
• pchip
• ppval
• spline
• unmkpp
• 'spline’ and 'v5cubic’ interpolation methods for interp1
• 'spline’ and 'cubic’ interpolation methods for interp2
6-3
R2014a
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.
6-4
Check bug reports for issues and fixes
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
• 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.
6-5
R2014a
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.
• 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.
C99 (ISO)
C++ C89/C90 (ANSI) – default
6-6
Check bug reports for issues and fixes
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:
6-8
Check bug reports for issues and fixes
See coder.HardwareImplementation.
6-9
R2014a
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:
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.
• comm.OFDMModulator
• comm.OFDMDemodulator
• detectHarrisFeatures
• detectMinEigenFeatures
• estimateGeometricTransform
fread
6-11
R2014a
• interp2
• interp3
• mkpp
• pchip
• ppval
• polyarea
• rectint
• spline
• unmkpp
flip
• fminsearch
• optimget
• optimset
Polynomials in MATLAB
• polyder
6-12
Check bug reports for issues and fixes
• polyint
• polyvalm
• findpeaks
• db2pow
• pow2db
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.
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.
6-13
R2014a
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
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.
• narginchk
Programming Utilities
• mfilename
Specialized Math
• psi
• extractFeatures
• detectSURFFeatures
• disparity
• detectMSERFeatures
• detectFASTFeatures
• vision.CascadeObjectDetector
• vision.PointTracker
• vision.PeopleDetector
• cornerPoints
• MSERRegions
• SURFPoints
7-2
Check bug reports for issues and fixes
For more information, see parfor and Accelerate MATLAB Algorithms That Use Parallel
for-loops (parfor).
7-3
R2013b
• 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.
7-4
Check bug reports for issues and fixes
• 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.
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);
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.
7-6
Check bug reports for issues and fixes
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.
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/.
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
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.
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
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.
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.
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.
7-8
Check bug reports for issues and fixes
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
For more information, see Propose Fixed-Point Data Types Based on Simulation Ranges
and Propose Fixed-Point Data Types Based on Derived Ranges.
• fclose
• fopen
• fprintf
8-2
Check bug reports for issues and fixes
• 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;
For example, the following code for function foo specifies to include the application
header file mystruct.h in the generated code using double quotes.
...
8-3
R2013a
To view implementation details for the load function, see Functions Supported for Code
Generation — Alphabetical List.
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
8-4
Check bug reports for issues and fixes
MATLAB algorithm since the previous build, saving you time during the verification
phase.
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:
• 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';
8-5
R2013a
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.
• 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.
• cumprod
8-6
Check bug reports for issues and fixes
• cumsum
• factor
• factorial
• gcd
• isprime
• lcm
• median
• mode
• nchoosek
• nextpow2
• primes
• prod
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.
8-8
Check bug reports for issues and fixes
This enhancement reduces code size and execution time. It also improves code
readability.
Compatibility Considerations
If existing configuration settings disable BLAS, MATLAB Coder now ignores these
settings.
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/.
8-9
R2013a
• flintmax
• binaryFeatures
• insertMarker
• insertShape
• computer
• fclose
• fopen
• fprintf
• load
• conndef
• imcomplement
• imfill
• imhmax
• imhmin
• imreconstruct
• imregionalmax
• imregionalmin
• iptcheckconn
• padarray
• interp2
• ismac
8-10
Check bug reports for issues and fixes
• ispc
• isunix
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
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
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.
• deblank
• hex2num
• isletter
• isspace
• isstrprop
• lower
9-2
Check bug reports for issues and fixes
• num2hex
• strcmpi
• strjust
• strncmp
• strncmpi
• strtok
• strtrim
• upper
9-3
R2012b
9-4
Check bug reports for issues and fixes
For more information, see Package Code For Use in Another Development Environment.
You can use these proposed fixed-point data types to create a fixed-point version of your
original MATLAB entry-point function.
• integralImage
• bwlookup
9-5
R2012b
• bwmorph
• interp2
Trigonometric Functions
• atan2d
• 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.AllpoleFilter
• dsp.CICDecimator
• dsp.CICInterpolator
9-6
Check bug reports for issues and fixes
• dsp.IIRFilter
• dsp.SignalSource
9-7
R2012b
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
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.
For more information, see Generating C/C++ Dynamically Linked Libraries from
MATLAB Code.
10-2
Check bug reports for issues and fixes
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.
New Demo
The following demo has been added:
10-4
Check bug reports for issues and fixes
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
X(:,2) = [];
For more information, see Diminishing the Size of a Matrix in the MATLAB
documentation.
11-2
Check bug reports for issues and fixes
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
• 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
• 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.
12-2
Check bug reports for issues and fixes
12-3
R2011a
The codegen function uses new configuration objects that replace the old emlc objects
with the following differences:
• RTWCompilerOptimization is now
CCompilerOptimization
• RTWCustomCompilerOptimization is now
CCustomCompilerOptimization
• RTWVerbose is now Verbose
emlcoder.RTWConfig('ert')coder.EmbeddedCodeConfig
12-4
Check bug reports for issues and fixes
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.
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.
• coder.ArrayType
12-5
R2011a
• coder.Constant
• coder.EnumType
• coder.FiType
• coder.PrimitiveType
• coder.StructType
• coder.Type
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
12-6
Check bug reports for issues and fixes
New Demos
The following demos have been added:
12-7
R2011a
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
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