## Propose Fixed-Point Data Types Based on Simulation Ranges

This example shows how to propose fixed-point data types based on simulation range data using the MATLAB® Coder™ app.

### Prerequisites

This example requires the following products:

• MATLAB

• MATLAB Coder

• Fixed-Point Designer™

• C compiler

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

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

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 code`ex_2ndOrder_filter.m`Entry-point MATLAB function
Test file`ex_2ndOrder_filter_test.m`MATLAB script that tests `ex_2ndOrder_filter.m`

### Open the MATLAB Coder 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

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

### Enable Fixed-Point Conversion

1. Set Numeric Conversion to ```Convert to fixed point```. 2. Click to go to the Define Input Types step.

The app screens `ex_2ndOrder_filter.m` for code violations and code generation 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 .

2. Click .

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 to go to the Check for Run-Time Issues step.

### Check for Run-Time Issues

The Check for Run-Time Issues step generates instrumented MEX. It runs the test file `ex_2ndOrder_filter_test` replacing calls to `ex_2ndOrder_filter` with calls to the generated MEX function. If the app finds issues, it provides warning and error messages. You can click a message to highlight the problematic code in a window where you can edit the code.

1. On the Check for Run-Time Issues page, the app populates the test file field with `ex_2ndOrder_filter_test`, the test file that you used to define the input types.

2. Click .

The app does not detect issues.

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

### Convert to Fixed Point

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

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 arrow . Select Log inputs and outputs for comparison plots, and then click . 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 to go to the Generate Code page.

### Generate Fixed-Point C Code

1. In the dialog box, set Build source to `Fixed-Point` and Build type to `Static Library`.

2. Set Language to C.

3. Click 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/ex_2ndOrder_filter`.

4. The app displays the generated code for `ex_2ndOrder_filter.c`. In the generated C code, variables are assigned fixed-point data types.

5. Click to go to the Finish Workflow page.

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