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