| Contents | Index |
| On this page… |
|---|
Design Considerations When Writing MATLAB Code for Code Generation |
In this tutorial, you will learn how to:
Automatically generate a MEX function from your MATLAB code and use this MEX function to validate your algorithm in MATLAB before generating C code.
Automatically generate C code from your MATLAB code.
Define function input properties at the command line.
Specify variable-size inputs when generating code.
Specify code generation properties.
Generate a code generation report that you can use to debug your MATLAB code and verify that it is suitable for code generation.
To complete this tutorial, you should have basic familiarity with MATLAB software.
To complete this tutorial, you must install the following products:
MATLAB
MATLAB Coder
C compiler (for most platforms, a default C compiler is supplied with MATLAB)
For a list of supported compilers, see Supported Compilers.
You must set up the C compiler before generating C code. See Setting Up Your C Compiler.
For instructions on installing MathWorks products, see the MATLAB installation documentation for your platform. If you have installed MATLAB and want to check which other MathWorks products are installed, enter ver in the MATLAB Command Window.
This section describes the example used by the tutorial. You do not have to be familiar with the algorithm to complete the tutorial.
The example for this tutorial uses a Kalman filter to estimate the position of an object moving in a two-dimensional space from a series of noisy inputs based on past positions. The position vector has two components, x and y, indicating its horizontal and vertical coordinates.
Kalman filters have a wide range of applications, including control, signal and image processing; radar and sonar; and financial modeling. They are recursive filters that estimate the state of a linear dynamic system from a series of incomplete or noisy measurements. The Kalman filter algorithm relies on the state-space representation of filters and uses a set of variables stored in the state vector to characterize completely the behavior of the system. It updates the state vector linearly and recursively using a state transition matrix and a process noise estimate.
This section describes the algorithm of the Kalman filter and is implemented in the MATLAB version of the filter supplied with this tutorial.
The algorithm predicts the position of a moving object based on its past positions using a Kalman filter estimator. It estimates the present position by updating the Kalman state vector, which includes the position (x and y), velocity (Vx and Vy), and acceleration (Ax and Ay) of the moving object. The Kalman state vector, x_est, is a persistent variable.
% Initial conditions
persistent x_est p_est
if isempty(x_est)
x_est = zeros(6, 1);
p_est = zeros(6, 6);
endx_est is initialized to an empty 6x1 column vector and updated each time the filter is used.
The Kalman filter uses the laws of motion to estimate the new state:

These laws of motion are captured in the state transition matrix A, which is a matrix that contains the coefficient values of x, y, Vx, Vy, Ax, and Ay.
% Initialize state transition matrix
dt=1;
A=[ 1 0 dt 0 0 0;...
0 1 0 dt 0 0;...
0 0 1 0 dt 0;...
0 0 0 1 0 dt;...
0 0 0 0 1 0 ;...
0 0 0 0 0 1 ];The filtering process has two phases:
Predicted state and covariance
The Kalman filter uses the previously estimated state, x_est, to predict the current state, x_prd. The predicted state and covariance are calculated in:
% Predicted state and covariance x_prd = A * x_est; p_prd = A * p_est * A' + Q;
Estimation
The filter also uses the current measurement, z, and the predicted state, x_prd, to estimate a closer approximation of the current state. The estimated state and covariance are calculated in:
% Measurement matrix H = [ 1 0 0 0 0 0; 0 1 0 0 0 0 ]; Q = eye(6); R = 1000 * eye(2);
% Estimation S = H * p_prd' * H' + R; B = H * p_prd'; klm_gain = (S \ B)'; % Estimated state and covariance x_est = x_prd + klm_gain * (z - H * x_prd); p_est = p_prd - klm_gain * H * p_prd; % Compute the estimated measurements y = H * x_est;
Haykin, Simon. Adaptive Filter Theory. Upper Saddle River, NJ: Prentice-Hall, Inc., 1996.
The tutorial uses the following files:
Example MATLAB code files for each step of the tutorial.
Throughout this tutorial, you work with MATLAB files that contain a simple Kalman filter algorithm.
Build scripts that you use to compile your function code.
Test files that:
Perform the preprocessing functions.
Call the Kalman filter.
Perform the post-processing functions.
A MAT-file that contains input data.
The tutorial files are available in the following folder: docroot\toolbox\coder\examples\kalman. To run the tutorial, you must copy these files to a local folder. For instructions, see Copying Files Locally.
| Type | Name | Description |
|---|---|---|
| Function code | kalman01.m | Baseline MATLAB implementation of a scalar Kalman filter. |
| kalman02.m | Version of the original algorithm that is suitable for code generation. | |
| kalman03.m | Kalman filter suitable for use with frame-based and packet-based inputs. | |
| Build scripts | build01.m | Generates MEX function for the original Kalman filter. |
| build02.m | Generates C code for the original Kalman filter. | |
| build03.m | Generates C code for the frame-based Kalman filter. | |
| build04.m | Generates C code for the variable-size (packet-based) Kalman filter. | |
| Test scripts | test01.m | Tests the scalar Kalman filter and plots the trajectory. |
| test02.m | Tests MEX function for the original Kalman filter and plots the trajectory. | |
| test03.m | Tests the frame-based Kalman filter. | |
| test04.m | Tests the variable-size (packet-based) Kalman filter. | |
| MAT-file | position.mat | Contains the input data used by the algorithm. |
| Plot function | plot_trajectory.m | Plots the trajectory of the object and the Kalman filter estimated position. |
When writing MATLAB code that you want to convert into efficient, standalone C/C++ code, you must consider the following:
Data types
C and C++ use static typing. To determine the types of your variables before use, MATLAB Coder requires a complete assignment to each variable.
Array sizing
Variable-size arrays and matrices are supported for code generation. You can define inputs, outputs, and local variables in MATLAB functions to represent data that varies in size at run time.
Memory
You can choose whether the generated code uses static or dynamic memory allocation.
With dynamic memory allocation, you potentially use less memory at the expense of time to manage the memory. With static memory, you get best speed performance, but with higher memory usage. Most MATLAB code takes advantage of the dynamic sizing features in MATLAB, therefore dynamic memory allocation typically enables you to generate code from existing MATLAB code without modifying it much. Dynamic memory allocation also allows some programs to compile even when upper bounds cannot be found.
Static allocation reduces the memory footprint of the generated code, and therefore is suitable for applications where there is a limited amount of available memory, such as embedded applications.
Speed
Because embedded applications must run in real time, the code must be fast enough to meet the required clock rate.
To improve the speed of the generated code:
Choose a suitable C/C++ compiler. The default compiler that MathWorks supplies with MATLAB for Windows 32-bit platforms is not a good compiler for performance.
Consider disabling run-time checks.
By default, for safety, the code generated for your MATLAB code contains memory integrity checks and responsiveness checks. Generally, these checks result in more generated code and slower simulation. Disabling run-time checks usually results in streamlined generated code and faster simulation. Disable these checks only if you have verified that array bounds and dimension checking is unnecessary.
About Code Generation from MATLAB Algorithms in the Code Generation from MATLAB documentation
Defining MATLAB Variables for C/C++ Code Generation in 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
Copy the tutorial files to a local working folder:
Create a local solutions folder, for example, c:\coder\kalman\solutions.
Change to the docroot\toolbox\coder\examples folder. At the MATLAB command line, enter:
cd(fullfile(docroot, 'toolbox', 'coder', 'examples'))
Copy the contents of the kalman subfolder to your local solutions folder, specifying the full path name of the solutions folder:
copyfile('kalman', 'solutions')Your solutions folder now contains a complete set of solutions for the tutorial. If you do not want to perform the steps for each task in the tutorial, you can view the solutions to see how the code should look.
Create a local work folder, for example, c:\coder\kalman\work.
Copy the following files from your solutions folder to your work folder.
kalman01.m
position.mat
Build files build01.m through build04.m
Test scripts test01.m through test04.m
plot_trajectory.m
Your work folder now contains all the files that you need to get started with the tutorial.
In this tutorial, you work with a MATLAB function that implements a Kalman filter algorithm, which predicts the position of a moving object based on its past positions. Before generating C code for this algorithm, you make the MATLAB version suitable for code generation and generate a MEX function. Then you test the resulting MEX function to validate the functionality of the modified code. As you work through the tutorial, you refine the design of the algorithm to accept variable-size inputs.
First, use the script test01.m to run the original MATLAB function to see how the Kalman filter algorithm works. This script loads the input data and calls the Kalman filter algorithm to estimate the location. It then calls a plot function, plot_trajectory, which plots the trajectory of the object and the Kalman filter estimated position.
Set your MATLAB current folder to the work folder that contains your files for this tutorial. At the MATLAB command line, enter:
cd work
where work is the full path name of the work folder containing your files. For more information, see Using the Current Folder Browser in the MATLAB Desktop Tools and Development Environment documentation.
At the MATLAB command line, enter:
test01
The test script runs and plots the trajectory of the object in blue and the Kalman filter estimated position in green. Initially, you see that it takes a short time for the estimated position to converge with the actual position of the object. Then three sudden shifts in position occur—each time the Kalman filter readjusts and tracks the object after a few iterations.

Before using codegen to compile the Kalman filter example code, you must set up your C compiler. For most platforms, MathWorks supplies a default compiler with MATLAB. If your installation does not include a default compiler, for a list of supported compilers for the current release of MATLAB, see Supported Compilers and install a compiler that is suitable for your platform.
To set up the installed compiler:
At the MATLAB command line, enter:
mex -setup
Enter y to see the list of installed compilers.
Select a supported compiler.
Enter y to verify your choice.
Designing for Code Generation. Before generating code, you must prepare your MATLAB code for code generation. The first step is to eliminate unsupported constructs.
Checking for Violations at Design Time. You use the code analyzer in the MATLAB Editor to check for code violations at design time, minimizing compilation errors. The code analyzer continuously checks your code as you enter it. It reports problems and recommends modifications to maximize performance and maintainability.
To use the code analyzer to identify warnings and errors specific to MATLAB for code generation, you must add the %#codegen directive (or pragma) to your MATLAB file. A complete list of MATLAB for Code Generation code analyzer messages is available in the MATLAB Code Analyzer preferences. See Using the MATLAB Code Analyzer Report for more details.
Note The code analyzer might not detect all MATLAB for code generation issues. After eliminating any errors or warnings that the code analyzer detects, compile your code with codegen to determine if the code has other compliance issues. |
Checking for Violations at Code Generation Time. You can use codegen to check for violations at code generation time. codegen checks that your MATLAB code is suitable for code generation, as described in About Code Generation from MATLAB Algorithms in the Code Generation from MATLAB documentation.
When codegen detects errors or warnings, it automatically generates an error report that describes the issues and provides links to the offending MATLAB code. For more information, see Code Generation Reports .
After code generation, codegen generates a MEX function that you can use to test your implementation in MATLAB.
Checking for Violations at Run Time. You can use codegen to generate a MEX function and check for violations at run time. In simulation, the code generated for your MATLAB functions includes the run-time checks. Disabling run-time checks and extrinsic calls usually results in streamlined generated code and faster simulation. You control run-time checks using the MEX configuration object, coder.MexCodeConfig. For more information, see Controlling Run-Time Checks.
If you encounter run-time errors in your MATLAB functions, a run-time stack appears automatically in the MATLAB Command Window. See Debugging Run-Time Errors.
Making Your Code Suitable for Code Generation. To modify the code yourself, work through the exercises in this section. Otherwise, open the supplied file kalman02.m in your solutions subfolder to see the modified algorithm.
To begin the process of making your MATLAB code suitable for code generation, you work with the file kalman01.m. This code is a MATLAB version of a scalar Kalman filter that estimates the state of a dynamic system from a series of noisy measurements.
Set your MATLAB current folder to the work folder that contains your files for this tutorial. At the MATLAB command line, enter:
cd work
where work is the full path name of the work folder containing your files. See Using the Current Folder Browser in the MATLAB Desktop Tools and Development Environment documentation for more information.
Open kalman01.m in the MATLAB Editor. At the MATLAB command line, enter:
edit kalman01.m
The file opens in the MATLAB Editor. The code analyzer message indicator in the top right corner of the MATLAB Editor is green, which indicates that it has not detected any errors, warnings, or opportunities for improvement in the code.
Turn on MATLAB for code generation error checking by adding the %#codegen directive after the function declaration.
function y = kalman01(z) %#codegenThe code analyzer message indicator remains green, indicating that it has not detected any code generation related issues.

For more information on using the code analyzer, see Using the MATLAB Code Analyzer Report in the MATLAB Desktop Tools and Development documentation.
Save the file in the current folder as kalman02.m:
To match the function name to the file name, change the function name to kalman02.
function y = kalman02(z)
In the MATLAB Editor, select Save As from the File menu.
Enter kalman02.m as the new file name.
Note If you do not match the file name to the function name, the code analyzer warns you that these names are not the same and highlights the function name in orange to indicate that it can provide an automatic correction. For more information, see Changing Code Based on Code Analyzer Messages in the MATLAB documentation. |
Click Save.
Best Practice — Preserving Your Code
You are now ready to compile your code using codegen. By default, codegen checks that your MATLAB code is suitable for code generation, as described in About Code Generation from MATLAB Algorithms. Then, after compilation, codegen generates a MEX function that you can test in MATLAB.
Because C uses static typing, codegen must determine the properties of all variables in the MATLAB files at compile time. Therefore, you must specify the properties of all function inputs at the same time as you compile the file with codegen.
To compile kalman02.m, you must specify the size of the input vector y.
Load the position.mat file into your MATLAB workspace.
load position.mat
This command loads a matrix position containing the x and y coordinates of 310 points in Cartesian space.
Get the first vector in the position matrix.
z = position(1:2,1);
Compile the file kalman02.m using codegen.
codegen -report kalman02.m -args {z}codegen reports that the code generation is complete. By default, it generates a MEX function, kalman02_mex, in the current folder and provides a link to the code generation report.
Note that:
The -report option instructs codegen to generate a code generation report, which you can use to debug your MATLAB code and verify that it is suitable for code generation.
The -args option instructs codegen to compile the file kalman02.m using the class, size, and complexity of the sample input parameter z.
You have proved that the Kalman filter example code is suitable for code generation using codegen. You are ready to begin the next task in this tutorial, Verifying the MEX Function.
In this part of the tutorial, you test the MEX function to verify that it provides the same functionality as the original MATLAB code.
In addition, simulating your algorithm in MATLAB before generating C code enables you to detect and fix run-time errors that would be much harder to diagnose in the generated C code. By default, the following run-time checks execute when you simulate your MEX function in MATLAB:
Memory integrity checks. These checks perform array bounds and dimension checking and detect violations of memory integrity in code generated for MATLAB functions. If a violation is detected, MATLAB stops execution with a diagnostic message.
Responsiveness checks in code generated for MATLAB functions. These checks enable periodic checks for Ctrl+C breaks in code generated for MATLAB functions, allowing you to terminate execution with Ctrl+C at any time.
For more information, see Controlling Run-Time Checks.
Running the Generated MEX Function. You run the MEX function, kalman02_mex, using coder.runTest to call the test file, test02. This test file is the same as test01 that you used in Running the Original MATLAB Code except that it calls kalman02 instead of kalman01.
coder.runTest runs the test file and replaces calls to the MATLAB algorithm with calls to the MEX function.
coder.runTest('test02','kalman02')coder.runTest runs the MEX function, kalman02_mex, using the same inputs you used in Running the Original MATLAB Code.
The test script runs and plots the trajectory of the object and the Kalman filter estimated position as before.
You have generated a MEX function for your MATLAB code, verified that it is functionally equivalent to your original MATLAB code, and checked that no run-time errors occur. Now you are ready to begin the next task in this tutorial, Generating C Code Using codegen.
Best Practice — Separating Test Bench from Function
Code
In this task, you use codegen to generate C code for your MATLAB filter algorithm. You then view the generated C code using the MATLAB Coder code generation report and compare the generated C code with the original MATLAB code. You use the supplied build script build02.m to generate code.
About the Build Script. A build script automates a series of MATLAB commands that you want to perform repeatedly from the command line, saving you time and eliminating input errors.
The build script build02.m contains:
% Load the position vector
load position.mat
% Get the first vector in the position matrix
% to use as an example input
z = position(1:2,1);
% Generate C code only, create a code generation report
codegen -c -d build02 -config coder.config('lib') -report kalman02.m -args {z}Note that:
codegen opens the file kalman02.m and automatically translates the MATLAB code into C source code.
For more information, see Generating C/C++ Code from MATLAB Code.
The -c option instructs codegen to generate code only, without compiling the code to an object file. This option enables you to iterate rapidly between modifying MATLAB code and generating C code.
The -config coder.config('lib') option instructs codegen to generate embeddable C code suitable for targeting a static library instead of generating the default MEX function. For more information, see coder.config.
The -d option instructs codegen to generate code in the output folder build02.
The -report option instructs codegen to generate a code generation report that you can use to debug your MATLAB code and verify that it is suitable for code generation.
The -args option instructs codegen to compile the file kalman01.m using the class, size, and complexity of the sample input parameter z.
Best Practice — Generating C Code Only During Development
Run the build script.
build02
MATLAB processes the build file and outputs the message:
Code generation successful: View report.codegen generates files in the folder, build02.
To view the code generation report, click View report.
The MATLAB Coder Code Generation Report opens.
Click the C code tab to display the list of generated C files.
To view the generated C code, click the link to the target source file, for example, kalman02.c.
The file appears in the right pane. The code generation report provides a hyperlink to open the C code in the MATLAB Editor.
To learn more about the report, see Code Generation Reports.
To compare your generated C code to the original MATLAB code, open the C file, kalman02.c, and the kalman02.m file in the MATLAB Editor. View the files side by side by selecting Window > Left/Right Tile.

Here are some important points about the generated C code:
The function signature is:
void kalman02(const real_T z[2], real_T y[2])
z corresponds to the input z in your MATLAB code. The size of z is 2, which corresponds to the total size (2 x 1) of the example input you used when you compiled your MATLAB code.
You can easily compare the generated C code to your original MATLAB code. In the generated C code:
Your function name is unchanged.
Your comments are preserved in the same position.
Your variable names are the same as in the original MATLAB code.
The filter you have worked on so far in this tutorial uses a simple batch process that accepts one input at a time, so you must call the function repeatedly for each input. In this part of the tutorial, you learn how to modify the algorithm to accept a fixed-sized input, which makes the algorithm suitable for frame-based processing.
Modifying Your MATLAB Code. To modify the code yourself, work through the exercises in this section. Otherwise, open the supplied file kalman03.m in your solutions subfolder to see the modified algorithm.
The filter algorithm you have used so far in this tutorial accepts only one input. You can now modify the algorithm to process a vector containing more than one input. You need to find the length of the vector and call the filter code for each element in the vector in turn. You do this by calling the filter algorithm in a for-loop.
Open kalman02.m in the MATLAB Editor.
edit kalman02.m
Add a for-loop around the filter code.
Before the comment
% Predicted state and covariance
insert:
for i=1:size(z,2)
After
% Compute the estimated measurements y = H * x_est;
insert:
end
Your filter code should now look like this:
for i=1:size(z,2) % Predicted state and covariance x_prd = A * x_est; p_prd = A * p_est * A' + Q; % Estimation S = H * p_prd' * H' + R; B = H * p_prd'; klm_gain = (S \ B)'; % Estimated state and covariance x_est = x_prd + klm_gain * (z - H * x_prd); p_est = p_prd - klm_gain * H * p_prd; % Compute the estimated measurements y = H * x_est; end
Modify the line that calculates the estimated state and covariance to use the ith element of input z.
Change
x_est = x_prd + klm_gain * (z - H * x_prd);
to
x_est = x_prd + klm_gain * (z(:,i) - H * x_prd);
Modify the line that computes the estimated measurements to append the result to the ith element of the output y.
Change
y = H * x_est;
to
y(:,i) = H * x_est;
The code analyzer message indicator in the top right turns red to indicate that the code analyzer has detected an error. The code analyzer underlines the offending code in red and places a red marker to the right.
Move your pointer over the red marker to view the error.
The code analyzer reports that code generation does not support growth of the variable y through indexing.

To address the error, preallocate memory for the output y, which is the same size as the input z. Add this code before the for-loop.
% Pre-allocate output signal: y=zeros(size(z));
The red error marker disappears and the code analyzer message indicator in the top right edge of the code turns green, which indicates that you have fixed all the errors and warnings detected by the code analyzer.
For more information on using the code analyzer, see Using the MATLAB Code Analyzer Report in the MATLAB Desktop Tools and Development documentation.
Change the function name to kalman03 and save the file as kalman03.m in the current folder.
You are ready to begin the next task in the tutorial, Testing Your Modified Algorithm.
Testing Your Modified Algorithm. Use the test script test03.m to test kalman03.m. This script sets the frame size to 10 and calculates the number of frames in the example input. It then calls the Kalman filter and plots the results for each frame in turn.
At the MATLAB command line, enter:
test03
The test script runs and plots the trajectory of the object and the Kalman filter estimated position as before.
You are ready to begin the next task in the tutorial, Generating C Code for Your Modified Algorithm.
Note Before generating C code, it is best practice to generate a MEX function that you can execute within the MATLAB environment to test your algorithm and check for run-time errors. |
Generating C Code for Your Modified Algorithm. You use the supplied build script build03.m to generate code. The only difference between this build script and the script for the initial version of the filter is the example input used when compiling the file. build03.m specifies that the input to the function is a matrix containing five 2x1 position vectors, which corresponds to a frame size of 10.
To generate C code for kalman03:
At the MATLAB command line, enter:
build03
MATLAB processes the build file and outputs the message:
Code generation successful: View report.The generated C code is in work\codegen\lib\kalman03, where work is the folder that contains your tutorial files.
To view the generated C code:
Click View report.
The MATLAB Coder Code Generation Report appears.
Click the C code tab to display the list of generated C files.
Click the link to kalman03.c.
The file appears in the right pane.
Compare the generated C code with the C code for the scalar Kalman filter. You see that the code is almost identical except that there is a now a for-loop for the frame processing.
Here are some important points about the generated C code:
The function signature is now:
void kalman03(const real_T z[10], real_T y[10])
The size of z and y is now 10, which corresponds to the size of the example input z (2x5) used to compile your MATLAB code.
The filtering now takes place in a for-loop. The for-loop iterates over all 5 inputs.
for(i = 0; i < 5; i++)
{
/* Predicted state and covariance */ ...The algorithm you have used so far in this tutorial is suitable for processing input data that consists of fixed-size frames. In this part of the tutorial, you test your algorithm with variable-size inputs and see that the algorithm is suitable for processing packets of data of varying size. You then learn how to generate code for a variable-size input.
Use the test script test04.m to test kalman03.m with variable-size inputs.
The test script calls the filter algorithm in a loop, passing a different size input to the filter each time. Each time through the loop, the test script calls the plot_trajectory function for every position in the input.
To run the test script, at the MATLAB command line, enter:
test04
The test script runs and plots the trajectory of the object and the Kalman filter estimated position as before.
You have created an algorithm that accepts variable-size inputs. You are ready to begin the next task in the tutorial, Generating C Code for a Variable-Size Input.
Note Before generating C code, it is best practice to generate a MEX function that you can execute within the MATLAB environment to test your algorithm and check for run-time errors. |
You use the supplied build script build04.m to generate code.
This build file:
Specifies the upper bounds explicitly for the variable-size input using the declaration coder.typeof(z, [2 N], [0 1]) with the -args option on the codegen command line. The second input, [2 N], specifies the size and upper bounds of the variable size input z. Because N=100, coder.typeof specifies that the input to the function is a matrix with two dimensions, the upper bound for the first dimension is 2; the upper bound for the second dimension is 100. The third input specifies which dimensions are variable. A value of true or one means that the corresponding dimension is variable; a value of false or zero means that the corresponding dimension is fixed. The value [0 1] specifies that the first dimension is fixed, the second dimension is variable. For more information, see How to Generate Code for MATLAB Functions with Variable-Size Data in the Code Generation from MATLAB documentation.
Creates a code configuration object cfg and uses it with the -config option to specify code generation parameters. For more information, see coder.config.
How to Generate C Code for a Variable-Size Input.
Use the build script build04 to generate C code.
build04
View the generated C code as before.
Here are some important points about the generated C code:
The generated C code can process any size input from 2 x 1 to 2 x 100. The function signature is now:
void kalman03(real_T z_data[200], ...
int32_T z_sizes[2], ...
real_T y_data[200], int32_T y_sizes[2])Because y and z are variable size, the generated code contains two pieces of information about each of them: the data and the actual size of the sample. For example, for variable z, the generated code contains:
The data z_data[200], where 200 is the maximum size specified using coder.typeof.
z_sizes[2], which contains the actual size of the input data. This information varies each time the filter is called.
To maximize efficiency, the actual size of the input data z_sizes is used when calculating the estimated position. The filter processes only the number of samples available in the input.
for(i = 0; i+1 <= z_sizes[1]; i++) {
/* Predicted state and covariance */
for(k = 0; k < 6; k++) {
...
Back up your MATLAB code before you modify it.
Decide on a naming convention for your files and save interim versions frequently. For example, this tutorial uses a two-digit suffix to differentiate the various versions of the filter algorithm.
Use build scripts to build your files.
Use test scripts to separate the pre- and post-processing from the core algorithm.
Generate a MEX function before generating C code. Use this MEX function to simulate your algorithm in MATLAB to validate its operation and check for run-time errors.
Use the -args option to specify input parameters at the command line.
Use the -report option to create a code generation report.
Use coder.typeof to specify variable-size inputs.
Use the code generation configuration object (coder.config) to specify parameters for standalone C code generation.
| To... | See... |
|---|---|
See all the compilation options for codegen | |
Learn how to integrate your MATLAB code with Simulink models | Tutorial: Integrating MATLAB Code with a Simulink Model for Tracking a Moving Object in the Simulink documentation |
Learn more about using MATLAB for code generation | |
Use variable-size data | How Working with Variable-Size Data Is Different for Code Generation in the Code Generation from MATLAB documentation. |
Speed up fixed-point MATLAB code | fiaccel in the Fixed-Point Toolbox documentation. |
Integrate custom C code into MATLAB code and generate standalone code | |
Integrate custom C code into a MATLAB function for code generation | coder.ceval in the Code Generation from MATLAB documentation. |
Generate HDL from MATLAB code | |
Learn more about the best practices used in this tutorial |
MathWorks product documentation is available from the Help menu on the MATLAB desktop.
| For... | See... |
|---|---|
Code Generation from MATLAB | |
A list of MATLAB and toolbox functions that are suitable for code generation | |
What's new |
For additional information and support, visit the MATLAB Coder page on the MathWorks Web site at:
www.mathworks.com/products/matlab-coder
![]() | Generating C Code from MATLAB Code Using the MATLAB Coder Project Interface | Generating MEX Functions from MATLAB Code at the Command Line | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |