C Code Generation at the Command Line

Learning Objectives

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.

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:

  • MATLAB

  • MATLAB Coder™

  • C compiler

    For most platforms, a default compiler is supplied with MATLAB.

    MATLAB Coder automatically locates and uses a supported installed compiler. For the current list of supported compilers, see Supported and Compatible Compilers on the MathWorks® website.

    You can use mex -setup to change the default compiler. See Change Default 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:

X=X0+Vx.dtY=Y0+Vy.dtVx=Vx0+Ax.dtVy=Vy0+Ay.dt

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:

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

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:

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

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:

  • 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 the best speed, 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 much modification. Dynamic memory allocation also allows some programs to compile even when upper bounds cannot be found.

  • 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® 64-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.

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 prompt, 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 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 prompt, enter:

    cd work
    where work is the full path name of the work folder containing your files. For more information, see Files and Folders that MATLAB Accesses.

  2. At the MATLAB command prompt, 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

MATLAB Coder automatically locates and uses a supported installed compiler. For the current list of supported compilers, see Supported and Compatible Compilers on the MathWorks website.

You can use mex -setup to change the default compiler. See Change Default Compiler.

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 Issues at Design Time.  There are two tools that help you detect code generation issues at design time: the code analyzer and the code generation readiness tool.

You use the code analyzer in the MATLAB Editor to check for coding issues at design time, minimizing compilation errors. The code analyzer continuously checks your code as you enter it. It reports issues 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 Running the Code Analyzer Report.

    Note:   The code analyzer might not detect all MATLAB for code generation issues. After eliminating errors or warnings that the code analyzer detects, compile your code with MATLAB Coder to determine if the code has other compliance issues.

The code generation readiness tool screens MATLAB code for features and functions that are not supported for code generation. The tool provides a report that lists the source files that contain unsupported features and functions and an indication of how much work is required to make the MATLAB code suitable for code generation.

You can access the code generation readiness tool in the following ways:

  • In the current folder browser — by right-clicking a MATLAB file

  • At the command line — by using the coder.screener function.

  • Using the MATLAB Coder app — after you specify your entry-point files, the app runs the Code Analyzer and code generation readiness tool.

Checking Issues at Code Generation Time.  You can use codegen to check for issues at code generation time. codegen checks that your MATLAB code is suitable for code generation.

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 Issues at Run Time.  You can use codegen to generate a MEX function and check for issues 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 Control 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 Debug 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 prompt, enter:

    cd work
    
    where work is the full path name of the work folder containing your files. See Files and Folders that MATLAB Accesses.

  2. Open kalman01.m in the MATLAB Editor. At the MATLAB command prompt, 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 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 code generation related issues.

    For more information on using the code analyzer, see Running the Code Analyzer Report.

  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.

    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. 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 MEX function includes 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. For more information, see Control 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 for run-time errors. 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:

  • codegen opens the file kalman02.m and automatically translates the MATLAB code into C source 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

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 and displays the generated code, 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.

Here are some important points about the generated C code:

  • The function signature is:

    void kalman02(const double z[2], double 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.

        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.

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 requires variable y to be fully defined before subscripting it.

     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 the errors and warnings detected by the code analyzer.

    For more information on using the code analyzer, see Running the Code Analyzer Report.

  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 prompt, 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.

 Contents of build03.m

To generate C code for kalman03:

  1. At the MATLAB command prompt, 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 opens and displays the generated coder, kalman03.c.

  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 double z[10], double 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 prompt, 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.

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:

  • 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 Generating Code for MATLAB Functions with Variable-Size Data.

  • 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  

  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 inputs from 2 x 1 to 2 x 100. The function signature is now:

      void kalman01(const double z_data[], const int z_size[2], double y_data[], int y_size[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[].

      • z_size[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_size 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_size[1]; i++) {
         /*  Predicted state and covariance */
           for(k = 0; k < 6; k++) {
             ...

Key Points to Remember

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

Learn More

Next Steps

To...See...

See the compilation options for codegen

codegen

Learn how to integrate your MATLAB code with Simulink® models

Track Object Using MATLAB Code

Learn more about using MATLAB for code generation

MATLAB Programming for Code Generation

Use variable-size data

Variable-Size Data Definition for Code Generation

Speed up fixed-point MATLAB code

fiaccel

Integrate custom C code into MATLAB code and generate standalone code

Specify External File Locations

Integrate custom C code into a MATLAB function for code generation

coder.ceval

Generate HDL from MATLAB code

www.mathworks.com/products/slhdlcoder

MathWorks Online

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

www.mathworks.com/products/matlab-coder

Was this topic helpful?