MATLAB Coder Users Guide PDF
MATLAB Coder Users Guide PDF
Users Guide
R2011b
Web
Newsgroup
www.mathworks.com/contact_TS.html Technical Support
www.mathworks.com
comp.soft-sys.matlab
suggest@mathworks.com
bugs@mathworks.com
doc@mathworks.com
service@mathworks.com
info@mathworks.com
508-647-7000 (Phone)
508-647-7001 (Fax)
The MathWorks, Inc.
3 Apple Hill Drive
Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site.
MATLAB Coder Users Guide
COPYRIGHT 2011 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern
the use, modification, reproduction, release, performance, display, and disclosure of the Program and
Documentation by the federal government (or other entity acquiring for or through the federal government)
and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the
governments needs or is inconsistent in any respect with federal procurement law, the government agrees
to return the Program and Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
April 2011
Online only
September 2011 Online only
Contents
About MATLAB Coder
1
Product Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About MATLAB Coder . . . . . . . . . . . . . . . . . . . . . . . . . . . .
When to Use MATLAB Coder . . . . . . . . . . . . . . . . . . . . . . .
Code Generation for Embedded Software Applications . . .
Code Generation for Fixed-Point Algorithms . . . . . . . . . . .
1-2
1-2
1-2
1-2
1-3
1-4
1-4
Bug Reports
2
Setting Up a MATLAB Coder Project
3
MATLAB Coder Project Set Up Workflow . . . . . . . . . . .
3-2
............................
3-3
3-5
3-6
3-7
3-7
3-7
iii
iv
Contents
3-10
3-10
3-12
3-12
3-17
3-21
3-25
3-26
3-27
3-27
3-28
3-29
3-31
3-31
3-31
3-32
3-33
3-33
3-34
3-34
3-35
3-35
3-35
More About . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-39
3-8
3-8
3-9
4
Preparing MATLAB Code for C/C++ Code Generation
Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4-2
4-3
4-4
4-5
4-6
4-6
4-6
4-9
4-10
4-11
4-12
4-13
4-13
4-13
4-14
4-14
4-15
4-15
4-16
4-17
Debugging Strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4-18
5
Workflow for Testing MEX Functions in MATLAB . . . .
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5-2
5-2
..............
5-4
5-5
5-5
5-7
6
Code Generation Workflow . . . . . . . . . . . . . . . . . . . . . . . . .
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-3
6-4
6-5
6-5
vi
Contents
6-6
6-6
6-7
6-8
6-8
6-10
6-12
6-12
6-15
6-15
6-18
6-20
6-21
6-22
6-22
6-30
6-30
6-30
6-34
6-35
6-51
6-51
6-51
6-52
6-56
6-56
6-58
Speeding Up Compilation . . . . . . . . . . . . . . . . . . . . . . . . . .
Generate Code Only . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Disable Compiler Optimization . . . . . . . . . . . . . . . . . . . . . .
6-62
6-62
6-62
Code Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Unrolling for-loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Inlining Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Eliminating Redundant Copies of Function Inputs
(A=foo(A)) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rewriting Logical Array Indexing as a Loop . . . . . . . . . . . .
6-64
6-64
6-66
6-36
6-42
6-58
6-58
6-59
6-59
6-67
6-69
vii
viii
Contents
6-70
6-70
6-70
6-70
6-71
6-71
6-73
6-73
6-73
6-76
6-78
6-78
6-80
6-80
6-80
6-81
6-82
6-87
6-88
6-88
6-89
6-91
6-92
6-96
6-98
6-99
6-99
6-100
6-102
6-104
6-120
6-120
6-120
6-121
6-127
6-129
6-134
6-134
6-134
6-135
6-170
6-171
6-173
6-174
6-174
6-177
6-178
6-179
6-181
6-181
6-181
6-183
6-189
6-190
6-190
7
Workflow for Accelerating MATLAB Algorithms . . . . . .
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7-2
7-3
ix
7-4
7-5
7-5
7-5
7-7
7-8
7-11
7-11
7-11
7-12
7-12
7-13
7-14
7-14
7-15
7-15
7-17
Contents
8-2
8-2
8-2
8-3
8-7
8-3
8-5
8-7
8-9
8-10
8-10
8-11
8-12
8-12
8-13
8-13
8-8
Examples
A
Generating MEX Functions . . . . . . . . . . . . . . . . . . . . . . . . .
A-2
..................
A-2
A-2
Specifying Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A-2
A-3
A-3
A-3
Index
xi
xii
Contents
1
About MATLAB Coder
Product Overview on page 1-2
Code Generation Workflow on page 1-4
Product Overview
In this section...
About MATLAB Coder on page 1-2
When to Use MATLAB Coder on page 1-2
Code Generation for Embedded Software Applications on page 1-2
Code Generation for Fixed-Point Algorithms on page 1-3
1-2
Product Overview
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.
See Also
MATLAB Tutorials in the Embedded Coder documentation.
1-3
See Also
Chapter 3, Setting Up a MATLAB Coder Project
Chapter 4, Preparing MATLAB Code for C/C++ Code Generation
Chapter 5, Testing MEX Functions in MATLAB
Chapter 6, Generating C/C++ Code from MATLAB Code
Chapter 7, Accelerating MATLAB Algorithms
1-4
2
Bug Reports
Software is inherently complex and is not free of errors. The output of a code
generator might contain bugs, some of which are not detected by a compiler.
MathWorks reports critical known bugs brought to its attention on its Bug
Report system at http://www.mathworks.com/support/bugreports/. Use the
Saved Searches and Watched Bugs tool with the search phrase Incorrect
Code Generation to obtain a report of known bugs that produce code that
might compile and execute, but still produce wrong answers.
The bug reports are an integral part of the documentation for each release.
Examine periodically all bug reports for a release, as such reports may
identify inconsistencies between the actual behavior of a release you are using
and the behavior described in this documentation.
In addition to reviewing bug reports, you should implement a verification and
validation strategy to identify potential bugs in your design, code, and tools.
2-2
Bug Reports
3
Setting Up a MATLAB
Coder Project
MATLAB Coder Project Set Up Workflow on page 3-2
Creating a New Project on page 3-3
Opening an Existing Project on page 3-5
Adding Files to the Project on page 3-6
Specifying Properties of Primary Function Inputs in a Project on page 3-7
Defining Input Parameters by Example in a Project on page 3-8
Defining or Editing Input Parameter Type in a Project on page 3-12
Defining Constant Input Parameters in a Project on page 3-25
Adding Global Variables in a Project on page 3-26
Specifying Global Variable Type and Initial Value in a Project on page
3-27
Output File Name Specification on page 3-33
Specifying Output File Locations on page 3-34
Selecting Output Type on page 3-35
More About on page 3-39
or C/C++ executable.
3-2
coder
3-3
3-4
3-5
3-6
See Also
Properties to Specify on page 6-30
3-7
context menu.
3 From this menu, select Define by Example.
3-8
) to open the
MATLAB Coder software uses the class, size, and complexity of the value
of the specified variable or MATLAB expression when compiling the code.
zeros(1,4,'uint16')
2 To specify that the input is variable size.
a On the project Overview tab, select the input.
b To the right of u, click the Actions icon to open the context menu.
c From the menu, select Edit Type.
d In the Define Type dialog box, click the Actions icon to open the context
menu.
3-9
The size of variable u changes from 1x4 to 1x:4. The colon, : indicates
that the second dimension is variable size with an upper bound of 4.
Alternatively, you can specify that the input is variable size by using the
coder.newtype function. In the Define by Example dialog box, enter the
following MATLAB expression:
coder.newtype('uint16',[1 4],[0 1])
expression:
MyColors.red
3-10
3-11
) to open the
context menu.
3 From the menu, select Define Type or Edit Type, as applicable.
4 In the Define Type dialog box, from the Class drop-down list, select a class.
3-12
Note To specify an enumerated type, enter its name in the Class field.
Define the enumerated type in a file on the MATLAB path. For more
information, see Code Generation for Enumerated Types on page 6-98.
5 In the Size field, enter the size.
Note If you enter an invalid size, MATLAB Coder highlights the Size field
in red to indicate that you must correct the size specification.
6 Optionally, to edit the type definition further, to the right of the Size field,
3-13
3-14
You can modify the size vector definition as described in the following table.
To...
Do this...
Specify a variable-size
dimension with fixed
upper bounds
upper bounds.
Note This action disables the Dimension Bound field for the
selected dimension.
Add a dimension
1 Select the dimension below which you want to add a new
dimension.
2 Click +.
3-15
menu.
3 From the menu, select Make Sizes Variable.
The size of variable u changes from 1x4 to 1x:4. The : indicates that the
second dimension is variable size with an upper bound of 4.
Note Alternatively, in the Size field, enter 1x:4 to specify a variable-size
input with an upper bound of 4. If the size of the dimension is 0 or 1, it is
always fixed in size.
3-16
green(1),
red(2),
end
end
2 In the Define Type dialog box Class type field, enter MyColors.
3-17
) to open the
context menu.
3 From this menu, select Edit Type.
In the Define Type dialog box, the input type is signed fixed-point with a
word length of 8 bits, a fraction length of 3 bits, and uses the global fimath.
3-18
on page 3-20.
3-19
fimath to True.
Additional fimath properties are displayed.
3-20
2 Select the property value that you want to change and set it to the value
Specifying Structures
When a primary input is a structure, MATLAB Coder treats each field as
a separate input. Therefore, you must specify properties for all fields of
a primary structure input in the order that they appear in the structure
definition, as follows:
For each field of input structures, specify class, size, and complexity.
For each field that is fixed-point class, also specify numerictype, and fimath.
to define.
3-21
) to open the
context menu.
3 From the menu, select Define Type or Edit Type, as applicable.
4 In the Define Type dialog box:
a From the Class drop-down list, select struct.
b Set the size and complexity of the structure as described in How to
on page 3-22. Set its size and complexity as described in How to Define
or Edit an Input Parameter Type on page 3-12.
6 Optionally, add fields to the structure as described in How to Add a Field
to a Structure on page 3-23 and then set their size and complexity.
3-22
menu.
3 From the menu, select Rename.
4 In the Rename Field dialog box New Name field, enter the field name
add a field.
2 To the right of the structure, click the Actions icon (
menu.
3 From the menu, select Add Field.
4 In the Rename Field dialog box New Name field, enter the field name
menu.
3 From the menu, select Insert Field.
4 In the Rename Field dialog box New Name field, enter the field name
3-23
menu.
3 From the menu, select Remove Field.
3-24
to define.
2 To the right of the parameter, click the Actions icon (
) to open the
context menu.
3 From this menu, select Define Constant.
4 In the Define Constant dialog box, enter the value of the constant or a
3-25
and, optionally, initial value. If you do not do this, you must create a
variable with the same name in the global workspace.
3-26
Define by example
Define type
2 Optionally, define an initial value for each global variable.
If you do not provide a type definition and initial value for a global variable,
you must create a variable with the same name and correct class, size,
complexity, and value in the MATLAB workspace.
Why Specify a Type Definition for Global Variables?
If you use global variables in your MATLAB algorithm, before building the
project, you must add a global type definition and initial value for each. If
you do not initialize the global data, MATLAB Coder looks for the variable
in the MATLAB global workspace. If the variable does not exist, MATLAB
Coder generates an error.
For MEX functions, if you use global data, you must also specify whether to
synchronize this data between MATLAB and the MEX function. For more
information, see Synchronizing Global Data with MATLAB on page 6-82.
3-27
to define.
context menu.
3 From this menu, select Define by Example.
3-28
) to open the
that has the required class, size, and complexity. MATLAB Coder software
uses the class, size, and complexity of the value of this expression as the
type for the global variable.
Note You define global variables in the same way that you define input
parameters. For more information, see Defining Input Parameters by
Example in a Project on page 3-8
to define.
) to open the
context menu.
3 From the menu, select Define Type or Edit Type, as applicable.
3-29
4 In the Define Type dialog box, from the Class drop-down list, select a class.
3-30
menu.
3 From the menu, select Define Initial Value.
Note This option is available only if the global variable has a specified
type.
4 In the Define Initial Value dialog box, enter a MATLAB expression.
rename.
2 To the right of the variable, click the Actions icon (
menu.
3 From this menu, select Rename.
4 In the Rename Global dialog box New Name field, enter the name of the
global variable.
menu.
3-31
global variable.
remove.
2 To the right of the variable, click the Actions icon (
menu.
3 From this menu, select Remove Global.
3-32
To learn how to change the default output folder, see Specifying Output
File Locations on page 3-34.
3-33
The default setting for the Build Folder field is A subfolder of the
project folder. By default, MATLAB Coder generates files in the folder
project_folder/codegen/target/fcn1:
fcn1 is the name of the first entry-point file
target is:
mex for MEX functions
lib for static C/C++ libraries
3-34
Parameter Name
General
Language
Saturate on integer overflow
Generated file partitioning method
Enable variable-sizing
Dynamic memory allocation
3-35
Parameter Name
Paths
Working folder
Build folder
Search paths
Report
Comments
Include comments
MATLAB source code as comments
Symbols
Reserved names
Custom Code
Source file
Header file
Initialize function
Terminate function
Include directories
Source files
Libraries
Post-code-generation command
Optimization
Advanced
Inline threshold
Inline threshold max
Inline stack limit
Stack usage max
Constant folding timeout
3-36
3-37
ReservedNameArray
SaturateOnIntegerOverflow
StackUsageMax
TargetLang
3-38
More About
More About
Primary Function Input Specification on page 6-30
How Working with Variable-Size Data Is Different for Code Generation
Code Generation for Complex Data
Code Generation for Enumerated Types on page 6-98
Generating C Code from MATLAB Code Using the MATLAB Coder Project
Interface
3-39
3-40
4
Preparing MATLAB Code
for C/C++ Code Generation
Preparing MATLAB Code for C/C++ Code Generation Workflow on page
4-2
Fixing Errors Detected by the Code Analyzer on page 4-4
How to Generate MEX Functions Using the MATLAB Coder Project
Interface on page 4-6
How to Generate MEX Functions at the Command Line on page 4-13
Fixing Errors Detected at Code Generation Time on page 4-15
Design Considerations When Writing MATLAB Code for Code Generation
on page 4-16
Debugging Strategies on page 4-18
4-2
See Also
Chapter 3, Setting Up a MATLAB Coder Project
Fixing Errors Detected by the Code Analyzer on page 4-4
How to Generate MEX Functions Using the MATLAB Coder Project
Interface on page 4-6
Fixing Errors Detected at Code Generation Time on page 4-15
Chapter 5, Testing MEX Functions in MATLAB
Chapter 6, Generating C/C++ Code from MATLAB Code
Chapter 7, Accelerating MATLAB Algorithms
4-3
If the indicator is red, a red 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.
4-4
Before generating code from your MATLAB code, you must fix any errors
detected by the code analyzer . For more information about how to fix
these errors, see Changing Code Based on Code Analyzer Messages in the
MATLAB Desktop Tools and Development Environment documentation.
See Also
Design Considerations When Writing MATLAB Code for Code Generation
on page 4-16
Debugging Strategies on page 4-18
4-5
Details
4-6
How to Generate MEX Functions Using the MATLAB Coder Project Interface
b On the project Overview tab, click the Add files link, browse to the
4-7
By default, the Output type is MEX function and the Output file name
is mcadd_mex.
4-8
How to Generate MEX Functions Using the MATLAB Coder Project Interface
4 On this tab, click the Build button to generate a MEX function using the
4-9
If you want to generate C/C++ code only, select this option. Doing so does not
invoke the make command or generate compiled object code.
When to Generate Code Only
After successful MEX generation.
During the development cycle, when you want to iterate rapidly between
modifying MATLAB code and generating code and you want to inspect
the code.
You want to compile the code with your own compiler.
Tip To learn more about the configuration parameters on the current tab
of the Project Settings dialog box, click the Help button in the dialog box.
See Also
How to Enable Code Generation Reports in the Project Settings Dialog
Box on page 6-177
In the Project Settings Dialog Box on page 6-120
4-10
How to Generate MEX Functions Using the MATLAB Coder Project Interface
See Also
Code Generation Reports on page 6-174
Code Generation for More Than One Entry-Point MATLAB Function
on page 6-73
4-11
See Also
Code Generation for More Than One Entry-Point MATLAB Function
on page 6-73
Code Generation for Global Data on page 6-80
Output File Name Specification on page 3-33
Specifying Output File Locations on page 3-34
4-12
Details
command line, specify that the two input parameters are int16 using the
-args option. By default, if you do not use the -args option, codegen treats
inputs as real, scalar doubles.
4-13
as the root name for the generated files and creates a platform-specific
extension for the MEX file, as described in Naming Conventions on page
6-71.
See Also
Primary Function Input Specification on page 6-30
Generating MEX Functions from MATLAB Code at the Command Line
Code Generation for More Than One Entry-Point MATLAB Function
on page 6-73
Code Generation for Global Data on page 6-80
4-14
See Also
Code Generation Reports on page 6-174
Why Test MEX Functions in MATLAB? on page 5-4
Design Considerations When Writing MATLAB Code for Code Generation
on page 4-16
Debugging Strategies on page 4-18
Declaring MATLAB Functions as Extrinsic Functions
4-15
4-16
See Also
About Code Generation from MATLAB Algorithms in the Code
Generation from MATLAB documentation
Defining MATLAB Variables for C/C++ Code Generationin the Code
Generation from MATLAB documentation
How Working with Variable-Size Data Is Different for Code Generation
in the Code Generation from MATLAB documentation
Bounded Versus Unbounded Variable-Size Data in the Code Generation
from MATLAB documentation
Enabling and Disabling Dynamic Memory Allocation on page 6-100
Controlling Run-Time Checks on page 7-14
4-17
Debugging Strategies
Before you perform code verification, MathWorks recommends that you
choose a debugging strategy for detecting and correcting noncompliant code
in your MATLAB applications, especially if they consist of a large number of
MATLAB files that call each others functions. The following table describes
two general strategies, each of which has advantages and disadvantages.
Debugging What to Do
Strategy
Pros
Cons
Bottom-up
verification
Efficient
lowest-level (leaf)
functions are compliant.
2 Work your way up
4-18
Unlikely to
cause errors
Easy to isolate
code generation
syntax violations
Debugging Strategies
Debugging What to Do
Strategy
Pros
Cons
Top-down
verification
function is compliant.
Additional assignment
statements as necessary
to convert opaque values
returned by extrinsic
functions to nonopaque
values (see Working with
mxArrays in the Code
Generation from MATLAB
documentation).
4-19
4-20
5
Testing MEX Functions in
MATLAB
Workflow for Testing MEX Functions in MATLAB on page 5-2
Why Test MEX Functions in MATLAB? on page 5-4
Debugging Run-Time Errors on page 5-5
See Also
Chapter 3, Setting Up a MATLAB Coder Project
5-2
5-3
5-4
5-5
Example Run-Time Stack Trace. This example shows the run-time stack
trace for MEX function mlstack_mex:
5-6
How to Disable the Run-Time Stack. You can disable the run-time stack
by disabling the memory integrity checks as described in How to Disable
Run-Time Checks on page 7-15.
Caution Before disabling the memory integrity checks, you should verify
that all array bounds and dimension checking is unnecessary.
5-7
5-8
6
Generating C/C++ Code
from MATLAB Code
Code Generation Workflow on page 6-3
C/C++ Code Generation on page 6-5
Generating Static C/C++ Libraries from MATLAB Code on page 6-6
Standalone C/C++ Executables from MATLAB Code on page 6-8
Build Setting Configuration on page 6-15
Primary Function Input Specification on page 6-30
Calling Generated C/C++ Functions on page 6-51
Custom C/C++ Code Integration on page 6-58
Speeding Up Compilation on page 6-62
Code Optimization on page 6-64
Paths and File Infrastructure Setup on page 6-70
Code Generation for More Than One Entry-Point MATLAB Function
on page 6-73
Code Generation for Global Data on page 6-80
Generation of Traceable Code on page 6-88
Code Generation for Enumerated Types on page 6-98
Code Generation for Variable-Size Data on page 6-99
How MATLAB Coder Partitions Generated Code on page 6-120
Customizing the Post-Code-Generation Build Process on page 6-134
6-2
6-3
See Also
Chapter 3, Setting Up a MATLAB Coder Project
Chapter 4, Preparing MATLAB Code for C/C++ Code Generation
Chapter 5, Testing MEX Functions in MATLAB
Build Setting Configuration on page 6-15
C/C++ Code Generation on page 6-5
Code Optimization on page 6-64
6-4
See...
If there are errors, MATLAB Coder does not generate code, but produces an
error report and provides a link to this report. For more information, see
Code Generation Reports on page 6-174.
Description
.c
Custom C file
.cpp
.h
.o , .obj
.a , .lib, .so
Library
.tmf
6-5
6-6
iii In the Define Type dialog box, set Class to int16. Click OK to
specify that the input is a scalar int16.
d Repeat step c for input v.
3 In the MATLAB Coder project, click the Build tab.
4 On this tab, set the Output type to C/C++ Static library.
settings.
MATLAB Coder builds the project and generates a C library and supporting
files in the default folder, codegen/lib/mcadd.
first input is a 1-by-4 vector of unsigned 16-bit integers and that the
second input is a double-precision scalar.
codegen -config:lib mcadd -args {zeros(1,4,'uint16'),0}
MATLAB Coder generates a C library with the default name, mcadd, and
supporting files in the default folder, codegen/lib/mcadd.
6-7
value from the standard uniform distribution on the open interval (0,1):
function r = coderand() %#codegen
r = rand();
2 Write a main C function, c:\myfiles\main.c, that calls coderand. For
example:
/*
** main.c
*/
#include <stdio.h>
#include <stdlib.h>
#include "coderand.h"
#include "coderand_initialize.h"
#include "coderand_terminate.h"
int main()
{
coderand_initialize();
6-8
printf("coderand=%g\n", coderand());
coderand_terminate();
return 0;
}
6-9
Note When you are building an executable, you must specify the main
function . For more information, see Specifying main Functions for C/C++
Executables on page 6-12.
7 On the Build tab, click the Build button to generate a library using the
See Also
Chapter 3, Setting Up a MATLAB Coder Project
Chapter 4, Preparing MATLAB Code for C/C++ Code Generation
Chapter 5, Testing MEX Functions in MATLAB
Build Setting Configuration on page 6-15
C/C++ Code Generation on page 6-5
Code Optimization on page 6-64
value from the standard uniform distribution on the open interval (0,1):
function r = coderand() %#codegen
r = rand();
6-10
example:
/*
** main.c
*/
#include <stdio.h>
#include <stdlib.h>
#include "coderand.h"
#include "coderand_initialize.h"
#include "coderand_terminate.h"
int main()
{
coderand_initialize();
printf("coderand=%g\n", coderand());
coderand_terminate();
return 0;
}
6-11
be built, set:
a Source files to the name of the C/C++ source file that contains the main
c:\myfiles.
6-12
cfg = coder.config('exe');
2 Set the CustomSource property to the name of the C/C++ source file that
contains the main function. (For more information, see Specifying main
Functions for C/C++ Executables on page 6-12.) For example:
cfg.CustomSource = 'main.c';
3 Set the CustomInclude property to the location of main.c. For example:
cfg.CustomInclude = 'c:\myfiles';
4 Generate the C/C++ executable using the appropriate command line
MATLAB Coder compiles and links the main function with the C/C++ code
that it generates from myMFunction.m.
cfg = coder.config('exe');
2 Open the Code Generation dialog box:
open cfg
3 On the Custom Source tab, under Include list of additional:
a Set Source files to the name of the C/C++ source file that contains the
6-13
c:\myfiles.
c Click Apply.
4 Generate the C/C++ executable using the appropriate command line
MATLAB Coder compiles and links the main function with the C/C++ code
that it generates from myMFunction.m.
6-14
6-15
Note Each time MATLAB Coder generates the same type of output for the
same code or project, it removes the files from the previous build. If you
want to preserve files from a build, copy them to a different location before
starting another build.
6-16
To Generate:
codegen foo
cfg = coder.config('mex');
% Set configuration parameters, for example,
% enable a code generation report
cfg.GenerateReport=true;
% Call codegen, passing the configuration
% object
codegen -config cfg foo
codegen -config:lib foo
cfg = coder.config('lib');
% Set configuration parameters, for example,
% enable a code generation report
cfg.GenerateReport=true;
% Call codegen, passing the configuration
% object
codegen -config cfg foo
codegen -config:exe main.c foo
6-17
To Generate:
cfg = coder.config('exe');
% Set configuration parameters, for example,
% specify main file
cfg.CustomSource = 'main.c';
cfg.CustomInclude = 'c:\myfiles';
codegen -config cfg foo
6-18
See Also.
Setting Up the C/C++ Compiler
Chapter 3, Setting Up a MATLAB Coder Project
cfg = coder.config('lib');
3 Set the TargetLang property to 'C' or 'C++'. For example:
cfg.TargetLang = 'C++';
See Also.
Working with Configuration Objects on page 6-24
Setting Up the C/C++ Compiler
cfg = coder.config('lib');
3 Open the configuration object dialog box:
open cfg
4 On the General tab, set Language to C or C++.
6-19
See Also.
Working with Configuration Objects on page 6-24
Setting Up the C/C++ Compiler
6-20
The default setting for the Build Folder field is A subfolder of the
project folder. By default, MATLAB Coder generates files in the folder
project_folder/codegen/target/fcn1:
fcn1 is the name of the first entry-point file
target is:
mex for MEX functions
lib for static C/C++ libraries
6-21
Use...
Details
Specifying Build
Configuration Parameters
in the Project Settings Dialog
Box on page 6-22
Configuration objects
Specifying Build
Configuration Parameters
at the Command Line Using
Configuration Objects on
page 6-23
Specifying Build
Configuration Parameters
at the Command Line Using
Dialog Boxes on page 6-28
6-22
The Project Settings dialog box opens. This dialog box provides the set of
configuration parameters applicable to the output type that you select.
Note MEX functions use a different set of configuration parameters than
C/C++ libraries and executables. When you switch the output type between
MEX Function and C/C++ Static Library or C/C++ Executable, verify
that these settings are correct. For more information, see Changing
Output Type on page 3-35.
2 Modify the parameters as necessary. For more information about
Description
coder.CodeConfig
coder.EmbeddedCodeConfig
6-23
Configuration Object
Description
coder.HardwareImplementation
coder.MexCodeConfig
of these methods:
Interactive commands, as described in Specifying Build Configuration
Parameters at the Command Line Using Configuration Objects on page
6-23
Dialog boxes, as described in Specifying Build Configuration Parameters
at the Command Line Using Dialog Boxes on page 6-28
3 Call the codegen function with the -config option. Specify the
6-24
The -config option instructs codegen to generate code for the target,
based on the configuration property values. In the following example,
codegen generates a C library from a MATLAB function, foo, based on
the parameters of a code generation configuration object, cfg, defined in
the first step:
codegen -config cfg foo
The -config option specifies the type of output that you want to build in
this case, a C library. For more information, see codegen.
6-25
6-26
To Create...
coder.EmbeddedCodeConfig
hwcfg = coder.HardwareImplementation
coder.HardwareImplementation
6-27
cfg = coder.config('lib');
cfg.GenerateReport= true;
cfg.LaunchReport = true;
codegen -config cfg foo
The save command saves mexcfg to the file mexcfg.mat in the current folder.
To restore mexcfg in a new MATLAB session, at the MATLAB prompt, enter:
load mexcfg.mat
The load command loads the objects defined in mexcfg.mat to the MATLAB
workspace.
Write a script that creates the configuration object and sets its
properties.
You can rerun the script whenever you need to use the configuration object
again.
6-28
Apply.
4 Call the codegen function with the -config option. Specify the
The -config option specifies the type of output that you want to build.
For more information, see codegen.
6-29
Properties to Specify
If your primary function has inputs, you must specify the following properties
for each input.
6-30
For...
Specify properties...
Class
Size
Complexity
numerictype
fimath
Fixed-point
inputs
Each field in
a structure
input
All other
inputs
Default
class
double
size
scalar
complexity
real
numerictype
No default
fimath
6-31
Specifying Default Values for Structure Fields. In most cases, when you
dont explicitly specify values for properties, MATLAB Coder uses defaults
except for structure fields. The only way to name a field in a structure is
to set at least one of its properties. Therefore, you might need to specify
default values for properties of structure fields. For examples, see Example:
Specifying Class and Size of Scalar Structure on page 6-49 and Example:
Specifying Class and Size of Structure Array on page 6-50.
Specifying Default fimath Values for MEX Functions. MEX functions
generated with MATLAB Coder use the default fimath value in effect at
compile time. If you do not specify a default fimath value, MATLAB Coder
uses the MATLAB default global fimath. The MATLAB factory default has
the following properties:
RoundMode:
OverflowMode:
ProductMode:
MaxProductWordLength:
SumMode:
MaxSumWordLength:
nearest
saturate
FullPrecision
128
FullPrecision
128
For more information, see Working with the Global fimath in the
Fixed-Point Toolbox documentation.
When running MEX functions that depend on the MATLAB default fimath
value, do not change this value during your MATLAB session. Otherwise, you
receive a run-time error, alerting you to a mismatch between the compile-time
and run-time fimath values.
For example, suppose you define the following MATLAB function test:
function y = test %#codegen
y = fi(0);
6-32
Now modify the MATLAB default fimath value so it no longer matches the
factory setting used at compile time:
F = fimath('RoundMode','Floor');
globalfimath(F);
Finally, clear the MEX function from memory and rerun it:
clear test_mex
test_mex
Supported Classes
The following table presents the class names supported by MATLAB Coder.
6-33
Class Name
Description
logical
char
Character array
int8
uint8
int16
uint16
int32
uint32
single
Single-precision floating-point or
fixed-point number array
double
Double-precision floating-point or
fixed-point number array
struct
Structure array
embedded.fi
6-34
Advantages
Disadvantages
Specifying Properties
of Primary Function
Inputs in a Project
on page 3-7
Easy to use
Does not alter original MATLAB
code
Designed for prototyping a
function that has a small
number of primary inputs
6-35
Method
Advantages
Efficient for specifying
memory-intensive inputs
such as large structures
Disadvantages
reenter the input types in the
project.
6-36
The cell array of sample values must contain the same number of elements
as primary function inputs.
The order of elements in the cell array must correspond to the order in
which inputs appear in the primary function signature for example, the
first element in the cell array defines the properties of the first primary
function input.
Note If you specify an empty cell array with the -args option, codegen
interprets this to mean that the function takes no inputs; a compile-time error
occurs if the function does have inputs.
This expression specifies that an input will be a constant with the size, class,
complexity, and value of constant_input.
Calling Functions with Constant Inputs. codegen compiles constant
function inputs into the generated code. As a result, the MEX function
signature differs from the MATLAB function signature. At run time you
supply the constant argument to the MATLAB function, but not to the MEX
function.
For example, consider the following function identity which copies its input
to its output:
function y = identity(u) %#codegen
y = u;
6-37
The following example shows how to specify that primary input u is a double
scalar variable and primary input p is a constant structure:
codegen rowcol -args {0,coder.Constant(tmp)}
6-38
6-39
stays fixed in size and its second dimension can grow to an upper bound of
100. Specify the second input n as a double scalar.
codegen -report nway -args {coder.typeof(0,[1 100],1),1}
3 As an alternative, assign the coder.typeof expression to a MATLAB
6-40
Assign sample values to a cell array variable to specify that both inputs are
real, unsigned 8-bit integer vectors:
a = uint8([1;2;3;4])
b = uint8([5;6;7;8])
ex = {a,b}
codegen mcf -args ex
T = numerictype('WordLength',32,
'FractionLength',23,
'Signed',true);
2 Define the fimath properties for x, as in this example:
F = fimath('SumMode','SpecifyPrecision',
'SumWordLength',32,
'SumFractionLength',23,
'ProductMode','SpecifyPrecision',
'ProductWordLength',32,
'ProductFractionLength',23);
3 Create a fixed-point variable with the numerictype and fimath properties
6-41
myeg = { fi(4.0,T,F) };
4 Compile the function sqrtfi using the codegen command, passing the
6-42
Sets the input parameter param to the MATLAB class class_name. For
example, to set the class of input U to a 32-bit signed integer, call:
...
assert(isa(U,'int32'));
...
If you set the class of an input parameter to fi, you must also set its
numerictype, see Specify numerictype of Fixed-Point Input on page 6-46.
You can also set its fimath properties, see Specify fimath of Fixed-Point
Input on page 6-46. If you do not set the fimath properties, codegen uses
the MATLAB default fimath value.
If you set the class of an input parameter to struct, you must specify the
properties of all fields in the order that they appear in the structure definition.
Specify fi Class.
assert ( isfi ( param ) )
assert ( isa ( param, 'embedded.fi' ) )
Sets the input parameter param to the MATLAB class fi (fixed-point numeric
object). For example, to set the class of input U to fi, call:
...
assert(isfi(U));
...
or
...
6-43
assert(isa(U,'embedded.fi'));
...
If you set the class of an input parameter to fi, you must also set its
numerictype, see Specify numerictype of Fixed-Point Input on page 6-46.
You can also set its fimath properties, see Specify fimath of Fixed-Point
Input on page 6-46. If you do not set the fimath properties, codegen uses
the MATLAB default fimath value.
If you set the class of an input parameter to struct, you must specify the
properties of all fields in the order they appear in the structure definition.
Specify Structure Class.
assert ( isstruct ( param ) )
assert ( isa ( param, 'struct' ) )
Sets the input parameter param to the MATLAB class struct (structure). For
example, to set the class of input U to a struct, call:
...
assert(isstruct(U));
...
or
...
assert(isa(U, 'struct'));
...
If you set the class of an input parameter to struct, you must specify the
properties of all fields in the order they appear in the structure definition.
Specify Any Size.
assert ( all ( size (param == [dims ] ) )
Sets the input parameter param to the size specified by dimensions dims. For
example, to set the size of input U to a 3-by-2 matrix, call:
...
assert(all(size(U)== [3 2]));
6-44
...
Sets the size of input parameter param to scalar. To set the size of input
U to scalar, call:
...
assert(isscalar(U));
...
or
...
assert(all(size(U)== [1]));
...
Specifies that the input parameter param is real. To specify that input U is
real, call:
...
assert(isreal(U));
...
Specifies that the input parameter param is complex. To specify that input U
is complex, call:
...
assert(~isreal(U));
...
6-45
If you do not specify the fimath properties using assert, codegen uses the
MATLAB default fimath value.
Specify Multiple Properties of Input.
assert ( function1 ( params ) &&
6-46
Specifies the class, size, and complexity of one or more inputs using a single
assert function call. For example, the following code specifies that input U is
a double, complex, 3-by-3 matrix, and input V is a 16-bit unsigned integer:
%#codegen
...
assert(isa(U,'double') &&
~isreal(U) &&
all(size(U) == [3 3]) &&
isa(V,'uint16'));
...
6-47
Property
Value
pennywhistle
class
int16
size
220500-by-1 vector
complexity
class
double
size
1024-by-1 vector
complexity
win
%#codegen
function y = mcspecgram(pennywhistle,win)
nx = 220500;
nfft = 1024;
assert(isa(pennywhistle,'int16'));
assert(all(size(pennywhistle) == [nx 1]));
assert(isa(win, 'double'));
assert(all(size(win) == [nfft 1]));
...
Alternatively, you can combine property specifications for one or more inputs
inside assert commands:
%#codegen
function y = mcspecgram(pennywhistle,win)
nx = 220500;
nfft = 1024;
assert(isa(pennywhistle,'int16') && all(size(pennywhistle) == [nx 1]));
assert(isa(win, 'double') && all(size(win) == [nfft 1]));
...
6-48
In the following example, the primary MATLAB function mcsqrtfi takes one
fixed-point input x. The code specifies the following properties for this input.
Property
Value
class
fi
numerictype
fimath
function
size
scalar
complexity
Here is code that specifies the class and size of S and its fields when passed as
an input to your MATLAB function:
%#codegen
function y = fcn(S)
% Specify the class of the input as struct.
6-49
assert(isstruct(S));
% Specify the class and size of the fields r and i
% in the order in which you defined them.
assert(isa(S.r,'double'));
assert(isa(S.i,'int8');
...
In most cases, when you dont explicitly specify values for properties,
MATLAB Coder uses defaults except for structure fields. The only way
to name a field in a structure is to set at least one of its properties. As a
minimum, you must specify the class of a structure field
The following code specifies the class and size of each field of structure input S
using the first element of the array:
%#codegen
function y = fcn(S)
% Specify the class of the input S as struct.
assert(isstruct(S));
% Specify the size of the fields r and i
% based on the first element of the array.
assert(all(size(S) == [2 2]));
assert(isa(S(1).r,'double'));
assert(isa(S(1).i,'int8'));
The only way to name a field in a structure is to set at least one of its
properties. As a minimum, you must specify the class of all fields.
6-50
For more information about optimizing your code by using the same variable
as both input and output, see Eliminating Redundant Copies of Function
Inputs (A=foo(A)) on page 6-67.
6-51
%#codegen
y = 1.5;
y = coder.ceval('myCFunction',y);
When to Call
primary_function_name_initialize
primary_function_name_terminate
From C/C++ code, you can call these functions directly. However, to call them
from MATLAB code that is suitable for code generation, you must use the
coder.ceval function. coder.ceval is a MATLAB Coder function, but is not
supported by the native MATLAB language. Therefore, if your MATLAB code
6-52
uses this function, use coder.target to disable these calls in MATLAB and
replace them with equivalent functions.
%#codegen
function y = callabsval
6-53
b At the MATLAB prompt, call the C library by running the MEX function.
6-54
6-55
For example, you can define a configuration object that points to the
custom C code:
a Create a configuration object. At the MATLAB prompt, enter:
cfg = coder.config('exe');
b Set custom code properties on the configuration object, as in these
example commands:
cfg.CustomSource = 'main.c';
cfg.CustomInclude = 'c:\myfiles';
3 Generate the C executable. Use the -args option to specify that the input
absval(-2.75)
See Also
Calling Generated C/C++ Functions on page 6-51
coder.wref function reference information
coder.ceval function reference information
6-56
values. Instead, you can return arrays from your C/C++ function by reference
as pointers by using coder.wref with coder.ceval.
See Also
Calling Generated C/C++ Functions on page 6-51
coder.wref function reference information
coder.ceval function reference information
6-57
generated files, set Source file and Header file as needed. Source file
specifies the code to appear at the top of generated C/C++ source files.
Header file specifies the code to appear at the top of generated header files.
Custom Code Property
Description
Under Additional files and directories to be built, provide an absolute path or a path
relative to the project folder.
Include directories
6-58
Description
Source files
Libraries
Header file
6-59
Description
CustomInclude
CustomSource
CustomLibrary
CustomSourceCode
CustomHeaderCode
object.
Note If you generate code for a function that has input parameters, you
must specify the inputs. For more information, see Primary Function
Input Specification on page 6-30.
codegen -config cc
6-60
myFunc
From...
Call...
coder.ceval.
See Also
Calling Generated C/C++ Functions on page 6-51
6-61
Speeding Up Compilation
In this section...
Generate Code Only on page 6-62
Disable Compiler Optimization on page 6-62
For more information and a complete list of compilation options, see codegen.
6-62
Speeding Up Compilation
cfg.CCompilerOptimization='Off';
6-63
Code Optimization
In this section...
Unrolling for-loops on page 6-64
Inlining Code on page 6-66
Eliminating Redundant Copies of Function Inputs (A=foo(A)) on page 6-67
Rewriting Logical Array Indexing as a Loop on page 6-69
Unrolling for-loops
Unrolling for-loops eliminates the loop logic by creating a separate copy of
the loop body in the generated code for each iteration. Within each iteration,
the loop index variable becomes a constant. By unrolling short loops with
known bounds at compile time, MATLAB generates highly optimized code
with no branches.
You can also force loop unrolling for individual functions by wrapping the loop
header in a coder.unroll function. For more information, see coder.unroll.
6-64
Code Optimization
The generated C code for getrand(50) does not unroll the for-loop because
the number of iterations is greater than 10:
6-65
Inlining Code
MATLAB uses internal heuristics to determine whether or not to inline
functions in the generated code. You can use the coder.inline directive to
fine-tune these heuristics for individual functions. For more information,
see coder.inline.
6-66
Code Optimization
6-67
...
MATLAB generates code that passes the inputs by value and returns the
value of the output:
...
/* Function Definitions */
real_T foo2(real_T A, real_T B)
{
return A * B;
}
...
In some cases, the output of the function cannot be a modified version of its
inputs. If you do not use the inputs later in the function, you can modify
your code to operate on the inputs instead of on a copy of the inputs. One
method is to create additional return values for the function. For example,
consider the code:
function y1=foo(u1) %#codegen
x1=u1+1;
y1=bar(x1);
end
function y2=bar(u2)
% Since foo does not use x1 later in the function,
% it would be optimal to do this operation in place
x2=u2.*2;
% The change in dimensions in the following code
% means that it cannot be done in place
6-68
Code Optimization
y2=[x2,x2];
end
You can modify this code to eliminate redundant copies. The changes are
highlighted in bold.
function y1=foo(u1) %#codegen
u1=u1+1;
[y1, u1]=bar(u1);
end
function [y2, u2]=bar(u2)
u2=u2.*2;
% The change in dimensions in the following code
% still means that it cannot be done in place
y2=[u2,u2];
end
The generated C code for this function is not very efficient. Rewrite the
MATLAB code to use a loop instead of logical indexing:
function x = foo_rewrite(x,N) %#codegen
assert(all(size(x) == [1 100]))
for ii=1:numel(x)
if x(ii) > N
x(ii) = N;
end
end
6-69
6-70
3 Add the customized version of the function to the code generation path.
Do this:
Code generation
path using the
MATLAB Coder
interface
tab.
3 For the Search paths field, either browse to add
MATLAB path
Naming Conventions
MATLAB Coder enforces naming conventions for MATLAB functions and
generated files.
Reserved Prefixes on page 6-72
Conventions for Naming Generated files on page 6-72
6-71
Reserved Prefixes
MATLAB Coder reserves the prefix eml for global C/C++ functions and
variables in generated code. For example, MATLAB for code generation
run-time library function names all begin with the prefix emlrt, such as
emlrtCallMATLAB. To avoid naming conflicts, do not name C/C++ functions or
primary MATLAB functions with the prefix eml.
6-72
Platform
MEX File
Extension
MATLAB
Coder Library
Extension
MATLAB Coder
Executable
Extension
Linus Torvalds
Linux (32-bit)
.mexglx
.a
None
Linux x86-64
.mexa64
.a
None
Microsoft
Windows (32-bit)
.mexw32
.lib
.exe
Windows x64
.mexw64
.lib
.exe
6-73
6-74
By default, the Output type is MEX function and the Output file name
is ep1_mex.
5 On this tab, click the Build button to generate a MEX function using the
6-75
You can now test your MEX function in MATLAB. For more information,
see How to Call an Entry-Point Function in a MEX Function on page 6-78.
Generating a C Library with Two Entry-Point Functions Using the
Project Interface
You can generate a C library with two entry-point functions, ep1 and ep2,
following the same project set-up steps that you use to generate a MEX
function. (See Generating a MEX Function with Two Entry-Point Functions
Using the Project Interface on page 6-74.) When you build the project, set the
Output type to C/C++ Static Library.
MATLAB Coder builds the project and generates a C library, ep1, and
supporting files in the default folder, codegen/lib/ep1.
You can now test your library. For more information, see How to Call an
Entry-Point Function in a C/C++ Library Function from C/C++ Code on
page 6-78.
By default, codegen:
Generates a MEX function in the current folder. codegen names the MEX
function , fun_1_mex. fun_1 is the name of the first entry-point function.
Stores generated files in the subfolder codegen/mex/fun_1/.
If you specify an output file name, out_fun, using the -o option, codegen
stores the generated files in the subfolder codegen/mex/out_fun/. For more
information on setting build options at the command line, see codegen.
6-76
6-77
6-78
6-79
If you use global data, you must also specify whether you want to synchronize
this data between MATLAB and the generated MEX function. For more
information, see Synchronizing Global Data with MATLAB on page 6-82.
6-80
global B;
AR(1) = u + B(1);
y = AR * 2;
6-81
3 After adding a global variable, before building the project, specify its type
and, optionally, initial value. For more information, see Specifying Global
Variable Type and Initial Value in a Project on page 3-27.
Note If you do not specify the type, you must create a variable with the
same name in the global workspace.
Alternatively, specify the type and initial value with the -globals flag using
the format -globals {'g', {type, initial_value}}.
Defining Variable-Size Global Data. To provide initial values for
variable-size global data, specify the type and initial value with the -globals
flag using the format -globals {'g', {type, initial_value}}. For
example, to specify a global variable g1 that has an initial value [1 1] and
upper bound [2 2], enter:
codegen foo -globals {'g1', {coder.typeof(0, [2 2],1),[1 1]}}
6-82
their global variables might differ. The level of interaction determines when
to synchronize global data. For more information, see When to Synchronize
Global Data on page 6-83.
6-83
Set the
global data
synchronization
mode to:
Synchronize before
and after extrinsic
calls?
At MEX-function
entry, exit and
extrinsic calls
At MEX-function
entry, exit and
extrinsic calls
Yes.
(default)
At MEX-function
entry and exit
Maximize performance
when synchronizing global
data, and none of your
extrinsic calls modify global
data.
At MEX-function
entry and exit
No.
Communicate between
generated MEX functions
only. No interaction
between MATLAB and
MEX function global data.
Disabled
No.
(default)
Use the
coder.extrinsic
-sync:off option to
Yes.
Use the
coder.extrinsic
-sync:on option to
6-84
You can control the global data synchronization mode from the project
settings dialog box, the command line, or a MEX configuration dialog box.
You control the synchronization of data with extrinsic functions using the
coder.extrinsic -sync:on and -sync:off options.
Controlling the Global Data Synchronization Mode in the Project
Settings Dialog Box.
1 On the MATLAB Coder project Build tab, verify that Output type is set
example, to generate a MEX function for function foo that has no inputs:
codegen -config mexcfg foo
6-85
open mexcfg
3 On the dialog box General tab, set Global data synchronization mode
as applicable.
4 When compiling your code, use the mexcfg configuration object. For
example, to generate a MEX function for function foo that has no inputs:
codegen -config mexcfg myFile
6-86
6-87
6-88
a constructor command:
mexcfg = coder.config('mex');
2 From the command line, enable the MATLABSourceComments:
mexcfg.MATLABSourceComments = true;
6-89
3 Using the -config option, pass the configuration object to codegen. For
example, to generate a MEX function for a function foo that has no input
parameters:
codegen -config mexcfg foo
Alternatively, you can set this parameter using the MATLAB Coder Project
Settings dialog box. On the Comments pane , select MATLAB source code
as comments. For more information, see Specifying Build Configuration
Parameters at the Command Line Using Dialog Boxes on page 6-28.
For C/C++ Libraries. Use the MATLABSourceComments option of the code
generation configuration object. For example, to compile the file foo.m and
include the source code as comments in the generated code for a C library:
1 Create a code generation configuration object and enable the
For example, to generate a library for a function foo that has no input
parameters:
codegen -config cfg foo
For Embedded Coder projects (requires an Embedded Coder license), you can
also include the function help text in the generated code function banner
using the MATLABFcnDesc option. For more information, see Tracing
Between Generated C Code and MATLAB Code in the Embedded Coder
documentation.
For C/C++ Executables. Use the MATLABSourceComments option of the code
generation configuration object. For example, to compile the file foo.m and
include the source code as comments in the generated code for a C executable:
6-90
For Embedded Coder projects, (requires an Embedded Coder license), you can
also include the function help text in the function banner of the generated
code using the MATLABFcnDesc option. For more information, see Tracing
Between Generated C Code and MATLAB Code in the Embedded Coder
documentation.
Note With an Embedded Coder license, the traceability tags in the code
generation report are hyperlinks to the MATLAB source code. For more
information, see Tracing Between Generated C Code and MATLAB Code in
the Embedded Coder documentation.
6-91
Commented C Code.
void straightline(real_T r, real_T theta, ...
real_T *x, real_T *y)
{
/* Convert polar to Cartesian */
/* 'straightline:4' x = r * cos(theta); */
*x = r * muDoubleScalarCos(theta);
/* 'straightline:5' y = r * sin(theta); */
*y = r * muDoubleScalarSin(theta);
}
If Statements
The comment for the if statement immediately precedes the code that
implements the statement. This comment appears after any user comment
6-92
that precedes the generated code. The comments for the elseif and else
clauses appear immediately after the code that implements the clause, and
before the code generated for statements in the clause.
MATLAB Code.
function y = ifstmt(u,v)
%#codegen
if u > v
y = v + 10;
elseif u == v
y = u * 2;
else
y = v - 10;
end
Commented C Code.
real_T ifstmt(real_T u, real_T v)
{
/* 'ifstmt:3' if u > v */
if(u > v) {
/* 'ifstmt:4' y = v + 10; */
return v + 10.0;
} else if(u == v) {
/* 'ifstmt:5' elseif u == v */
/* 'ifstmt:6' y = u * 2; */
return u * 2.0;
} else {
/* 'ifstmt:7' else */
/* 'ifstmt:8' y = v - 10; */
return v - 10.0;
}
}
6-93
For Statements
The comment for the for statement header immediately precedes the
generated code that implements the header. This comment appears after any
user comment that precedes the generated code.
MATLAB Code.
function y = forstmt(u)
%#codegen
y = 0;
for i=1:u
y = y + 1;
end
Commented C Code.
real_T forstmt(real_T u)
{
real_T y;
real_T i;
/* 'forstmt:3' y = 0; */
y = 0.0;
/* 'forstmt:4' for i=1:u */
for(i = 1.0; i <= u; i++) {
/* 'forstmt:5' y = y + 1; */
y++;
}
return y;
}
While Statements
The comment for the while statement header immediately precedes the
generated code that implements the statement header. This comment appears
after any user comment that precedes the generated code.
MATLAB Code.
function y = subfcn(y)
coder.inline('never');
while y < 100
6-94
y = y + 1;
end
Commented C Code.
static void m_refp1_subfcn(real_T *y)
{
/* 'whilestmt:6' coder.inline('never'); */
/* 'whilestmt:7' while y < 100 */
while(*y < 100.0) {
/* 'whilestmt:8' y = y + 1; */
(*y)++;
}
}
Switch Statements
The comment for the switch statement header immediately precedes the
generated code that implements the statement header. This comment appears
after any user comment that precedes the generated code. The comments for
the case and otherwise clauses appear immediately after the generated code
that implements the clause, and before the code generated for statements
in the clause.
MATLAB Code.
function y = switchstmt(u)
%#codegen
y = 0;
switch u
case 1
y = y + 1;
case 3
y = y + 2;
otherwise
y = y - 1;
end
6-95
Commented C Code.
real_T switchstmt(real_T u)
{
/* 'switchstmt:3' y = 0; */
/* 'switchstmt:4' switch u */
switch((int32_T)u) {
case 1:
/* 'switchstmt:5' case 1 */
/* 'switchstmt:6' y = y + 1; */
return 1.0;
break;
case 3:
/* 'switchstmt:7' case 3 */
/* 'switchstmt:8' y = y + 2; */
return 2.0;
break;
default:
/* 'switchstmt:9' otherwise */
/* 'switchstmt:10' y = y - 1; */
return -1.0;
break;
}
}
Traceability Limitations
For MATLAB Coder, there are traceability limitations:
You cannot include MATLAB source code as comments for:
6-96
6-97
6-98
6-99
dialog box.
option:
mexcfg = coder.config('mex');
mexcfg.EnableVariableSizing = false;
2 Using the -config option, pass the configuration object to codegen. For
EnableVariableSizing option:
cfg = coder.config('exe');
cfg.EnableVariableSizing = false;
2 Using the -config option, pass the configuration object to codegen :
6-100
memory allocation from the project settings dialog box, the command line,
or using dialog boxes.
dynamic memory allocation and generate a MEX function for a function, foo,
that takes no inputs:
1 Create a MEX configuration object and set the DynamicMemoryAllocation
option:
mexcfg = coder.config('mex');
mexcfg.DynamicMemoryAllocation = 'AllVariableSizeArrays';
2 Using the -config option, pass the configuration object to codegen:
DynamicMemoryAllocation option:
6-101
cfg = coder.config('exe');
cfg.DynamicMemoryAllocation = 'AllVariableSizeArrays';
2 Using the -config option, pass the configuration object to codegen :
In some cases, the MATLAB Code Analyzer warns you when your code
assigns data a fixed size but later grows the data, such as by assignment
or concatenation in a loop. If that data is supposed to vary in size at run
time, you can ignore these warnings.
3 Generate a MEX function using codegen to verify the generated code. Use
6-102
Cause:
How To Fix:
For More
Information:
See Diagnosing
and Fixing Size
Mismatch Errors in
the Code Generation
from MATLAB
documentation.
6-103
Cause:
How To Fix:
For More
Information:
MATLAB cannot
determine or
compute the upper
bound
Specify an upper
bound.
MATLAB attempts
to compute an upper
bound for unbounded
variable-size data.
If the data is
unbounded, enable
dynamic memory
allocation.
6-104
In this function, vector B should expand in size as it adds values from vector A.
Therefore, you can ignore this warning.
6-105
6-106
The error indicates a size mismatch between the left-hand side and right-hand
side of the assignment statement B = [B A(i)];. The assignment B =
A(1) establishes the size of B as a fixed-size scalar (1 x 1). Therefore, the
concatenation of [B A(i)] creates a 1 x 2 vector.
coder.varsize('B');
6-107
coder.varsize('B');
B = A(1);
k = 1;
for i = 2:length(A)
if abs(A(k) - A(i)) > tol
B = [B A(i)];
k = i;
end
end
6-108
This error occurs because codegen cannot determine an upper bound for B .
6-109
coder.varsize('B', [1 100]);
The argument [1 100] specifies that B is a vector with its first dimension
fixed at size 1 and the second dimension variable to an upper bound of
100. The value of 100 matches the upper bound of variable-size vector A.
Based on the algorithm, output B is at most as large as input A. By default,
dimensions of 1 are fixed size.
Here is the modified code:
function B = uniquetol(A, tol) %#codegen
A = sort(A);
coder.varsize('B', [1 100]);
B = A(1);
k = 1;
for i = 2:length(A)
if abs(A(k) - A(i)) > tol
B = [B A(i)];
k = i;
end
end
2 Compile the function again:
This exercise presents one way to specify an upper bound. To learn about
other methods, see Specifying Upper Bounds for Variable-Size Data in the
Code Generation from MATLAB documentation.
Enable Dynamic Memory Allocation for an Unbounded Variable B.
Choose this method if you do not know the upper bound for B or do not need
to enforce an upper bound. In this exercise, you will also remove the upper
bound for input A.
6-110
generation:
cfg = coder.config('mex');
cfg.DynamicMemoryAllocation = 'AllVariableSizeArrays';
2 Compile the function again, adding a -config argument:
If you do not know the upper bounds of an input, it is good coding practice
to specify the input as unbounded instead of giving it an arbitrary upper
bound. In this codegen command, the size of the second dimension of
input A is Inf. When you specify the size of a dimension as Inf in a
coder.typeof statement, codegen treats the dimension as unbounded.
You can use Inf only with dynamic allocation.
See Also.
codegen
Primary Function Input Specification on page 6-30
6-111
generation:
cfg=coder.config('lib');
cfg.DynamicMemoryAllocation = 'AllVariableSizeArrays';
2 Issue this command:
In the generated code, MATLAB represents data with unknown upper bounds
as a data type called emxArray. MATLAB provides utility functions for
creating and interacting with emxArrays in your generated code.
See Also.
C Code Interface for Unbounded Arrays and Structure Fields in the Code
Generation from MATLAB documentation.
The following code will create a folder in your current working folder (pwd).
The new folder will contain only the files that are relevant for this example. If
you do not want to affect the current folder (or if you cannot generate files in
this folder), change your working folder.
Run Command: Create a New Folder and Copy Relevant Files
coderdemo_setup('coderdemo_atoms');
About the run_atoms Function
6-112
Create a template structure Atom to provide the compiler with the necessary
information about input parameter types. An atom is a structure with four
fields (x,y,vx,vy) specifying position and velocity in Cartesian coordinates.
atom = struct('x', 0, 'y', 0, 'vx', 0, 'vy', 0);
Generate a MEX Function for Testing
6-113
atoms =
1x10000 struct array with fields:
x
y
vx
vy
atoms =
1x10000 struct array with fields:
x
y
vx
vy
6-114
In MATLAB the default data type is double. However, integers are usually
used in C code, so pass int32 integer example values to represent the number
of atoms and iterations.
.
..
buildInfo.mat
rtGetInf.c
rtGetInf.h
rtGetInf.obj
rtGetNaN.c
rtGetNaN.h
rtGetNaN.obj
rt_nonfinite.c
rt_nonfinite.h
rt_nonfinite.obj
rtw_proj.tmw
rtwtypes.h
run_atoms.c
run_atoms.h
run_atoms.lib
run_atoms.lnk
run_atoms.obj
run_atoms_emxAPI.c
run_atoms_emxAPI.h
run_atoms_emxAPI.obj
run_atoms_emxutil.c
run_atoms_emxutil.h
run_atoms_emxutil.obj
run_atoms_initialize.c
run_atoms_initialize.h
run_atoms_initialize.obj
run_atoms_ref.rsp
run_atoms_rtw.bat
run_atoms_rtw.mk
run_atoms_terminate.c
run_atoms_terminate.h
run_atoms_terminate.obj
run_atoms_types.h
6-115
6-116
printf("%f %f %f %f\n",
atoms->data[i].x, atoms->data[i].y, atoms->data[i].vx, atoms}
/* Free memory */
emxDestroyArray_Atom(atoms);
}
cfg = coder.config('exe');
cfg.DynamicMemoryAllocation = 'AllVariableSizeArrays';
Generate a Standalone Executable
6-117
for i = 1:size(atoms_state,1)
atoms(1,i).x = atoms_state(i,1);
atoms(1,i).y = atoms_state(i,2);
atoms(1,i).vx = atoms_state(i,3);
atoms(1,i).vy = atoms_state(i,4);
end
Render the State
Clean Up
6-118
if ispc
delete run_atoms.exe
else
delete run_atoms
end
delete atoms_state.mat
cleanup
6-119
6-120
Generate one file for each MATLAB file or Generate all functions
into a single file. Close the dialog box.
option:
mexcfg = coder.config('mex');
mexcfg.FilePartitionMethod = 'MapMFileToCFile';
2 Using the -config option, pass the configuration object to codegen:
FilePartitionMethod option:
cfg = coder.config('exe');
cfg.FilePartitionMethod = 'SingleFile';
2 Using the -config option, pass the configuration object to codegen.
6-121
output type.
c In the Project Settings dialog box, click the Advanced tab.
d Set the Inline threshold parameter to 0.
4 Click Build to generate a library.
6-122
MATLAB Coder generates source, header, and object files for foo and
identity in your output folder.
6-123
function y = identity(u)
y = u;
To generate a C++ library, before generating code, make sure you select a
C++ compiler and select C++ as your target language. For example, at the
command line:
1 Select C++ as your target language:
cfg = coder.config('lib')
cfg.TargetLang='C++'
2 Generate the C++ library:
In the primary function foo, MATLAB Coder inlines the code for the
identity subfunction.
6-124
...
/* Function Definitions */
real_T foo(real_T u, real_T v)
{
return (real_T)(real32_T)u + v;
}
...
6-125
MATLAB Coder generates C source, header, and object files for each
implementation of multiply_defined, as highlighted. Use numeric suffixes
to create unique file names.
6-126
Location
Current folder
codegen/mex/function_name
HTML reports
codegen/mex/function_name/html
Location
codegen/lib/function_name
HTML reports
codegen/lib/function_name/html
6-127
Type of Files
Location
codegen/exe/function_name
HTML reports
codegen/exe/function_name/html
Do this...
tab.
3 On this tab, set Build folder to Specified
folder.
6-128
To change the...
Do this...
At the Command Line. You can change the name and location of generated
files by using the codegen options -o and -d.
MATLAB Coder...
6-129
6-130
If you...
MATLAB Coder...
Generated
C/C++ Code
Advantages
Disadvantages
All C/C++
functions into
a single file
Easier to
integrate
with existing
embedded
software
Difficult to
map C/C++
code to original
MATLAB file
One C/C++-file
for each
MATLAB file
and enable
inlining
Program
executes faster
Difficult to
map C/C++
code to original
MATLAB file
One C/C++-file
for each
MATLAB file
and disable
inlining
Matches
MATLAB file
structure
Easy to map
C/C++ code
to original
MATLAB file
Program runs
less efficiently
6-131
2 On this tab, click the More settings link to view the project settings for
-O disable:inline foo
The directive applies only to the function in which it appears. In this example,
inlining is disabled for function foo, but not for identity, a top-level function
defined in a separate MATLAB file and called by foo. To disable inlining for
identity, add this directive after its function signature in the source file
identity.m. For more information, see coder.inline.
For a more efficient way to disable inlining for both functions, see How to
Disable Inlining Globally at the Command Line on page 6-132.
6-132
6-133
command to get the project name and build information or to add data to
the build information object.
2 Use this command in your build.
6-134
Linker options
Source files and paths
Include files and paths
Precompiled external libraries
Use the Build Information Functions on page 6-135 to access this information
in the build information object. Programming a Post-Code-Generation
Command on page 6-170 explains how to use the functions to control a
post-code-generation build.
6-135
addCompileFlags
Purpose. Add compiler options to projects build information
Syntax.
addCompileFlags(buildinfo, options, groups)
groups is optional.
Arguments.
buildinfo
6-136
'-O3'
groups (optional)
Character array.
addDefines
Purpose. Add preprocessor macro definitions to projects build information
Syntax.
addDefines(buildinfo, macrodefs, groups)
groups is optional.
6-137
Arguments.
buildinfo
'-DPRODUCTION'
groups (optional)
6-138
To...
Character array.
addIncludeFiles
Purpose. Add include files to projects build information
object
Syntax.
addIncludeFiles(buildinfo, filenames, paths, groups)
paths and groups are optional.
Arguments.
buildinfo
6-139
Character array.
6-140
The Function...
Character array
If you choose to specify groups, but omit paths, specify a null string ('')
for paths.
addIncludePaths
Purpose. Add include paths to projects build information
Syntax.
addIncludePaths(buildinfo, paths, groups)
groups is optional.
Arguments.
buildinfo
6-141
groups (optional)
Character array.
6-142
The Function...
Character array
addLinkFlags
Purpose. Add link options to projects build information
Syntax.
addLinkFlags(buildinfo, options, groups)
groups is optional.
Arguments.
buildinfo
'-T'
groups (optional)
6-143
Character array.
addLinkObjects
Purpose. Add link objects to projects build information
Syntax.
addLinkObjects(buildinfo, linkobjs, paths, priority,
precompiled, linkonly, groups)
All arguments except buildinfo , linkobjs, and paths are optional. If you
specify an optional argument, you must specify all of the optional arguments
preceding it.
6-144
Arguments.
buildinfo
6-145
6-146
To...
Character array.
The Function...
Character array
6-147
The Function...
Value
Vector of values
If you choose to specify an optional argument, you must specify all of the
optional arguments preceding it. For example, to specify that all objects are
precompiled using the precompiled argument, you must specify the priority
argument that precedes precompiled. You could pass the default priority
value 1000, as shown below.
addLinkObjects(myBuildInfo, 'test1', '/proj/lib/lib1', 1000, true);
addNonBuildFiles
Purpose. Add nonbuild-related files to projects build information
Syntax.
addNonBuildFiles(buildinfo, filenames, paths, groups)
paths and groups are optional.
Arguments.
buildinfo
6-148
The function adds the filenames to the end of a vector in the order that
you specify them.
The function removes duplicate nonbuild file entries that
Already exist in the nonbuild file vector
Have a path that matches the path of a matching filename
A duplicate entry consists of an exact match of a path string and
corresponding filename.
paths (optional)
Character array.
6-149
The Function...
Character array
If you choose to specify groups, but omit paths, specify a null string ('')
for paths.
addSourceFiles
Purpose. Add source files to projects build information
Syntax.
addSourceFiles(buildinfo, filenames, paths, groups)
paths and groups are optional.
Arguments.
buildinfo
6-150
The filename strings can include wildcard characters, provided that the
dot delimiter (.) is present. Examples are '*.*', '*.c', and '*.c*'.
The function adds the filenames to the end of a vector in the order that
you specify them.
The function removes duplicate source file entries that
You specify as input
Already exist in the source file vector
Have a path that matches the path of a matching filename
A duplicate entry consists of an exact match of a path string and
corresponding filename.
paths (optional)
6-151
To...
Character array.
The Function...
Character array
If you choose to specify groups, but omit paths, specify a null string ('')
for paths.
addSourcePaths
Purpose. Add source paths to projects build information
Syntax.
addSourcePaths(buildinfo, paths, groups)
groups is optional.
6-152
Arguments.
buildinfo
6-153
Character array.
The Function...
Character array
Note The MATLAB Coder software does not check whether a specified path
string is valid.
6-154
addTMFTokens
Purpose. Add template makefile (TMF) tokens that provide build-time
information for makefile generation
Syntax.
addTMFTokens(buildinfo, tokennames, tokenvalues, groups)
groups is optional.
Arguments.
buildinfo
6-155
Character array.
6-156
The Function...
Character array
findIncludeFiles
Purpose. Find and add include (header) files to build information object
Syntax.
findIncludeFiles(buildinfo, extPatterns)
extPatterns is optional.
Arguments.
buildinfo
6-157
getCompileFlags
Purpose. Compiler options from projects build information
Syntax.
options = getCompileFlags(buildinfo, includeGroups,
excludeGroups)
includeGroups and excludeGroups are optional.
Input Arguments.
buildinfo
getDefines
Purpose. Preprocessor macro definitions from projects build information
6-158
Syntax.
[macrodefs, identifiers, values] = getDefines(buildinfo,
includeGroups, excludeGroups)
includeGroups and excludeGroups are optional.
Input Arguments.
buildinfo
Description
macrodefs
identifiers
values
6-159
getFullFileList
Purpose. All files from projects build information
Syntax.
[fPathNames, names] = getFullFileList(buildinfo, fcase)
fcase is optional.
Input Arguments.
buildinfo
The Function...
'source'
'include'
'nonbuild'
Output Arguments. Fully-qualified file paths and file names for files stored
in the projects build information.
6-160
Note Usually it is not necessary to resolve the path of every file in the project
build information, because the makefile for the project build will resolve file
locations based on source paths and rules. Therefore, getFullFileList
returns the path for each file only if a path was explicitly associated with the
file when it was added, or if you called updateFilePathsAndExtensions to
resolve file paths and extensions before calling getFullFileList.
Description. The getFullFileList function returns the fully-qualified
paths and names of all files, or files of a selected type (source, include, or
nonbuild), stored in the projects build information.
getIncludeFiles
Purpose. Get include files from projects build information
Syntax.
files = getIncludeFiles(buildinfo, concatenatePaths,
replaceMatlabroot, includeGroups, excludeGroups)
includeGroups and excludeGroups are optional.
Arguments.
buildinfo
The Function...
true
false
replaceMatlabroot
6-161
If You Specify...
The Function...
true
false
includeGroups (optional)
getIncludePaths
Purpose. Get include paths from projects build information
Syntax.
files=getIncludePaths(buildinfo, replaceMatlabroot,
includeGroups, excludeGroups)
includeGroups and excludeGroups are optional.
6-162
Input Arguments.
buildinfo
The Function...
true
false
includeGroups (optional)
getLinkFlags
Purpose. Link options from projects build information
6-163
Syntax.
options=getLinkFlags(buildinfo, includeGroups, excludeGroups)
includeGroups and excludeGroups are optional.
Input Arguments.
buildinfo
A character array or cell array that specifies groups of linker flags you
want the function to return.
excludeGroups (optional)
A character array or cell array that specifies groups of linker flags you
do not want the function to return. To exclude groups and not include
specific groups, specify an empty cell array ('') for includeGroups.
Output Arguments. Linker options stored in the projects build information.
Description. The getLinkFlags function returns linker options stored
in the projects build information. Using optional includeGroups and
excludeGroups arguments, you can selectively include or exclude groups of
options the function returns.
If you choose to specify excludeGroups and omit includeGroups, specify a
null string ('') for includeGroups.
getNonBuildFiles
Purpose. Nonbuild-related files from projects build information
Syntax.
files=getNonBuildFiles(buildinfo, concatenatePaths,
replaceMatlabroot, includeGroups, excludeGroups)
includeGroups and excludeGroups are optional.
6-164
Input Arguments.
buildinfo
The Function...
true
false
replaceMatlabroot
The Function...
true
false
includeGroups (optional)
6-165
getSourceFiles
Purpose. Source files from projects build information
Syntax.
srcfiles=getSourceFiles(buildinfo, concatenatePaths,
replaceMatlabroot, includeGroups, excludeGroups)
includeGroups and excludeGroups are optional.
Input Arguments.
buildinfo
6-166
If You Specify...
The Function...
true
false
Note Usually it is not necessary to resolve the path of every file in the
project build information, because the makefile for the project build
will resolve file locations based on source paths and rules. Therefore,
specifying true for concatenatePaths returns the path for each file only
if a path was explicitly associated with the file when it was added, or if
you called updateFilePathsAndExtensions to resolve file paths and
extensions before calling getSourceFiles.
replaceMatlabroot
The Function...
true
false
includeGroups (optional)
6-167
getSourcePaths
Purpose. Source paths from projects build information
Syntax.
files=getSourcePaths(buildinfo, replaceMatlabroot,
includeGroups, excludeGroups)
includeGroups and excludeGroups are optional.
Input Arguments.
buildinfo
The Function...
true
false
includeGroups (optional)
6-168
updateFilePathsAndExtensions
Purpose. Update files in projects build information with missing paths
and file extensions
Syntax.
updateFilePathsAndExtensions(buildinfo, extensions)
extensions is optional.
Arguments.
buildinfo
A cell array of character arrays that specifies the extensions (file types)
of files for which to search and include in the update processing. By
default, the function searches for files with a .c extension. The function
checks files and updates paths and extensions based on the order in
which you list the extensions in the cell array. For example, if you
specify {'.c' '.cpp'} and a folder contains myfile.c and myfile.cpp,
an instance of myfile would be updated to myfile.c.
Description. Using paths that already exist in a projects build information,
the updateFilePathsAndExtensions function checks whether any file
references in the build information need to be updated with a path or file
extension. This function can be particularly useful for
6-169
Maintaining build information for a toolchain that requires the use of file
extensions
Updating multiple customized instances of build information for a given
project
updateFileSeparator
Purpose. Change file separator used in projects build information
Syntax.
updateFileSeparator(buildinfo, separator)
Arguments.
buildinfo
6-170
the RTW.BuildInfo object in the variable buildInfo. You can program the
command as a script or a function.
If You Program the Command as
a...
Then the...
Script
Function
6-171
6-172
cfg = coder.config('lib');
cfg.PostCodeGenCommand = 'FunctionName(projectName,
buildInfo)';
configuration object to codegen. For example, for the function foo that has
no input parameters:
codegen -config cfg foo
6-173
Report Generation
If MATLAB Coder detects errors or warnings, the software automatically
produces a code generation report.
Even when there are no errors or warnings, you can also use the option to
request reports.
The report provides links to your MATLAB code and C/C++ code files. It also
provides compile-time type information for the variables and expressions
in your MATLAB code. This information simplifies finding sources of error
messages and aids understanding of type propagation rules.
6-174
Note The default output folder is codegen, but you can specify a different
folder. For more information, see Specifying Output File Locations on page
3-34.
6-175
6-176
MATLAB code information, including a list of all functions and their build
status
Call stack information, providing information on the nesting of function
calls
Links to generated C/C++ code files
Summary of build results, including type of target and number of warnings
or errors
List of all error and warning messages
List of all variables in your MATLAB code
Target build log that records compilation and linking activities
If you want the code generation or error report to open automatically when
MATLAB Coder finishes building a project, check Automatically launch
a report if one is generated.
If you want the code generation or error report to open automatically, use the
-launchreport option instead of the -report option.
6-177
Errors in function.
Warnings in function.
Successful build, no errors or warnings.
A filter control. You can use Filter function list by attributes to sort
your functions by:
Size
Complexity
Class
Viewing Subfunctions
The code generation report annotates the subfunction with the name of the
parent function in the list of functions on the MATLAB code tab.
For example, if the MATLAB function fcn1 contains the subfunction subfcn,
and fcn2 contains the subfunction subfcn2, the report displays:
fcn1 > subfcn1
fcn2 > subfcn2
Viewing Specializations
If your MATLAB function calls the same function with different types of
inputs, the code generation report numbers each of these specializations
in the list of functions on the MATLAB code tab.
6-178
For example, if the function fcn calls the function subfcn with different
types of inputs:
function y = fcn(u) %#codegen
% Specializations
y = y + subfcn(single(u));
y = y + subfcn(double(u));
The code generation report numbers the specializations in the list of functions:
fcn > subfcn > 1
fcn > subfcn > 2
6-179
Entry-point functions
6-180
6-181
warnings are related to the first message. If the build produces warnings, but
no errors, MATLAB Coder does generate code.
The code generation report provides information about errors and warnings
by:
Listing all errors and warnings on the All Messages tab. The report lists
these messages in chronological order.
Highlighting all errors and warnings on the MATLAB code pane.
If applicable, recording compilation and linking issues on the Target
Build Log tab. If compilation or linking errors occur, the code generation
report opens with the Target Build Log tab selected so that you can view
the build log.
6-182
6-183
Class
DataTypeMode (DT mode) for fixed-point data types only. For
more information, see DataTypeMode in the Fixed-Point Toolbox
documentation.
Signed sign information for built-in data types, signedness information
for fixed-point data types
Word length (WL) for fixed-point data types only
Fraction length (FL) for fixed-point data types only
Note For more information on viewing fixed-point data types, see Working
with Fixed-Point Code Generation Reports in the Fixed-Point Toolbox
documentation.
It only displays a column if at least one variable in the code has information
in that column. For example, if the code does not contain any fixed-point data
types, the report does not display the DT mode, WL or FL columns.
Sorting Variables in the Variables Tab. By default, the report lists the
variables in the order that they appear in the selected function.
You can sort the variables by clicking the column headings on the Variables
tab. To sort the variables by multiple columns, hold down the Shift key when
clicking the column headings.
To restore the list to the original order, click the Order column heading.
Viewing Structures on the Variables Tab. You can expand structures
listed on the Variables tab to display the field properties.
6-184
If you sort the variables by type, size, complexity or class, a structure and its
fields might not appear sequentially in the list. To restore the list to the
original order, click the Order column heading.
Viewing Information About Variable-Size Arrays in the Variables
Tab. For variable-size arrays, the Size field includes information on the
computed maximum size of the array. The size of each array dimension that
varies is prefixed with a colon :.
In the following report, variable A is variable-size. Its maximum computed
size is 1100.
6-185
If you declare 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 do not change during execution.
For more information on how to use the size information for variable-sized
arrays, see How Working with Variable-Size Data Is Different for Code
Generation in the Code Generation from MATLAB documentation.
Viewing Renamed Variables in the Variables Tab. If your MATLAB
function reuses a variable with different size, type, or complexity, whenever
possible, the code generation software creates separate, uniquely named
variables in the generated code. For more information, see Reusing the Same
Variable with Different Properties in the Code Generation from MATLAB
documentation. The report numbers the renamed variables in the list on the
Variables tab. When you place your pointer over a renamed variable, the
report highlights only the instances of this variable that share the same data
type, size, and complexity.
For example, suppose your code uses the variable t in a for-loop to hold a
scalar double, and reuses it outside the for-loop to hold a 5x5 matrix. The
report displays two variables, t>1 and t>2 in the list on the Variables tab.
6-186
For variable-size arrays, the Size field includes information on the computed
maximum size of the array. The size of each array dimension that varies is
prefixed with a colon :. Here the array A is variable-sized with a maximum
computed size of 1 x 100.
6-187
6-188
6-189
Use...
Ctrl+m
Ctrl+k
C code Tab
Ctrl+c
Code Pane
Ctrl+w
Summary Tab
Ctrl+s
Ctrl+a
Variables Tab
Ctrl+v
Ctrl+t
Report Limitations
The report displays information about the variables and expressions in your
MATLAB code with the following limitations:
varargin and varargout
The report does not support varargin and varargout arrays.
Loop Unrolling
The report does not display the correct information for unrolled loops.
Dead Code
The report does not display information about any dead code.
Structures
The report does not provide complete information about structures.
6-190
On the MATLAB code pane, the report does not provide information about
all structure fields in the struct() constructor.
On the MATLAB code pane, if a structure has a nonscalar field, and an
expression accesses an element of this field, the report does not provide
information for the field.
Column Headings on Variables Tab
If you scroll through the list of variables, the report does not display the
column headings on the Variables tab.
Multiline Matrices
On the MATLAB code pane, the report does not support selection of
multiline matrices. It supports only selection of individual lines at a time.
For example, if you place your pointer over the following matrix, you cannot
select the entire matrix.
out1 = [1 2 3;
4 5 6];
6-191
6-192
7
Accelerating MATLAB
Algorithms
Workflow for Accelerating MATLAB Algorithms on page 7-2
How to Accelerate MATLAB Algorithms on page 7-4
Modifying MATLAB Code for Acceleration on page 7-5
Speeding Up MATLAB Algorithms with the Basic Linear Algebra
Subprograms (BLAS) Library on page 7-11
Controlling Run-Time Checks on page 7-14
Accelerating Simulation of Bouncing Balls on page 7-17
7-2
See Also
Chapter 3, Setting Up a MATLAB Coder Project
Chapter 4, Preparing MATLAB Code for C/C++ Code Generation
Chapter 5, Testing MEX Functions in MATLAB
Modifying MATLAB Code for Acceleration on page 7-5
Code Acceleration and Code Generation from MATLAB for Fixed-Point
Algorithms in the Fixed-Point Toolbox documentation
7-3
7-4
Unrolling for-loops
Unrolling for-loops eliminates the loop logic by creating a separate copy of
the loop body in the generated code for each iteration. Within each iteration,
the loop index variable becomes a constant. By unrolling short loops with
known bounds at compile time, MATLAB generates highly optimized code
with no branches.
You can also force loop unrolling for individual functions by wrapping the loop
header in a coder.unroll function. For more information, see coder.unroll.
7-5
7-6
}
/* Loop body begins */
y[2] = m_rand();
y[4] = m_rand();
/* Loop body ends */
}
The generated C code for getrand(50) does not unroll the for-loop because
the number of iterations is greater than 10:
static void m_b_getrand(real_T y[50])
{
int32_T i;
for(i = 0; i < 50; i++) {
y[i] = 0.0;
}
/* Loop body begins */
for(i = 0; i < 50; i += 2) {
if((i + 1 > 2) && (i + 1 < 48)) {
y[i] = m_rand();
}
}
/* Loop body ends */
}
Inlining Code
MATLAB uses internal heuristics to determine whether or not to inline
functions in the generated code. You can use the coder.inline directive to
fine-tune these heuristics for individual functions. For more information,
see coder.inline.
7-7
7-8
MATLAB generates code that passes the inputs by value and returns the
value of the output:
...
/* Function Definitions */
real_T foo2(real_T A, real_T B)
{
return A * B;
}
...
In some cases, the output of the function cannot be a modified version of its
inputs. If you do not use the inputs later in the function, you can modify
your code to operate on the inputs instead of on a copy of the inputs. One
method is to create additional return values for the function. For example,
consider the code:
function y1=foo(u1) %#codegen
7-9
x1=u1+1;
y1=bar(x1);
end
function y2=bar(u2)
% Since foo does not use x1 later in the function,
% it would be optimal to do this operation in place
x2=u2.*2;
% The change in dimensions in the following code
% means that it cannot be done in place
y2=[x2,x2];
end
You can modify this code to eliminate redundant copies. The changes are
highlighted in bold.
function y1=foo(u1) %#codegen
u1=u1+1;
[y1, u1]=bar(u1);
end
function [y2, u2]=bar(u2)
u2=u2.*2;
% The change in dimensions in the following code
% still means that it cannot be done in place
y2=[u2,u2];
end
7-10
Speeding Up MATLAB Algorithms with the Basic Linear Algebra Subprograms (BLAS) Library
7-11
To run a demo showing you how to do this, see Replacing Math Functions
and Operators.
Note Requires an Embedded Coder license.
See Also
Code Replacement in the Embedded Coder documentation.
7-12
Speeding Up MATLAB Algorithms with the Basic Linear Algebra Subprograms (BLAS) Library
mexcfg = coder.config('mex');
2 Disable the BLAS option.
mexcfg.EnableBLAS = false;
mexcfg = coder.config('mex');
2 Open the Automatic C MEX Generation dialog box:
open mexcfg
3 On the dialog box General tab, clear Enable BLAS library if possible
Supported Compilers
MATLAB Coder uses the BLAS library on all C/C++ compilers except:
Watcom
Intel
Borland
The default MATLAB compiler for Windows 32bit platforms, lcc, supports
the BLAS library, but it is not designed to generate high performance code. To
install a different C/C++ compiler, use the mex -setup command, as described
in Building MEX-Files in the MATLAB External Interfaces documentation.
7-13
7-14
Only if...
Responsiveness checks
Extrinsic calls
7-15
mexcfg = coder.config('mex');
2 At the command line, set the IntegrityChecks, ExtrinsicCalls, or
mexcfg = coder.config('mex');
2 Open the Automatic C MEX Generation dialog box:
open mexcfg
3 On the dialog box General tab, clear Ensure memory integrity, Ensure
7-16
To run this demo, you must install a C compiler and set it up using the mex
-setup command. For more information, see Setting Up Your C Compiler.
Create a New Folder and Copy Relevant Files
The following code will create a folder in your current working folder (pwd).
The new folder will contain only the files that are relevant for this example. If
you do not want to affect the current folder (or if you cannot generate files in
this folder), change your working folder.
Run Command: Create a New Folder and Copy Relevant Files
coderdemo_setup('coderdemo_bouncing_balls');
About the run_balls Function
% balls = run_balls(n)
% Given 'n' number of balls, run a simulation until the balls come to a
% complete halt (or when the system has no more kinetic energy).
function balls = run_balls(n) %#codegen
%
7-17
% The seed will guarantee that we get the precisely same simulation
% every time we call this function.
rand('seed', 1283);
First, generate a MEX function using the command codegen followed by the
name of the MATLAB file to compile. Pass an example input (-args 0) to
indicate that the generated MEX function will be called with an input of
type double.
codegen run_balls -args 0
The run_balls function calls other MATLAB functions, but you need to
specify only the entry-point function when calling codegen.
7-18
Run and time the original run_balls function followed by the generated MEX
function.
tic, run_balls(50); t1 = toc;
tic, run_balls_mex(50); t2 = toc;
7-19
cleanup
7-20
8
Calling C/C++ Functions
from Generated Code
MATLAB Coder Interface to C/C++ Code on page 8-2
Calling External C/C++ Functions on page 8-7
Returning Multiple Values from C Functions on page 8-9
How MATLAB Coder Infers C/C++ Data Types on page 8-10
8-2
8-3
Do not store pointers that you pass to C/C++ functions because MATLAB
Coder optimizes the code based on the assumption that you do not store the
addresses of these variables. Storing the addresses might invalidate our
optimizations leading to incorrect behavior. For example, if a MATLAB
function passes a pointer to an array using coder.ref, coder.rref, or
coder.wref, then the C/C++ function can modify the data in the arraybut
you should not store the pointer for future use.
When you pass arguments by reference using coder.rref, coder.wref, and
coder.ref, the corresponding C/C++ function signature must declare these
variables as pointers of the same data type. Otherwise, the C/C++ compiler
generates a type mismatch error.
For example, suppose your MATLAB function calls an external C function
ctest:
function y = fcn()
u = pi;
y = 0;
y = coder.ceval('ctest',u);
When you compile the code, you get a type mismatch error because
coder.ceval calls ctest with an argument of type double when ctest
expects a pointer to a double-precision, floating-point value.
Match the types of arguments in coder.ceval with their counterparts in the
C function. For instance, you can fix the error in the previous example by
passing the argument by reference:
y = coder.ceval('ctest', coder.rref(u));
You can pass a reference to an element of a matrix. For example, to pass the
second element of the matrix v, you can use the following code:
y = coder.ceval('ctest', coder.ref(v(1,2));
8-4
Declaring Data
The construct coder.opaque allows you to manipulate C/C++ data that a
MATLAB function does not recognize. You can store the opaque data in a
variable or structure field and pass it to, or return it from, a C/C++ function
using coder.ceval.
8-5
y = [x char(0)];
% Remove all character 13 (CR) but keep character 10 (LF)
function buffer = strip_cr(buffer)
j = 1;
for i = 1:numel(buffer)
if buffer(i) ~= char(13)
buffer(j) = buffer(i);
j = j + 1;
end
end
buffer(i) = 0;
8-6
The header file defines the data types used by the C/C++ functions that
MATLAB Coder generates in code, as described in Mapping MATLAB
Types to C/C++ on page 8-10.
Tip One way to add these type definitions is to include the header file
tmwtypes.h, which defines all general data types supported by MATLAB.
This header file is in matlabroot/extern/include. Check the definitions
in tmwtypes.h to determine if they are compatible with your target. If not,
define these types in your own header files.
3 In your MATLAB function, add calls to coder.ceval to invoke your
8-7
This step ensures that you catch type mismatches between C/C++ and
MATLAB (see How MATLAB Coder Infers C/C++ Data Types on page
8-10).
6 Generate code and fix errors.
7 Run your application.
8-8
If you rewrite foo as a C function, you cannot return a, b, and c through the
return statement. You can create a C function with multiple pointer type
input arguments, and pass the output parameters by reference. For example:
foo(real_T x, real_T y, real_T *a, real_T *b, real_T *c)
Then you can call the C function with multiple outputs from a MATLAB
function using coder.wref constructs:
coder.ceval ('foo', x, y, ...
coder.wref(a), coder.wref(b), coder.wref(c));
Similarly, suppose that one of the outputs a is also an input argument. In this
case, create a C function with multiple pointer type input arguments, and
pass the output parameters by reference. For example:
foo(real_T *a, real_T *b, real_T *c)
Then call the C function from a MATLAB function using coder.wref and
coder.rref constructs:
coder.ceval ('foo', coder.ref(a), coder.wref(b), coder.wref(c));
8-9
8-10
MATLAB Type
C/C++ Type
C/C++ Reference
Type
int8
int8_T
int8_T *
int16
int16_T
int16_T *
int32
int32_T
int32_T *
uint8
uint8_T
uint8_T *
uint16
uint16_T
uint16_T *
uint32
uint32_T
uint32_T *
double
real_T
real_T *
single
real32_T
real32_T *
MATLAB Type
C/C++ Type
C/C++ Reference
Type
char
char
char *
logical
boolean_T
boolean_T *
fi
struct
complex
function handles
Not supported.
The MATLAB for code generation integer type is the next larger target word
size that can store the fixed-point value, based on its word length. The sign of
the integer type matches the sign of the fixed-point type.
embedded.numerictype
C/C++ Type
C/C++ Reference
Type
int16_T
int16_T *
int16_T
int16_T *
uint32_T
uint32_T *
numerictype(1, 8, 7)
int8_T
int8_T *
8-11
C/C++ Type
C/C++ Reference
Type
zeros(10, 5, 'int8')
int8_T *
int8_T *
int8_T *
int8_T *
zeros(3, 7)
real_T *
real_T *
zeros(10, 1, 'single')
real32_T *
real32_T *
8-12
Complex
C/C++ Type
C/C++ Reference
Type
complex int8
cint8_T
cint8_T *
complex int16
cint16_T
cint16_T *
complex int32
cint32_T
cint32_T *
complex uint8
cuint8_T
cuint8_T *
complex uint16
cuint16_T
cuint16_T *
complex uint32
cuint32_T
cuint32_T *
complex double
creal_T
creal_T *
complex single
creal32_T
creal32_T *
The MATLAB Coder software defines each complex value as a structure with
a real component re and an imaginary component im, as in this example
from tmwtypes.h:
typedef struct {
real32_T re;/* Real component*/
real32_T im;/* Imaginary component*/
} creal32_T;
MATLAB Coder uses the names re and im in generated code to represent the
components of complex numbers. For example, suppose you define a variable
x of type creal32_T. The generated code references the real component as
x.re and the imaginary component as x.im.
If your C/C++ library requires a different representation, you can define
your own versions of MATLAB Coder complex types, but you must use the
names re for the real components and im for the imaginary components in
your definitions.
The MATLAB Coder software represents a matrix of complex numbers as
an array of structures.
8-13
string' 0]. A single character translates to a C/C++ char type, not a C/C++
string.
Caution Failing to null-terminate your MATLAB strings might cause C/C++
code to crash without compiler errors or warnings.
8-14
A
Examples
Use this list to find examples in the documentation.
Examples
Specifying Inputs
Example: Specifying a Structure as a Constant Input on page 6-38
Example: Specifying a Variable-Size Vector Input on page 6-39
Example: Specifying Properties of Primary Inputs by Example at the
Command Line on page 6-40
Example: Specifying Properties of Primary Fixed-Point Inputs by
Example at the Command Line on page 6-41
Example: Specifying Class and Size of Scalar Structure on page 6-49
Example: Specifying Class and Size of Structure Array on page 6-50
A-2
A-3
A-4
Examples
Index
C
Index
MATLAB
debugging run-time errors 5-5
MATLAB code analyzer
using with MATLAB for code generation 4-4
MATLAB Coder
combining property specifications 6-48
controlling run-time checks 7-14
eliminating redundant copies of function
inputs 6-67 7-8
how to disable run-time checks 7-15
inlining functions 6-66 7-7
specifying build configuration
parameters 6-22
specifying general properties of primary
inputs 6-48
when to disable run-time checks 7-15
MATLAB for code generation
using the MATLAB code analyzer 4-4
readability
codegen 6-181
MATLAB Coder 6-88
S
specifying build configuration parameters
codegen 6-23
MATLAB Coder 6-22
Index-1
Index
codegen 6-181
MATLAB Coder 6-88
traceability
codegen 6-181
MATLAB Coder 6-88
validating code
Index-2