Documentation Center

  • Trial Software
  • Product Updates


Propose Data Types Based on Simulation Ranges

This example shows how to propose fixed-point data types based on simulation range data.


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


  • MATLAB Coder™

  • Fixed-Point Designer™

  • C compiler (for most platforms, a default C compiler is supplied with MATLAB) For a list of supported compilers, see Supported Compilers

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

Create a New Folder and Copy Relevant Files

  1. Create a local working folder, for example, c:\coder\fun_with_matlab.

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

    cd(fullfile(docroot, 'toolbox', 'coder', 'examples')) 
  3. Copy the fun_with_matlab.m and fun_with_matlab_test.m files to your local working folder.

    It is best practice to create a separate test script to do all the pre- and post-processing such as loading inputs, setting up input values, calling the function under test, and outputting test results. For more information, see Create a Test File.

    Function codefun_with_matlab.mEntry-point MATLAB function
    Test filefun_with_matlab_test.mMATLAB script that tests fun_with_matlab.m

 The fun_with_matlab Function

 The fun_with_matlab_test Script

Check Code Generation Readiness

In the current working folder, right-click the fun_with_matlab.m function. From the context menu, select Check Code Generation Readiness.

The code generation readiness tool screens the code for features and functions that are not supported for code generation. The tool reports that the fun_with_matlab.m function is already suitable for code generation.

If your entry-point function is not suitable for code generation, the tool provides a report that lists the source files that contain unsupported features and functions. The report also provides an indication of how much work you must do to make the MATLAB code ready for code generation. Before proposing data types, you must fix these issues. For more information, see Detect and Debug Code Generation Errors.

Create and set up a MATLAB Coder Project

  1. Navigate to the work folder that contains the file for this example.

  2. On the MATLAB Apps tab, select MATLAB Coder and then, in the MATLAB Coder Project dialog box, set Name to fun_with_matlab_project.prj.

    Alternatively, at the MATLAB command line, enter

    coder -new fun_with_matlab_project.prj

    By default, the project opens in the MATLAB workspace.

  3. On the project Overview tab, click the Add files link. Browse to the file fun_with_matlab.m and then click OK to add the file to the project.

Define Input Types

  1. On the project Overview tab, click the Autodefine types link.

  2. In the Autodefine Input Types dialog box, add fun_with_matlab_test as a test file and then click Run.

    The test file runs and displays the outputs of the filter for each of the input signals.

    MATLAB Coder determines the input types from the test file and then displays them.

  3. In the Autodefine Input Types dialog box, click Use These Types.

    MATLAB Coder sets the type of x to double(1x256).

Fixed-Point Conversion

  1. On the project Overview tab Fixed-Point Conversion pane, select Convert to fixed-point at build time.

    The project indicates that you must first define the fixed-point data types.

  2. In the Fixed-Point Conversion pane, click Define and validate fixed-point types.

    The Fixed-Point Conversion window opens and the tool generates an instrumented MEX function for your entry-point MATLAB function. After generating the MEX function, the tool displays compiled information — type, size, and complexity — for variables in your code. For more information, see View and Modify Variable Information.

    If the MEX function generation fails, the tool provides error message links to help you navigate to the code that caused the build issues. If your code contains functions that are not supported for fixed-point conversion, the tool displays these on the Function Replacements tab. For more information, see Running a Simulation.

  3. Click Run Simulation and verify that the fun_with_matlab_test file is selected as a test file to run. You can add test files and select to run more than one test file during the simulation. If you run multiple test files, the conversion tool merges the simulation results. To clear results, right-click the Variables tab and select Reset entire table.

  4. Click Run Simulation and select Log data for histogram.

    By default, the Show code coverage option is selected. This option provides code coverage information that helps you verify that your test file is testing your algorithm over the intended operating range.

  5. Click the Run Simulation button.

    The simulation runs and the conversion tool displays a color-coded code coverage bar to the left of the MATLAB code. Review this information to verify that the test file is testing the algorithm adequately. Here, the dark green line to the left of the code indicates that the code is run every time the algorithm is executed. The orange bar indicates that the code next to it is executed only once. In this example, this is the expected behavior because the code is initializing a persistent variable. If your test file is not covering all your code, update the test or add more test files.

    If a value has ... next to it, the value is rounded. Place your cursor over the ... to view the actual value.

    The tool displays simulation minimum and maximum ranges on the Variables tab. Using the simulation range data, the software proposes fixed-point types for each variable based on the default type proposal settings, and displays them in the Proposed Type column. The Validate Types option is now enabled.

      Note:   If you manually enter static ranges, these manually-entered ranges take precedence over simulation ranges and the tool uses them to propose data types. In addition, you can also modify and lock the proposed type.

  6. Examine the proposed types and verify that they cover the full simulation range. To view logged histogram data for a variable, click its Proposed Type field.

    To modify the proposed data types, either enter the required type into the ProposedType field or use the histogram controls. For more information about the histogram, see Histogram.

  7. To validate the build using the proposed types, click Validate Types.

    The software validates the proposed types, displays a Validation succeeded message, and enables the Test Numerics option. The project indicates that you have validated the fixed-point data types.

    If the errors or warnings occur during validation, they are displayed on the Type Validation Output tab. For more information, see Validating Types.

  8. Click Test Numerics, select Log inputs and outputs for comparison plots, and then click the Test Numerics button.

    The tool runs the test file that you used to define input types to test the fixed-point MATLAB code. Optionally, you can add test files and select to run more than one test file to test numerics. The software runs both a floating-point and a fixed-point simulation and then calculates the errors for the output variable y. Because you selected to log inputs and outputs for comparison plots, the tool generates an additional plot for each scalar output.

    The maximum error is less than 0.03%. For the purpose of this example, this margin of error is acceptable, so you are ready to generate fixed-point C code.

    If the difference is not acceptable, modify the fixed-point data types or your original algorithm. For more information, see Testing Numerics.

  9. Return to the MATLAB Coder project.

Generate Fixed-Point C Code

  1. In the MATLAB Coder project, verify that the Fixed-Point Conversion pane displays Ready for conversion, and then select the Build tab.

  2. On this tab, set the Output type to C/C++ Static library.

    The default output file name is fun_with_matlab.

  3. Click Build to generate a library using the default project settings.

    MATLAB Coder builds the project and generates a C static library and supporting files in the default subfolder, codegen/lib/fun_with_matlab_fixpt.

  4. To view the generated code, click View report.

    The code generation report opens and displays the generated code for fun_with_matlab_fixpt.c. In the generated C code, the variables are not assigned real types, they are assigned fixed-point data types.

    In this case, the generated code is not optimized; it contains a number of utility functions, such as MultiWordAdd. MATLAB Coder generates these utility functions because the results of adding or multiplying inputs results in a sum or product that exceed 32 bits. You can optimize the generated code by modifying the word length and fimath settings.

Optimize Fixed-Point C Code

  1. In the Fixed-Point Conversion tool, click Advanced to display the advanced type proposal settings.

    The fimath Product mode and Sum mode settings are both set to FullPrecision. In FullPrecision mode, the product word length grows to the sum of the word lengths of the operands.

  2. Set the fimath Product mode and Sum mode to SpecifyPrecision.

    Selecting SpecifyPrecision enables the Product word length, Product fraction length, Sum word length, and Sum fraction length settings. The product word length and sum word length are both set to 32, which limits these word lengths to 32 in the generated code.

  3. Click Validate Types.

    Because you have changed type proposal settings, you must validate the types again.

    The software validates the proposed types, displays a Validation succeeded message.

  4. Click the Test Numerics button.

    The maximum error is still less than 0.03%, so you are ready to generate fixed-point C code.

  5. Generate code again and view the generated C code for fun_with_matlab_fixpt.c. This time, because the word lengths in the generated code do not exceed 32 bits, the generated code does not contain utility functions.

    void fun_with_matlab_fixpt(const short x[256], short y[256])
      int i0;
      int i;
      int i1;
      short b_y;
      int i2;
      int i3;
      /*  [b,a] = butter(2, 0.25) */
      for (i0 = 0; i0 < 256; i0++) {
        y[i0] = 0;
      for (i = 0; i < 256; i++) {
        i0 = 25593 * x[i];
        if (i0 >= 0) {
          i1 = (int)((unsigned int)i0 >> 2);
        } else {
          i1 = ~(int)((unsigned int)~i0 >> 2);
        i0 = i1 + (z[0] << 15);
        if (i0 >= 0) {
          b_y = (short)((unsigned int)i0 >> 16);
        } else {
          b_y = (short)~(int)((unsigned int)~i0 >> 16);
        i0 = 25593 * x[i];
        if (i0 >= 0) {
          i2 = (int)((unsigned int)i0 >> 1);
        } else {
          i2 = ~(int)((unsigned int)~i0 >> 1);
        i0 = (i2 + (z[1] << 15)) - (-30894 * b_y << 1);
        if (i0 >= 0) {
          z[0] = (short)((unsigned int)i0 >> 15);
        } else {
          z[0] = (short)~(int)((unsigned int)~i0 >> 15);
        i0 = 25593 * x[i];
        if (i0 >= 0) {
          i3 = (int)((unsigned int)i0 >> 2);
        } else {
          i3 = ~(int)((unsigned int)~i0 >> 2);
        i0 = i3 - 21844 * b_y;
        if (i0 >= 0) {
          z[1] = (short)((unsigned int)i0 >> 15);
        } else {
          z[1] = (short)~(int)((unsigned int)~i0 >> 15);
        y[i] = b_y;
Was this topic helpful?