C Code Generation Using the MATLAB Coder App

Learning Objectives

In this tutorial, you learn how to:

  • Create and set up a MATLAB® Coder™ project.

  • Define function input properties.

  • Check for code generation readiness and run-time issues.

  • Generate C code from your MATLAB code.

  • 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

Required Products

This tutorial requires the following products:

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, at the MATLAB prompt, enter ver.

Example: The Kalman Filter

Description

You do not have to be familiar with the algorithm in the example to complete the tutorial.

The Kalman filter estimates 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 processing, 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. It 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 Kalman filter algorithm that this example uses.

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. The Kalman state vector 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
The algorithm initializes x_est to an empty 6x1 column vector. It updates x_est 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

The state transition matrix A, contains the coefficient values of x, y, Vx, Vy, Ax, and Ay. A captures these laws of motion.

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

  • 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. 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. In the example, you modify this file to make it suitable for code generation and for use with frame-based and packet-based inputs.
kalman02.mThe kalman01 function after modification to make it suitable for code generation.
kalman03.mThe kalman01 function after modification to make it suitable for frame-based and packet-based inputs.
Test scriptstest01_ui.mTests the scalar Kalman filter and plots the trajectory.
test02_ui.mTests the frame-based Kalman filter.
test03_ui.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, consider the following:

  • Data types

    C and C++ use static typing. Before you use your variables, to determine the types of your variables, 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 the software cannot find upper bounds.

  • Speed

    Because embedded applications 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® 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. These checks can result in more generated code and slower simulation. Disabling run-time checks can result 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

Copy Files to Local Working Folder

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 the modified code.

  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

    • Test script test01_ui.m

    • plot_trajectory.m

    Your work folder now contains the files to get started with the tutorial.

Run the Original MATLAB Code

In this tutorial, you work with a MATLAB function that implements a Kalman filter algorithm. The algorithm 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. You then 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_ui.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_ui.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 (MATLAB).

  2. At the MATLAB command prompt, enter:

    test01_ui

    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.

Set Up Your C Compiler

MATLAB Coder locates and uses a supported installed compiler. See Supported and Compatible Compilers on the MathWorks website.

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

Prepare MATLAB Code for Code Generation

Before generating code, prepare your MATLAB code for code generation:

  • To check for coding issues, use the Code Analyzer in the MATLAB Editor.

  • To screen the code for unsupported features and functions, use the code generation readiness tool.

  • To identify build and run-time issues, generate a MEX function from your entry-point functions. Run the MEX function.

During MATLAB code design, to prepare your code for code generation, you can use tools outside of the MATLAB Coder app. When you use the MATLAB Coder app to generate code, the app screens your code for coding issues and code generation readiness. If you perform the Check for Run-Time Issues step, the app generates and runs a MEX function. If the app finds issues, it displays warning and error messages. If you click a message, the app highlights the problem code in a pane where you can edit the code.

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.

Use the Code Analyzer in the MATLAB Editor to check for coding issues at design time. 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, add the %#codegen directive 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 (MATLAB).

Note

The Code Analyzer might not detect all code generation issues. After eliminating the 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 code generation does not support. The tool provides a report that lists the source files that contain unsupported features and functions. It also gives an indication of the amount of work 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 — right-click a MATLAB file

  • Using the command-line interface — use 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 for Issues at Code Generation Time.  You can use MATLAB Coder to check for issues at code generation time. MATLAB Coder checks that your MATLAB code is suitable for code generation.

When MATLAB Coder detects errors or warnings, it generates an error report that describes the issues and provides links to the problematic MATLAB code. For more information, see Code Generation Reports.

Checking for Issues at Run Time.  You can use MATLAB Coder to generate a MEX function and check for issues at run time. The MEX function generated for your MATLAB functions includes run-time checks. Disabling run-time checks and extrinsic calls usually results in streamlined generated code and faster simulation. Disabling run-time checks allows bugs in your code to cause MATLAB to fail. For more information, see Control Run-Time Checks.

If you encounter run-time errors in your MATLAB functions, a run-time stack appears in the Command Window. See Debug Run-Time Errors.

Make the MATLAB Code Suitable for Code Generation

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
    
    work is the full path of the work folder containing your files. See Files and Folders that MATLAB Accesses (MATLAB).

  2. Open kalman01.m in the MATLAB Editor. At the MATLAB command prompt, enter:

    edit kalman01.m

    Tip

    Before modifying your code, it is a best practice to back up your code.

     Best Practice — Preserving Your Code

    The file opens in the MATLAB Editor. The Code Analyzer message indicator in the top right corner of the MATLAB Editor is green. The analyzer did not detect errors, warnings, or opportunities for improvement in the code.

  3. Turn on MATLAB for code generation error checking. After the function declaration, add the %#codegen directive.

    function y = kalman01(z) %#codegen

    The Code Analyzer message indicator remains green, indicating that it has not detected code generation issues.

    For more information about using the Code Analyzer, see Running the Code Analyzer Report (MATLAB).

  4. Save the file.

    You are now ready to compile your code using the MATLAB Coder app.

Opening the MATLAB Coder App

On the MATLAB Toolstrip Apps tab, under Code Generation, click the MATLAB Coder app icon.

The app opens the Select Source Files page.

Select Source Files

  1. On the Select Source Files page, enter or select the name of the entry-point function kalman01. The app creates a project with the default name kalman01.prj in the current folder.

  2. Click Next to go to the Define Input Types step. The app analyzes the function for coding issues and code generation readiness. If the app identifies issues, it opens the Review Code Generation Readiness page where you can review and fix issues. In this example, because the app does not detect issues, it opens the Define Input Types page.

Define Input Types

Because C uses static typing, MATLAB Coder must determine the properties of all variables in the MATLAB files at compile time. Therefore, you must specify the properties of all function inputs. To specify input properties, you can:

  • Instruct the app to determine input properties using code that you provide.

  • Specify properties directly.

In this example, to define the properties of the input z, specify the test file test01_ui.m that MATLAB Coder can use to define types automatically for z:

  1. Enter or select the test file test01_ui.m.

  2. Click Autodefine Input Types.

    The test file, test01_ui.m, calls the entry-point function, kalman01.m, with the expected input types. The test file runs. The app infers that input z is double(2x1).

  3. Click Next to go to the Check for Run-Time Issues step.

Check for Run-Time Issues

The Check for Run-Time Issues step generates a MEX file from your entry-point functions, runs the MEX function, and reports issues. This step is optional. However, it is a best practice to perform this step. Using this step, you can detect and fix run-time errors that are harder to diagnose in the generated C code. By default, the MEX function includes memory integrity checks. These checks perform array bounds and dimension checking. The checks detect violations of memory integrity in code generated for MATLAB functions. For more information, see Control Run-Time Checks.

  1. To open the Check for Run-Time Issues dialog box, click the Check for Issues arrow .

  2. In the Check for Run-Time Issues dialog box, specify a test file or enter code that calls the entry-point file with example inputs. For this example, use the test file test01_ui that you used to define the input types. Make sure that the dialog box specifies the test01_ui script.

  3. Click Check for Issues.

    The app generates a MEX function. It runs the test script test01_ui replacing calls to kalman01 with calls to the generated MEX. If the app detects issues during the MEX function generation or execution, it provides warning and error messages. You can click these messages to navigate to the problematic code and fix the issue. In this example, the app does not detect issues.

    The test script plots the output from generated MEX version of kalman01. The MEX function has the same functionality as the original kalman01 function.

  4. By default, the app collects line execution counts. These counts help you to see how well the test file, test01_ui exercised the kalman01 function. To view line execution counts, click View MATLAB line execution counts. The app editor displays a color-coded bar to the left of the code. To extend the color highlighting over the code and to see line execution counts, pause over the bar.

    The orange color indicates that lines 27 and 28 executed one time. This behavior is expected because this code initializes a persistent variable. A particular shade of green indicates that the line execution count for this code falls in a certain range. In this case, the code executes 300 times. For information about how to interpret line execution counts and turn off collection of the counts, see Collect and View Line Execution Counts for Your MATLAB Code.

  5. Click Next to go to the Generate Code step.

Generate C Code

  1. To open the Generate dialog box, click the Generate arrow .

  2. In the Generate dialog box, set Build type to Static Library (.lib) and Language to C. Use the default values for the other project build configuration settings. Different project settings are available for MEX and C/C++ output types. When you switch between MEX and C/C++ code generation, verify these settings.

  3. Click Generate.

    MATLAB Coder generates a standalone C static library kalman01 in the work\codegen\lib\kalman01. work is the folder that contains your tutorial files. The MATLAB Coder app indicates that code generation succeeded. It displays the source MATLAB files and generated output files on the left side of the page. On the Variables tab, it displays information about the MATLAB source variables. On the Target Build Log tab, it displays the build log, including compiler warnings and errors. By default, in the code window, the app displays the C source code file, kalman01.c. To view a different file, in the Source Code or Output Files pane, click the file name.

  4. To view the report in the MATLAB Coder Report Viewer, click View Report.

  5. Click Next to open the Finish Workflow page.

Reviewing the Finish Workflow Page

The Finish Workflow page indicates that code generation succeeded. It provides a project summary and links to generated output.

Comparing the Generated C Code to Original MATLAB Code

To compare your generated C code to the original MATLAB code, open the C file, kalman01.c, and the kalman01.m file in the MATLAB Editor.

Here are some important points about the generated C code:

  • The function signature is:

    void kalman01(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. The code generator preserves your function name and comments. When possible, the software preserves your variable names.

    Note

    If a variable in your MATLAB code is set to a constant value, it does not appear as a variable in the generated C code. Instead, the generated C code contains the actual value of the variable.

Modifying the Filter to Accept a Fixed-Size Input

The filter uses a simple batch process that accepts one input at a time. 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. This modification makes the algorithm suitable for frame-based processing.

Modify Your MATLAB Code.  The original filter algorithm accepts only one input. You can modify the algorithm to process a vector containing more than one input. Modify the algorithm to find the length of the vector. To call the filter code for each element in the vector, call the filter algorithm in a for-loop.

  1. Open kalman01.m in the MATLAB Editor.

    edit kalman01.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 the comment

      % Compute the estimated measurements
      y = H * x_est;
      insert:
      end

    Your filter code now looks like this code:

    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(:, 1) = H * x_est;

    The Code Analyzer message indicator in the top right turns red to indicate that the Code Analyzer detects an error. The Code Analyzer underlines the offending code in red and places a red marker to the right.

  5. Move your cursor over the red marker to view the error.

    The Code Analyzer reports that code generation requires that you fully define variable y 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. Before the for-loop, add this code:

     % Pre-allocate output signal:
     y = zeros(size(z));

    You no longer see the red error marker and the Code Analyzer message indicator in the top right edge of the code turns green. The Code Analyzer does not detect errors or warnings.

    For more information about using the Code Analyzer, see Running the Code Analyzer Report (MATLAB).

  7. Save the file.

 Contents of the Modified kalman01.m

Generating C Code for Your Modified Algorithm.  The modified algorithm expects fixed-size input. Define the input types for the modified kalman01 function. Use the test file test02_ui.m to define input types for kalman01. 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.

 Contents of test02_ui.m

  1. To go to the Define Input Types step, expand the workflow steps and click Define Input Types.

  2. To delete the type information for z, above the input argument type definitions, click .

  3. To specify the test file to use for defining input types, enter or select test02_ui.m.

  4. Click Autodefine Input Types.

    The test file runs. The app infers that the type of z is double(2x10).

  5. Click Next to go to the Check for Run-Time Issues step.

  6. To open the Check for Issues dialog box, click the Check for Issues arrow .

  7. On the Check for Run-Time Issues page, make sure that the dialog box specifies the test02_ui.m file.

  8. Click Check for Issues.

    The app generates a MEX function. It runs the test script test02_ui replacing calls to kalman-01 with calls to the generated MEX. If the app detects issues during the MEX function generation or execution, it provides warning and error messages. You can click these messages to navigate to the problematic code and fix the issue. In this example, the app does not detect issues. The test script plots the output from generated the MEX version of kalman01. The MEX function has the same functionality as the original kalman01 function.

  9. Click Next to go to the Generate Code step.

  10. To open the Generate Code dialog box, click the Generate arrow .

  11. Set Build type to Source Code and Language to C.

    Selecting Source Code instructs MATLAB Coder to generate code without invoking the make command. If you use this option, MATLAB Coder does not generate compiled object code. This option saves you time during the development cycle when you want to iterate rapidly between modifying MATLAB code and inspecting generated C code.

  12. Click Generate.

    MATLAB Coder generates C code in the work\codegen\lib\kalman01 folder. work is the folder that contains your tutorial files. The MATLAB Coder app indicates that code generation succeeded. It displays the source MATLAB files and generated output files on the left side of the page. On the Variables tab, it displays information about the MATLAB source variables. On the Target Build Log, it displays the build log, including compiler warnings and errors. By default, the app displays the C source code file, kalman01.c. To view a different file, in the Source Code or Output Files pane, click the file name.

  13. View the generated C code.

    Some important points about the generated C code are:

    • The function signature is now:

      void kalman01(const double z[20], double y[20])
      The sizes of z and y are now 20, which corresponds to the size of the example input z (2x10) used to compile your MATLAB code.

    • The filtering now takes place in a for-loop. The for-loop iterates over all 10 inputs.

      for(i = 0; i < 10; i++) 
      {       
        /*  Predicted state and covariance */ ...

Use the Filter to Accept a Variable-Size Input

To show that the algorithm is suitable for processing packets of data of varying size, test your algorithm with variable-size inputs.

Test the Algorithm with Variable-Size Inputs.  Use the test script test03_ui.m to test the filter 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 test03_ui.m

To run the test script, at the MATLAB command prompt, enter:

test03_ui

The test script runs and plots the trajectory of the object and the Kalman filter estimated position.

Generating C Code for Variable-Size Inputs

  1. To go to the Define Input Types step, expand the workflow steps and click Define Input Types.

    To specify the test file to use for defining input types, enter or select test03_ui.m.

  2. To delete the type information for z, above the input argument type definitions, click .

  3. Click Autodefine Input Types.

    The test file runs. The app infers that the input type of z is double(2x:100). The : in front of the second dimension indicates that this dimension is variable size. The test file calls kalman01 multiple times with different-size inputs. Therefore, the app takes the union of the inputs and infers that the inputs are variable size. The upper bound is equal to the size of the largest input.

  4. Click Next to go to the Check for Run-Time Issues step.

  5. To open the Check for Issues dialog box, click the Check for Issues arrow .

  6. On the Check for Run-Time Issues page, make sure that the dialog box specifies the test03_ui.m file.

  7. Click Check for Issues.

    The app builds a MEX file and runs it replacing calls to kalman01 with calls to the MEX function. The app indicates that it does not detect issues.

  8. Click Next to go to the Generate Code step.

  9. To open the Generate Code dialog box, click the Generate arrow .

  10. Set Build type to Source Code and Language to C.

    Selecting Source Code instructs MATLAB Coder to generate code without invoking the make command. If you use this option, MATLAB Coder does not generate compiled object code. This option saves you time during the development cycle when you want to iterate rapidly between MATLAB code modification code and inspection of generated C code

  11. Click Generate.

    MATLAB Coder generates C code in the work\codegen\lib\kalman01 folder. work is the folder that contains your tutorial files. The MATLAB Coder app indicates that code generation succeeded. It displays the source MATLAB files and generated output files on the left side of the page. On the Variables tab, it displays information about the MATLAB source variables. On the Target Build Log, it displays the build log, including compiler warnings and errors. By default, the app displays the C source code file, kalman01.c. To view a different file, in the Source Code or Output Files pane, click the file name.

  12. View the generated C code.

    Some important points about the generated C code are:

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

Key Points to Remember

  • Before you modify your MATLAB code, back it up.

    Use test scripts to separate the pre- and post-processing from the core algorithm.

  • If you have a test file that calls the entry-point function with the required class, size, and complexity, use the Autodefine Input Types option to specify input parameters.

  • Perform the Check for Run-Time Issues step to check for run-time errors.

Learn More

Next Steps

ToSee

Learn how to integrate your MATLAB code with Simulink® models

Track Object Using MATLAB Code (Simulink)

Learn more about using MATLAB for code generation

MATLAB Programming for Code Generation

Use variable-size data

Code Generation for Variable-Size Arrays

Speed up fixed-point MATLAB code

fiaccel

Integrate custom C code into MATLAB code and generate embeddable code

Call C/C++ Code from MATLAB Code

Integrate custom C code into a MATLAB function for code generation

coder.ceval

Was this topic helpful?