Main Content

Propose Data Types Based on Simulation Ranges Using the Fixed-Point Converter App

This example shows how to propose fixed-point data types based on simulation range data using the Fixed-Point Converter app.

Prerequisites

This example requires the following products:

Create a New Folder and Copy Relevant Files

  1. In a local, writable folder, create a function ex_2ndOrder_filter.m.

    function y = ex_2ndOrder_filter(x) %#codegen
      persistent z
      if isempty(z)
          z = zeros(2,1);
      end
      % [b,a] = butter(2, 0.25)
      b = [0.0976310729378175,  0.195262145875635,  0.0976310729378175];
      a = [1, -0.942809041582063,  0.3333333333333333];
    
     
      y = zeros(size(x));
      for i = 1:length(x)
          y(i) = b(1)*x(i) + z(1);
          z(1) = b(2)*x(i) + z(2) - a(2) * y(i);
          z(2) = b(3)*x(i)        - a(3) * y(i);
      end
    end
    
  2. Create a test file, ex_2ndOrder_filter_test.m, to exercise the ex_2ndOrder_filter algorithm.

    It is a best practice is to create a separate test script to do pre- and post-processing, such as:

    • Loading inputs.

    • Setting up input values.

    • Outputting test results.

    See Create a Test File.

    To cover the full intended operating range of the system, the test script runs the ex_2ndOrder_filter function with three input signals: chirp, step, and impulse. The script then plots the outputs.

    % ex_2ndOrder_filter_test
    %
    % Define representative inputs
    N = 256;                   % Number of points
    t = linspace(0,1,N);       % Time vector from 0 to 1 second
    f1 = N/2;                  % Target frequency of chirp set to Nyquist
    x_chirp = sin(pi*f1*t.^2); % Linear chirp from 0 to Fs/2 Hz in 1 second
    x_step = ones(1,N);        % Step
    x_impulse = zeros(1,N);    % Impulse
    x_impulse(1) = 1;
    
    % Run the function under test
    x = [x_chirp;x_step;x_impulse];
    y = zeros(size(x));
    for i = 1:size(x,1)
      y(i,:) = ex_2ndOrder_filter(x(i,:));
    end
    
    % Plot the results
    titles = {'Chirp','Step','Impulse'}
    clf
    for i = 1:size(x,1)
      subplot(size(x,1),1,i)
      plot(t,x(i,:),t,y(i,:))
      title(titles{i})
      legend('Input','Output')
    end
    xlabel('Time (s)')
    figure(gcf)
    
    disp('Test complete.')
TypeNameDescription
Function codeex_2ndOrder_filter.mEntry-point MATLAB function
Test fileex_2ndOrder_filter_test.mMATLAB script that tests ex_2ndOrder_filter.m

Open the Fixed-Point Converter App

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

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

Select Source Files

  1. To add the entry-point function ex_2ndOrder_filter to the project, browse to the file ex_2ndOrder_filter.m, and then click Open. By default, the app saves information and settings for this project in the current folder in a file named ex_2ndOrder_filter.prj.

  2. Click Next to go to the Define Input Types step.

    The app screens ex_2ndOrder_filter.m for code violations and fixed-point conversion readiness issues. The app does not find issues in ex_2ndOrder_filter.m.

Define Input Types

  1. On the Define Input Types page, to add ex_2ndOrder_filter_test as a test file, browse to ex_2ndOrder_filter_test, and then click Open.

  2. Click Autodefine Input Types.

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

    The app determines from the test file that the input type of x is double(1x256).

  3. Click Next to go to the Convert to Fixed Point step.

Convert to Fixed Point

  1. The app generates an instrumented MEX function for your entry-point MATLAB function. The app displays compiled information—type, size, and complexity—for variables in your code. See View and Modify Variable Information.

    On the Function Replacements tab, the app displays functions that are not supported for fixed-point conversion. See Running a Simulation.

  2. Click the Analyze arrow . Verify that Analyze ranges using simulation is selected and that the test bench file is ex_2ndOrder_filter_test. You can add test files and select to run more than one test file during the simulation. If you run multiple test files, the app merges the simulation results.

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

  4. Click Analyze.

    The simulation runs and the app 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. The dark green line to the left of the code indicates that the code runs every time the algorithm executes. The orange bar indicates that the code next to it executes only once. This behavior is expected for this example because the code initializes a persistent variable. If your test file does not cover all of your code, update the test or add more test files.

    If a value has ... next to it, the value is rounded. Pause over the ... to view the actual value.

    The app 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 app enables the Convert option.

    Note

    You can manually enter static ranges. These manually entered ranges take precedence over simulation ranges. The app uses the manually entered ranges to propose data types. You can also modify and lock the proposed type.

  5. 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 Proposed Type field or use the histogram controls. For more information about the histogram, see Log Data for Histogram.

  6. To convert the floating-point algorithm to fixed point, click Convert.

    During the fixed-point conversion process, the software validates the proposed types and generates the following files in the codegen\ex_2ndOrder_filter\fixpt folder in your local working folder.

    • ex_2ndOrder_filter_fixpt.m — the fixed-point version of ex_2ndOrder_filter.m.

    • ex_2ndOrder_filter_wrapper_fixpt.m — this file converts the floating-point data values supplied by the test file to the fixed-point types determined for the inputs during conversion. These fixed-point values are fed into the converted fixed-point design, ex_2ndOrder_filter_fixpt.m.

    • ex_2ndOrder_filter_fixpt_report.html — this report shows the generated fixed-point code and the fixed-point instrumentation results.

    • ex_2ndOrder_filter_report.html — this report shows the original algorithm and the fixed-point instrumentation results.

    • ex_2ndOrder_filter_fixpt_args.mat — MAT-file containing a structure for the input arguments, a structure for the output arguments and the name of the fixed-point file.

    If errors or warnings occur during validation, you see them on the Output tab. See Validating Types.

  7. In the Output Files list, select ex_2ndOrder_filter_fixpt.m. The app displays the generated fixed-point code.

  8. Click the Test arrow . Select Log inputs and outputs for comparison plots, and then click Test.

    To test the fixed-point MATLAB code, the app runs the test file that you used to define input types. 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 app generates a plot for each input and output. The app docks these plots in a single figure window.

    The app also reports error information on the Verification Output tab. The maximum error is less than 0.03%. For this example, this margin of error is acceptable.

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

  9. On the Verification Output tab, the app provides a link to a report that shows the generated fixed-point code and the proposed type information.

  10. Click Next to go to the Finish Workflow page.

    On the Finish Workflow page, the app displays a project summary and links to generated output files.

Integrate Fixed-Point Code

To integrate the fixed-point version of the code into system-level simulations, generate a MEX function to accelerate the fixed-point algorithm. Call this MEX function instead of the original MATLAB algorithm.

  1. Copy ex_2ndOrder_filter_fixpt.m to your local working folder.

  2. Generate a MEX function for ex_2ndOrder_filter_fixpt.m. Look at the get_fimath function in the ex_2ndOrder_filter_fixpt.m file to get the fimath, and use the type proposal report to get fixed-point data type for input x.

    fm = fimath('RoundingMethod','Floor',...
        'OverflowAction','Wrap',...
        'ProductMode','FullPrecision',...
        'MaxProductWordLength',128,...
        'SumMode','FullPrecision',...
        'MaxSumWordLength',128);
    fiaccel ex_2ndOrder_filter_fixpt -args {fi(0,1,16,14,fm)}

    fiaccel generates a MEX function, ex_2ndOrder_filter_fixpt_mex, in the current folder.

  3. You can now call this MEX function in place of the original MATLAB algorithm.