Main Content

Propose Data Types Based on Derived Ranges

This example shows how to propose fixed-point data types based on static ranges using the Fixed-Point Converter app. When you propose data types based on derived ranges you, do not have to provide test files that exercise your algorithm over its full operating range. Running such test files often takes a long time. You can save time by deriving ranges instead.

Note

Derived range analysis is not supported for non-scalar variables.

Prerequisites

This example requires the following products:

Create a New Folder and Copy Relevant Files

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

    The dti function implements a Discrete Time Integrator in MATLAB.

    function [y, clip_status] = dti(u_in) %#codegen
    % Discrete Time Integrator in MATLAB
    %  
    % Forward Euler method, also known as Forward 
    % Rectangular, or left-hand approximation. 
    % The resulting expression for the output of 
    % the block at step 'n' is 
    % y(n) = y(n-1) + K * u(n-1)
    %
    
    init_val = 1;  
    gain_val = 1;
    limit_upper = 500;
    limit_lower = -500;
    
    % Variable to hold state between 
    % consecutive calls to this block
    persistent u_state;
    if isempty(u_state)
        u_state = init_val+1;
    end 
    
    % Compute Output
    if (u_state > limit_upper)
        y = limit_upper;
        clip_status = -2;
    elseif (u_state >= limit_upper)
        y = limit_upper;
        clip_status = -1;
    elseif (u_state < limit_lower)
    	y = limit_lower;
        clip_status = 2;
    elseif (u_state <= limit_lower)
    	y = limit_lower;
        clip_status = 1;   
    else        
        y = u_state;
        clip_status = 0;
    end
    
    % Update State
    tprod = gain_val * u_in;
    u_state = y + tprod;
    
  2. Create a test file, dti_test.m, to exercise the dti algorithm.

    The test script runs the dti function with a sine wave input. The script then plots the input and output signals.

    % dti_test
    % cleanup
    clear dti
    
    % input signal
    x_in = sin(2.*pi.*(0:0.001:2)).';
    
    pause(10);
    
    len = length(x_in);
    y_out = zeros(1,len);
    is_clipped_out = zeros(1,len);
    
    for ii=1:len
        data = x_in(ii);
        % call to the dti function
        init_val = 0;
        gain_val = 1;
        upper_limit = 500;
        lower_limit = -500;
        
        % call to the design that does DTI
        [y_out(ii), is_clipped_out(ii)] = dti(data);
        
    end
    
    figure('Name', [mfilename, '_plot']);
    subplot(2,1,1)
    plot(1:len,x_in)
    xlabel('Time')
    ylabel('Amplitude')
    title('Input Signal (Sin)')
    
    subplot(2,1,2)
    plot(1:len,y_out)
    xlabel('Time')
    ylabel('Amplitude')
    title('Output Signal (DTI)')
    
    disp('Test complete.');

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.

TypeNameDescription
Function codedti.mEntry-point MATLAB function
Test filedti_test.mMATLAB script that tests dti.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 dti to the project, browse to the file dti.m, and then click Open. By default, the app saves information and settings for this project in the current folder in a file named dti.prj.

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

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

Define Input Types

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

  2. Click Autodefine Input Types.

    The test file runs. The app determines from the test file that the input type of u_in is double(1x1).

  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. For more information, see View and Modify Variable Information.

    If functions are not supported for fixed-point conversion, the app displays them on the Function Replacements tab.

  2. Click the Analyze arrow .

    1. Select Analyze ranges using derived range analysis.

    2. Clear the Analyze ranges using simulation check box.

    Design ranges are required to use derived range analysis.

  3. On the Convert to Fixed Point page, on the Variables tab, for input u_in, select Static Min and set it to -1. Set Static Max to 1.

    To compute derived range information, at a minimum you must specify static minimum and maximum values or proposed data types for all input variables.

    Note

    If you 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.

  4. Click Analyze.

    Range analysis computes the derived ranges and displays them in the Variables tab. Using these derived ranges, the analysis proposes fixed-point types for each variable based on the default type proposal settings. The app displays them in the Proposed Type column.

    In the dti function, the clip_status output has a minimum value of -2 and a maximum of 2.

    % Compute Output
    if (u_state > limit_upper)
        y = limit_upper;
        clip_status = -2;
    elseif (u_state >= limit_upper)
        y = limit_upper;
        clip_status = -1;
    elseif (u_state < limit_lower)
    	y = limit_lower;
        clip_status = 2;
    elseif (u_state <= limit_lower)
    	y = limit_lower;
        clip_status = 1;   
    else        
        y = u_state;
        clip_status = 0;
    end
    

    When you derive ranges, the app analyzes the function and computes these minimum and maximum values for clip_status.

    The app provides a Quick derived range analysis option and the option to specify a timeout in case the analysis takes a long time. See Computing Derived Ranges.

  5. 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\dti\fixpt folder in your local working folder:

    • dti_fixpt.m — the fixed-point version of dti.m.

    • dti_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. The app feeds these fixed-point values into the converted fixed-point design, dti_fixpt.m.

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

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

    • dti_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, they show on the Output tab. See Validating Types.

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

  7. Use the Simulation Data Inspector to plot the floating-point and fixed-point results.

    1. Click the Settings arrow .

    2. Expand the Plotting and Reporting settings and set Plot with Simulation Data Inspector to Yes.

    3. Click the Test arrow . Select Log inputs and outputs for comparison plots. Click Test.

      The app 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 and to use the Simulation Data Inspector for these plots, the Simulation Data Inspector opens.

    4. You can use the Simulation Data Inspector to view floating-point and fixed-point run information and compare results. For example, to compare the floating-point and fixed-point values for the output y, select y. Click Compare. Set Baseline to the original run and Compare to to the converter run. Click Compare.

      The Simulation Data Inspector displays a plot of the baseline floating-point run against the fixed-point run and the difference between them.

  8. On the Verification Output tab, the app provides a link to the Fixed_Point Report.

    To open the report, click the dti_fixpt_report.html link.

  9. 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 dti_fixpt.m to your local working folder.

  2. To get the fimath properties for the input argument, look at the get_fimath function in dti_fixpt.m.

    function fm = get_fimath()
    	fm = fimath('RoundingMethod','Floor',...
            'OverflowAction','Wrap', ...
            'ProductMode','FullPrecision', ...
            'MaxProductWordLength',128,...
            'SumMode','FullPrecision',...
            'MaxSumWordLength',128);
    end
    

  3. To get the fixed-point data type for input u_in, look at the type proposal report.

  4. Generate a MEX function for dti_fixpt.m.

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

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

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