Replace Functions in a MATLAB Function Block with a Lookup Table

This example shows how to replace a function that is used inside a MATLAB® Function block, with a more efficient implementation. The following model contains a MATLAB Function block which computes the sine of the input. Use the Code View to replace the built-in sin function with a lookup table.

Change directories to the folder where the model is located. At the MATLAB command line, enter:

cd(fullfile(docroot,'toolbox','fixpoint','examples'))

Copy and save the ex_mySin.slx file to a local writable folder and open the model.

function y = my_sin(u)
%#codegen
y = sin(u);
  1. To open the Fixed-Point Tool, in the Apps tab, expand the Apps gallery and select Fixed-Point Tool

  2. In the Fixed-Point Tool, under System Under Design (SUD), select the model ex_mySin as the system to convert.

  3. Under Range Collection Mode, select Simulation ranges as the method of range collection. This configures the model to collect ranges using idealized floating-point data types.

  4. In the Prepare System section of the toolstrip, click Prepare.

  5. Click the Collect Ranges button to start the simulation

    The Fixed-Point Tool stores the simulation data in a run titled Ranges(Double). Examine the range information of the MATLAB variables in the spreadsheet.

  6. To launch the code view, in the Convert Data Types section of the toolstrip, click MATLAB Functions.

  7. Select the Function Replacements tab.

  8. Enter the name of the function you want to replace. For this example, enter sin. Select Lookup Table, and then click .

    The fixed-point conversion process infers the ranges for the function and then uses an interpolated lookup table to replace the function. By default, the lookup table uses linear interpolation, 1000 points, and the minimum and maximum values detected by running the test file.

  9. Click Propose to get data type proposals for the variables.

  10. Click Apply to apply the data type proposals and generate a fixed-point lookup table.

    If the behavior of the generated fixed-point code does not match the behavior of the original code closely enough, modify the interpolation method or number of points used in the lookup table and then regenerate the fixed-point code.

  11. Return to the Fixed-Point Tool. In the Verify section of the toolstrip, click the Simulate with Embedded Types button to simulate the model using the newly applied fixed-point data types. The model simulates with the fixed-point variant as the active variant.

Related Topics