Generate C Code by Using the MATLAB Coder App
In this tutorial, you use the MATLAB® Coder™ app to generate C source code for a MATLAB function. You first generate C code that can accept only inputs that have a fixed, preassigned size. You then generate C code that can accept inputs of many different sizes.
You can also generate code at the MATLAB command line by using the codegen
command. For a tutorial, see Generate C Code at the Command Line.
MATLAB Coder generates code from MATLAB functions, not scripts. If your MATLAB code is in the form of a script, create a wrapper function around the script before generating code.
Tutorial Files: Euclidean Distance
Open this example to obtain the files for this tutorial.
Description of Tutorial Files
This tutorial uses the euclidean_data.mat
,
euclidean.m
, and euclidean_test.m
files.
The MATLAB data file
euclidean_data.mat
contains two pieces of data:x
is a3
-by-1
column vector that represents a point in three-dimensional Euclidean space.cb
is a3
-by-216
array. Each column incb
represents a point in three-dimensional Euclidean space.
The MATLAB file
euclidean.m
contains the functioneuclidean
, which implements the core algorithm in this example. The function takesx
andcb
as inputs, calculates the Euclidean distance betweenx
and each point incb
, and returns these quantities:The column vector
y_min
, which is equal to the column incb
that represents the point that is closest tox
.The column vector
y_max
, which is equal to the column incb
that represents the point that is farthest fromx
.The two-dimensional vector
idx
, which contains the column indices of the vectorsy_min
andy_max
incb
.The two-dimensional vector
distance
, which contains the calculated smallest and largest distances tox
.
function [y_min,y_max,idx,distance] = euclidean(x,cb) % Initialize minimum distance as distance to first element of cb % Initialize maximum distance as distance to first element of cb idx(1)=1; idx(2)=1; distance(1)=norm(x-cb(:,1)); distance(2)=norm(x-cb(:,1)); % Find the vector in cb with minimum distance to x % Find the vector in cb with maximum distance to x for index=2:size(cb,2) d=norm(x-cb(:,index)); if d < distance(1) distance(1)=d; idx(1)=index; end if d > distance(2) distance(2)=d; idx(2)=index; end end % Output the minimum and maximum distance vectors y_min=cb(:,idx(1)); y_max=cb(:,idx(2)); end
The MATLAB script
euclidean_test.m
loads the data fileeuclidean_data.mat
into the workspace. It then calls the functioneuclidean
to calculatey_min
,y_max
,idx
, anddistance
. The script then displays the calculated quantities at the command line.Loading
euclidean_data.mat
is the preprocessing step that is executed before calling the core algorithm. Displaying the results is the post-processing step.% Load test data load euclidean_data.mat % Determine closest and farthest points and corresponding distances [y_min,y_max,idx,distance] = euclidean(x,cb); % Display output for the closest point disp('Coordinates of the closest point are: '); disp(num2str(y_min')); disp(['Index of the closest point is ', num2str(idx(1))]); disp(['Distance to the closest point is ', num2str(distance(1))]); disp(newline); % Display output for the farthest point disp('Coordinates of the farthest point are: '); disp(num2str(y_max')); disp(['Index of the farthest point is ', num2str(idx(2))]); disp(['Distance to the farthest point is ', num2str(distance(2))]);
Tip
Use test scripts to separate the pre- and post-processing steps from the function implementing the core algorithm. This practice enables you to easily reuse your algorithm. You generate code for the MATLAB function that implements the core algorithm. You do not generate code for the test script.
Generate C Code for the MATLAB Function
Use the MATLAB
Coder app to generate C source code for the function
euclidean
. The code you generate in this step accepts only
inputs that have a fixed, preassigned size.
Run the Original MATLAB Code
Run the test script euclidean_test.m
. The output displays
y
, idx
, and
distance
.
Coordinates of the closest point are: 0.8 0.8 0.4 Index of the closest point is 171 Distance to the closest point is 0.080374 Coordinates of the farthest point are: 0 0 1 Index of the farthest point is 6 Distance to the farthest point is 1.2923
Prepare MATLAB Code for Code Generation
The Code Analyzer in the MATLAB Editor continuously checks your code as you enter it. It reports issues and recommends modifications to maximize performance and maintainability.
Open
euclidean.m
in the MATLAB Editor. The Code Analyzer message indicator in the top right corner of the MATLAB Editor is green. The analyzer did not detect errors, warnings, or opportunities for improvement in the code.After the function declaration, add the
%#codegen
directive:Thefunction [y,idx,distance] = euclidean(x,cb) %#codegen
%#codegen
directive prompts the Code Analyzer to identify warnings and errors specific to code generation.The Code Analyzer message indicator becomes red, indicating that it detected code generation issues.
To view the warning messages, point to the underlined code fragments. The warnings indicate that code generation requires the variables
idx
anddistance
to be fully defined before subscripting them. These warnings appear because the code generator determines the sizes of variables at their first appearance in the code. To fix this issue, use theones
function to simultaneously allocate and initialize these arrays.idx = ones(1,2); distance = ones(1,2)*norm(x-cb(:,1));
The Code Analyzer displays the No errors found icon, indicating that it does not detect more code generation issues.
For more information about using the Code Analyzer, see Check Code for Errors and Warnings Using the Code Analyzer.
Save the file.
You are now ready to compile your code by using the MATLAB Coder app.
Note
In MATLAB Coder, compilation of MATLAB code refers to the generation of C/C++ code from the MATLAB code. In other contexts, the term compilation refers to the action of a C/C++ compiler.
Open the MATLAB Coder App and Create a Project File
To generate code using the MATLAB
Coder app, you must first create a MATLAB
Coder project file that has the extension .coderprj
.
This file contains the information that you provide to the code generator,
including the paths of the MATLAB
Coder entry-point functions, their input types, global variables, and
the code generation configuration parameters.
In the MATLAB Toolstrip, in the Apps tab, under Code Generation, click MATLAB Coder. The app opens the Create MATLAB Coder Project dialog box.
Provide the name of the project file and the folder in which you want to place the file. For this example, create a file named
euclidean.coderprj
in your current working folder.
The MATLAB Coder toolstrip tab opens. In the tab, each section corresponds to the different steps you perform when generating code, including preparing your MATLAB code for C/C++ code generation, generating code, performing verification on generated code, viewing the code generation report, and exporting the generated code.
The MATLAB Coder panel also opens. The Next Steps section displays messages to guide you thorough the code generation steps, and Input and Output section summarize the code generation inputs and outputs.
Specify MATLAB Entry-Point Functions
An entry-point function is a top-level MATLAB function from which you generate code. For this example, your
entry-point function is euclidean
.
The Next Steps section of the MATLAB Coder panel indicates that you must add an entry-point to the empty project.
To add an entry-point function:
Either click the Add Entry Points button in the Inputs section of the MATLAB Coder panel or the Entry Points button in the toolstrip.
The Entry Points tab opens. Enter the name of your entry-point function
euclidean
.
The app runs the Code Generation Readiness Tool on the entry-point function.
This tool screens the MATLAB code for features and functions that are not supported for code
generation. If the app identifies issues with an entry-point function or one of
its dependencies, it displays a warning message in the Entry
Points tab. Click the link next to the message to open the Code
Generation Readiness Tool in a separate window where you can review and fix the
issues. In this example, the app does not detect code generation readiness
issues in the euclidean
function. For more information, see
Code Generation Readiness Tool.
Note
The Code Analyzer and the Code Generation Readiness Tool might not detect all code generation issues. After eliminating the errors or warnings that these two tools detect, generate code with MATLAB Coder to determine if your MATLAB code has other compliance issues.
Certain MATLAB functions and objects that are supported for C/C++ code generation have specific code generation limitations. These limitations and related usage notes are in the Extended Capabilities sections of their corresponding reference pages. For more information, see Functions and Objects Supported for C/C++ Code Generation.
Define Input Types
Because C/C++ uses static typing, the code generator must determine the class, size, and other properties (such as complexity) of the variables in the MATLAB files at code generation time, also known as compile time. Therefore, you must specify the properties of all entry-point function inputs. To specify input properties, you can:
Instruct the app to automatically determine input properties by:
Providing a script that calls the entry-point functions with sample inputs.
Executing commands at the Command Window that exercise the entry-point functions with sample inputs.
Specify properties directly.
In this example, to define the properties of the inputs
x
and cb
, specify the test file
euclidean_test.m
that the code generator can use to
define types automatically.
In the top of the Entry Points tab, set the Automatically Define Input Types parameter to
Using Script
.Enter the test file
euclidean_test.m
and click the run button.
The test file, euclidean_test.m
, calls the entry-point
function, euclidean
, with the expected input types. The app
determines that the input x
is a double
3-by-1 array and the input cb
is a double
3-by-216 array.
Generate and Run MEX Function
The Run Generated MEX toolstrip button generates a MEX function from your entry-point functions, runs the MEX function, and reports issues. A MEX function is generated code that can be called from inside MATLAB. It is a best practice to perform this step because you can detect and fix run-time errors that are harder to diagnose in the generated standalone C/C++ code. By default, the MEX function includes memory integrity checks. These checks perform array bounds and dimension checking. The checks detect violations of memory integrity in code generated for MATLAB functions. For more information, see Control Run-Time Checks.
In the MATLAB Coder toolstrip tab, open the Run Generated MEX drop-down menu.
Specify a test file that calls the entry-point function with example inputs. For this example, use the test file
euclidean_test.m
that you used to define the input types.
The app generates a MEX function. It runs the test script
euclidean_test
replacing calls to
euclidean
with calls to the generated MEX. If the app
detects issues during the MEX function generation or execution, it provides
warning and error messages in the Command Window. Click these messages to
navigate to the problematic code and fix the issue. In this example, the app
does not detect issues and shows this message in the Output
section of the code generation panel.
Tip
Before generating standalone C/C++ code from your MATLAB code, generate a MEX function. In certain situations, the code generator might produce code that has different numerical behavior from MATLAB. Therefore, it is a best practice to run the generated MEX function and make sure it has the same run-time behavior as your MATLAB function. If the generated MEX function produces answers that are different from MATLAB, or produces an error, you must fix these issues before proceeding to standalone code generation. Otherwise, the standalone code that you generate might be unreliable and have undefined behavior.
Generate C Source Code
In the Prepare section of the MATLAB Coder tab of the toolstrip, make sure Output Type is set to Static Library (.lib). Use the default values for the other code configuration settings.
Click the Generate Code button in the toolstrip.
MATLAB Coder generates C source files for your project in the
folder, wherework
\codegen\lib\euclidean
is the folder that contains your tutorial files. The Output section indicates that code generation succeeds and displays links to the generated output folder and the code generation report.work
Click Code generation report to view the report in the Report Viewer. If the code generator detects errors or warnings during code generation, the report describes the issues and provides links to the problematic MATLAB code. For more information, see Code Generation Reports.
Clicking the Generate Code button generates source code only and does not build the source code to create binaries. To both generate source code and build binaries in a single step, open the Generate Code drop-down menu and select the Generate Code and Build option. Also, instead of generating a C static library, you can choose to generate a MEX function or other C/C++ build types. Different code configuration settings are available for the MEX and C/C++ build types. When you switch between MEX and C/C++ code generation, verify the settings that you choose.
To convert MATLAB code to efficient C/C++ code, the code generator introduces optimizations that, in certain situations, cause the generated code to behave differently than the original MATLAB code. See Differences Between Generated Code and MATLAB Code.
Compare the Generated C Code to Original MATLAB Code
To compare your generated C code to the original MATLAB code, open the C file, euclidean.c
, and the
euclidean.m
file in the MATLAB Editor.
In the euclidean.c
file, the signature of the generated
entry-point function
is:
void euclidean(const double x[3], const double cb[648], double y_min[3], double
y_max[3], double idx[2], double distance[2])
const double x[3]
corresponds to the input
x
in your MATLAB code. The size of x
is 3
,
which corresponds to the total size (3 x 1) of the example input that you used
when you generated code from your MATLAB code.
const double cb[648]
corresponds to the input
cb
in your MATLAB code. The size of cb
is 648
,
which corresponds to the total size (3 x 216) of the example input that you used
when you generated code from your MATLAB code. In this case, the generated code uses a one-dimensional
array to represent a two-dimensional array in the MATLAB code.
The generated code has four additional input arguments: the arrays
y_min
, y_max
, idx
,
and distance
. These arrays are used to return the output
values. They correspond to the output arguments y_min
,
y_max
, idx
, and
distance
in the original MATLAB code.
The code generator preserves your function name and comments. When possible, the code generator preserves your variable names.
Note
If a variable in your MATLAB code is set to a constant value, it does not appear as a variable in the generated C code. Instead, the generated C code contains the actual value of the variable.
With Embedded Coder®, you can interactively trace between MATLAB code and generated C/C++ code. See Interactively Trace Between MATLAB Code and Generated C/C++ Code (Embedded Coder).
Generate C Code for Variable-Size Inputs
The C function in euclidean.c
can accept only inputs that have
the same size as the sample inputs that you specified during code generation.
However, the input arrays to the corresponding MATLAB function can be of any size.
Suppose that you want the dimensions of x
and
cb
in the generated C code to have these properties:
The first dimension of both
x
andcb
can vary in size up to3
.The second dimension of
x
is fixed and has the value1
.The second dimension of
cb
can vary in size up to216
.
To specify these input properties:
In the Entry Points tab, enter the test file
euclidean_test.m
under Automatically Define Input Types and click the run button. The test file calls the entry-point function,euclidean
, with the expected input types. The app determines that the inputx
isdouble 3 x 1
and the inputcb
isdouble 3 x 216
. These types specify fixed-size inputs.Under the section for the
euclidean
function, in the third column, click the size specifications. A drop-down menu opens that you can use to edit the size of the inputs. You can specify variable size up to a specified limit, by using the:
prefix. For example,:3
implies that the corresponding dimension can vary in size up to3
. Change the types todouble :3 x 1
forx
anddouble :3 x :216
forcb
.
Generate code by following the same steps as before. The function signature for
the generated C code in euclidean.c
now
reads:
void euclidean(const double x_data[], const int x_size[1], const double cb_data[],
const int cb_size[2], double y_min_data[], int y_min_size[1],
double y_max_data[], int y_max_size[1], double idx[2], double
distance[2])
x_data
,
cb_data
, y_min_data
, and
y_max_data
correspond to the input arguments
x
and cb
and the output arguments
y_min
and y_max
in the original
MATLAB function. The C function now accepts four additional input arguments
x_size
, cb_size
,
y_min_size
, and y_max_size
that specify
the sizes of x_data
, cb_data
,
y_min_data
, and y_max_data
at run
time.See Also
Topics
- Functions and Objects Supported for C/C++ Code Generation
- C++ Code Generation
- Use an Example C Main in an Application
- Package Code for Other Development Environments
- Optimize Generated C/C++ and MEX Code
- Call Custom C/C++ Code from the Generated Code
- Code Generation Reports
- Interactively Trace Between MATLAB Code and Generated C/C++ Code (Embedded Coder)