Generate C Code by Using the MATLAB Coder App
In this tutorial, you use the MATLAB® Coder™ app to generate a static C library for a MATLAB function. You first generate C code that can accept only inputs that have fixed preassigned size. You then generate C code that can accept inputs of many different sizes.
Coder app is not supported in MATLAB
Online™. To generate C/C++ code in MATLAB
Online, use the
Copy the tutorial files from the folder
to a local working folder. Here,
is the MATLAB installation folder, for example,
Files\MATLAB\R2019a. To copy these files to your current folder, run
The MATLAB data file
euclidean_data.matcontains two pieces of data: a single point in three-dimensional Euclidean space and a set of several other points in three-dimensional Euclidean space. More specifically:
1column vector that represents a point in three-dimensional Euclidean space.
216array. Each column in
cbrepresents a point in three-dimensional Euclidean space.
The MATLAB file
euclidean.mcontains the function
euclideanthat implements the core algorithm in this example. The function takes
cbas inputs. It calculates the Euclidean distance between
xand each point in
cband returns these quantities:
The column vector
y_min, which is equal to the column in
cbthat represents the point that is closest to
The column vector
y_max, which is equal to the column in
cbthat represents the point that is farthest from
The 2-dimensional vector
idxthat contains the column indices of the vectors
The 2-dimensional vector
distancethat contains the calculated smallest and largest distances to
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
test.mloads the data file
euclidean_data.matinto the workspace. It then calls the function
distance. The script then displays the calculated quantities at the command line.
euclidean_data.matis 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))]);
You can generate code from MATLAB functions by using MATLAB Coder. Code generation from MATLAB scripts is not supported.
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
Run the Original MATLAB Code
Run the test script
test.m in MATLAB. The output displays
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
Make the MATLAB Code Suitable 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.
euclidean.min 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
function [y,idx,distance] = euclidean(x,cb) %#codegen
%#codegendirective prompts the Code Analyzer to identify warnings and errors specific to code generation.
The Code Analyzer message indicator becomes red, indicating that it has detected code generation issues.
To view the warning messages, move your cursor to the underlined code fragments. The warnings indicate that code generation requires the variables
distanceto be fully defined before subscripting them. These warnings appear because the code generator must determine the sizes of these variables at their first appearance in the code. To fix this issue, use the
onesfunction to simultaneously allocate and initialize these arrays.
% Initialize minimum distance as distance to first element of cb % Initialize maximum distance as distance to first element of cb idx = ones(1,2); distance = ones(1,2)*norm(x-cb(:,1));
The Code Analyzer message indicator becomes green again, indicating that it does not detect any 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. Here, compilation refers to the generation of C/C++ code from your MATLAB code.
Compilation of MATLAB code refers to the generation of C/C++ code from the MATLAB code. In other contexts, the term compilation could refer to the action of a C/C++ compiler.
Open the MATLAB Coder App and Select Source Files
On the MATLAB toolstrip Apps tab, under Code Generation, click the MATLAB Coder app icon. The app opens the Select Source Files page.
In the Select Source Files page, enter or select the name of the entry-point function
euclidean. An entry-point function is a top-level MATLAB function from which you generate code. The app creates a project with the default name
euclidean.prjin the current folder.
Click Next to go to the Define Input Types step. The app runs the Code Analyzer (that you already ran in the previous step) and the Code Generation Readiness Tool on the entry-point function. The Code Generation Readiness Tool screens the MATLAB code for features and functions that are not supported for code generation. If the app identifies issues, it opens the Review Code Generation Readiness page where you can review and fix issues. In this example, because the app does not detect issues, it opens the Define Input Types page. For more information, see Code Generation Readiness Tool.
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 built-in functions and toolbox functions, classes, and System objects that are supported for C/C++ code generation have specific code generation limitations. These limitations and related usage notes are listed 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 uses static typing, the code generator must determine the class, size, and complexity of all 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.
Specify properties directly.
In this example, to define the properties of the inputs
cb, specify the test file
test.m that the code generator can use to define types automatically:
Enter or select the test file
Click Autodefine Input Types.
The test file,
test.m, calls the entry-point function,
euclidean, with the expected input types. The app determines that the input
double(3x1)and the input
Click Next to go to the Check for Run-Time Issues step.
Check for Run-Time Issues
The Check for Run-Time Issues step generates a MEX file from your entry-point functions, runs the MEX function, and reports issues. 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 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.
To convert MATLAB code to efficient C/C++ source code, the code generator introduces optimizations that, in certain situations, cause the generated code to behave differently than the original source code. See Differences Between Generated Code and MATLAB Code.
To open the Check for Run-Time Issues dialog box, click the Check for Issues arrow .
In the Check for Run-Time Issues dialog box, specify a test file or enter code that calls the entry-point function with example inputs. For this example, use the test file
testthat you used to define the input types.
Click Check for Issues.
The app generates a MEX function. It runs the test script
testreplacing calls to
euclideanwith calls to the generated MEX. If the app detects issues during the MEX function generation or execution, it provides warning and error messages. Click these messages to navigate to the problematic code and fix the issue. In this example, the app does not detect issues.
By default, the app collects line execution counts. These counts help you to see how well the test file
euclideanfunction. To view line execution counts, click View MATLAB line execution counts. The app editor displays a color-coded bar to the left of the code. To extend the color highlighting over the code and to see line execution counts, place your cursor over the bar.
A particular shade of green indicates that the line execution count for this code falls in a certain range. In this case, the
for-loop executes 215 times. For information about how to interpret line execution counts and turn off collection of the counts, see Collect and View Line Execution Counts for Your MATLAB Code.
Click Next to go to the Generate Code step.
Before generating standalone C/C++ code from your MATLAB code, generate a MEX function. 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 Code
To open the Generate dialog box, click the Generate arrow .
In the Generate dialog box, set Build type to
Static Library (.lib)and Language to C. Use the default values for the other project build configuration settings.
Instead of generating a C static library, you can choose to generate a MEX function or other C/C++ build types. Different project 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.
MATLAB Coder generates a standalone C static library
is the folder that contains your tutorial files. The MATLAB Coder app indicates that code generation succeeded. It displays the source MATLAB files and generated output files on the left side of the page. On the Variables tab, it displays information about the MATLAB source variables. On the Target Build Log tab, it displays the build log, including C/C++ compiler warnings and errors. By default, in the code window, the app displays the C source code file,
euclidean.c. To view a different file, in the Source Code or Output Files pane, click the file name.
Click View 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.
Click Next to open the Finish Workflow page.
Review the Finish Workflow Page
The Finish Workflow page indicates that code generation succeeded. It provides a project summary and links to generated output.
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.
Important information about the generated C code:
The function signature is:
void euclidean(const double x, const double cb, double y_min, double y_max, double idx, double distance)
const double xcorresponds to the input
xin your MATLAB code. The size of
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 cbcorresponds to the input
cbin your MATLAB code. The size of
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
distance. These arrays are used to return the output values. They correspond to the output arguments
distancein the original MATLAB code.
The code generator preserves your function name and comments. When possible, the code generator preserves your variable names.
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 that you generated for
euclidean.m 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. In
this part of the tutorial, you generate C code from
that accepts variable-size inputs.
Suppose that you want the dimensions of
cb in the generated C code to have these properties:
The first dimension of both
cbcan vary in size up to
The second dimension of
xis fixed and has the value
The second dimension of
cbcan vary in size up to
To specify these input properties:
In the Define Input Types step, enter the test file
test.mand click Autodefine Input Types as before. The test file calls the entry-point function,
euclidean.m, with the expected input types. The app determines that the input
double(3x1)and the input
double(3x216). These types specify fixed-size inputs.
Click the input type specifications and edit them. You can specify variable size, up to a specified limit, by using the
:prefix. For example,
:3implies that the corresponding dimension can vary in size up to
3. Change the types to
double(:3 x 1)for
double(:3 x :216)for
You can now generate code by following the same steps as before. The function
signature for the generated C code in
void euclidean(const double x_data, const int x_size, const double cb_data, const int cb_size, double y_min_data, int y_min_size, double y_max_data, int y_max_size, double idx, double distance)
y_max_datacorrespond to the input arguments
cband the output arguments
y_maxin the original MATLAB function. The C function now accepts four additional input arguments
y_max_sizethat specify the sizes of
y_max_dataat run time.
Learn about code generation support for MATLAB built-in functions and toolbox functions, classes, and System objects
Generate C++ code
Generate and modify an example C main function and use it to build a C executable program
Package generated files into a compressed file
Optimize the execution speed or memory usage of generated code
Integrate your custom C/C++ code into the generated code
Learn about the code generation report
Interactively Trace Between MATLAB Code and Generated C/C++ Code (Embedded Coder)