Skip to Main Content Skip to Search
Product Documentation

Generating C Code from MATLAB Code at the Command Line

Learning Objectives

In this tutorial, you will learn how to:

Tutorial Prerequisites

What You Need to Know

To complete this tutorial, you should have basic familiarity with MATLAB software.

Required Products

To complete this tutorial, you must install the following products:

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.

Example: The Kalman Filter

Description

This section describes the example used by the tutorial. You do not have to be familiar with the algorithm to complete the tutorial.

The example for this tutorial uses a Kalman filter to estimate the position of an object moving in a two-dimensional space from a series of noisy inputs based on past positions. The position vector has two components, x and y, indicating its horizontal and vertical coordinates.

Kalman filters have a wide range of applications, including control, signal and image processing; radar and sonar; and financial modeling. They are recursive filters that estimate the state of a linear dynamic system from a series of incomplete or noisy measurements. The Kalman filter algorithm relies on the state-space representation of filters and uses a set of variables stored in the state vector to characterize completely the behavior of the system. It updates the state vector linearly and recursively using a state transition matrix and a process noise estimate.

Algorithm

This section describes the algorithm of the Kalman filter and is implemented in the MATLAB version of the filter supplied with this tutorial.

The algorithm predicts the position of a moving object based on its past positions using a Kalman filter estimator. It estimates the present position by updating the Kalman state vector, which includes the position (x and y), velocity (Vx and Vy), and acceleration (Ax and Ay) of the moving object. The Kalman state vector, x_est, is a persistent variable.

% Initial conditions
persistent x_est p_est
if isempty(x_est)
    x_est = zeros(6, 1);
    p_est = zeros(6, 6);
end

x_est is initialized to an empty 6x1 column vector and updated each time the filter is used.

The Kalman filter uses the laws of motion to estimate the new state:

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 ];

Filtering Process

The filtering process has two phases:

Reference

Haykin, Simon. Adaptive Filter Theory. Upper Saddle River, NJ: Prentice-Hall, Inc., 1996.

Files for the Tutorial

About the Tutorial Files

The tutorial uses the following files:

Location of Files

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.

Names and Descriptions of Files

TypeNameDescription
Function code kalman01.mBaseline MATLAB implementation of a scalar Kalman filter.
kalman02.mVersion of the original algorithm that is suitable for code generation.
kalman03.mKalman filter suitable for use with frame-based and packet-based inputs.
Build scriptsbuild01.mGenerates MEX function for the original Kalman filter.
build02.mGenerates C code for the original Kalman filter.
build03.mGenerates C code for the frame-based Kalman filter.
build04.mGenerates C code for the variable-size (packet-based) Kalman filter.
Test scriptstest01.mTests the scalar Kalman filter and plots the trajectory.
test02.mTests MEX function for the original Kalman filter and plots the trajectory.
test03.mTests the frame-based Kalman filter.
test04.mTests the variable-size (packet-based) Kalman filter.
MAT-fileposition.matContains the input data used by the algorithm.
Plot functionplot_trajectory.mPlots the trajectory of the object and the Kalman filter estimated position.

Design Considerations When Writing MATLAB Code for Code Generation

When writing MATLAB code that you want to convert into efficient, standalone C/C++ code, you must consider the following:

See Also

Tutorial Steps

Copying Files Locally

Copy the tutorial files to a local working folder:

  1. Create a local solutions folder, for example, c:\coder\kalman\solutions.

  2. Change to the docroot\toolbox\coder\examples folder. At the MATLAB command line, enter:

    cd(fullfile(docroot, 'toolbox', 'coder', 'examples')) 
  3. 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.

  4. Create a local work folder, for example, c:\coder\kalman\work.

  5. Copy the following files from your solutions folder to your work folder.

    • kalman01.m

    • position.mat

    • Build files build01.m through build04.m

    • Test scripts test01.m through test04.m

    • plot_trajectory.m

    Your work folder now contains all the files that you need to get started with the tutorial.

Running the Original MATLAB Code

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.

 Contents of test01.m

 Contents of plot_trajectory.m

  1. 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.

  2. 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.

Setting Up Your C Compiler

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:

  1. At the MATLAB command line, enter:

    mex -setup
  2. Enter y to see the list of installed compilers.

  3. Select a supported compiler.

  4. Enter y to verify your choice.

Considerations for Making Your Code Suitable for Code Generation

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.

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 the MATLAB Code Suitable for Code Generation

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.

  1. 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.

  2. 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.

  3. Turn on MATLAB for code generation error checking by adding the %#codegen directive after the function declaration.

    function y = kalman01(z) %#codegen

    The 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.

  4. Save the file in the current folder as kalman02.m:

    1. To match the function name to the file name, change the function name to kalman02.

      function y = kalman02(z)
    2. In the MATLAB Editor, select Save As from the File menu.

    3. 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.

    4. 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.

Generating a MEX Function Using codegen

Because C uses static typing, codegen must determine the properties of all variables in the MATLAB files at compile time. Therefore, you must specify the properties of all function inputs at the same time as you compile the file with codegen.

To compile kalman02.m, you must specify the size of the input vector y.

  1. 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.

  2. Get the first vector in the position matrix.

    z = position(1:2,1);
  3. 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.

     Best Practice — Generating a Code Generation Report

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.

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:

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.

 Contents of test02.m

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

Generating C Code Using codegen

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:

 Best Practice — Generating C Code Only During Development

How to Generate C Code.  

  1. 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.

  2. To view the code generation report, click View report.

    The MATLAB Coder Code Generation Report opens.

  3. Click the C code tab to display the list of generated C files.

  4. 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.

Comparing the Generated C Code to Original MATLAB Code

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:

Modifying the Filter to Accept a Fixed-Size Input

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.

  1. Open kalman02.m in the MATLAB Editor.

    edit kalman02.m
  2. Add a for-loop around the filter code.

    1. Before the comment

      % Predicted state and covariance

      insert:

      for i=1:size(z,2)
    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
  3. 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);
  4. 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.

  5. 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.

     Why Preallocate the Outputs?

  6. To address the error, preallocate memory for the output y, which is the same size as the input z. Add this code before the for-loop.

     % 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.

  7. Change the function name to kalman03 and save the file as kalman03.m in the current folder.

 Contents of kalman03.m

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.

 Contents of test03.m

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.

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.

 Contents of build03.m

To generate C code for kalman03:

  1. 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.

  2. To view the generated C code:

    1. Click View report.

      The MATLAB Coder Code Generation Report appears.

    2. Click the C code tab to display the list of generated C files.

    3. Click the link to kalman03.c.

      The file appears in the right pane.

  3. Compare the generated C code with the C code for the scalar Kalman filter. You see that the code is almost identical except that there is a now a for-loop for the frame processing.

    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 */ ...

Modifying the Filter to Accept a Variable-Size Input

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.

Testing the Algorithm with Variable-Size Inputs

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.

 Contents of test04.m

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.

Generating C Code for a Variable-Size Input

You use the supplied build script build04.m to generate code.

About the Build Script.  

 Contents of build04.m

This build file:

How to Generate C Code for a Variable-Size Input.  

  1. Use the build script build04 to generate C code.

    build04
  2. 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++) {
             ...

Key Points to Remember

Where to Learn More

Next Steps

To...See...

See all the compilation options for codegen

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

Code Generation from MATLAB User's Guide

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

Custom C/C++ Code Integration

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

www.mathworks.com/products/slhdlcoder

Learn more about the best practices used in this tutorial

Best Practices for Working with MATLAB Coder

Product Help

MathWorks product documentation is available from the Help menu on the MATLAB desktop.

For...See...

Code Generation from MATLAB

Code Generation from MATLAB User's Guide

A list of MATLAB and toolbox functions that are suitable for code generation

Code Generation from MATLAB Reference

What's new

MathWorks Online

For additional information and support, visit the MATLAB Coder page on the MathWorks Web site at:

www.mathworks.com/products/matlab-coder

  


Recommended Products

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