Main Content

Replace a Custom Function with a Lookup Table

This example shows how to replace a custom function with a lookup table approximation function using the codegen function.

Prerequisites

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

Create a MATLAB function, custom_fcn.m. This is the function that you want to replace.

function y = custom_fcn(x)
  y = 1./(1+exp(-x));
end

Create a wrapper function that calls custom_fcn.m.

function y = call_custom_fcn(x)
  y = custom_fcn(x);
end

Create a test file, custom_test.m, that uses call_custom_fcn.m.

close all

x = linspace(-10,10,1e3);
for itr = 1e3:-1:1
   y(itr) = call_custom_fcn( x(itr) );
end
plot( x, y );

Create a function replacement configuration object to approximate custom_fcn. Specify the function handle of the custom function and set the number of points to use in the lookup table to 50.

q = coder.approximation('Function','custom_fcn','CandidateFunction',@custom_fcn, 'NumberOfPoints',50);

Create a coder.FixptConfig object, fixptcfg. Specify the test file name and enable numerics testing. Associate the function replacement configuration object with the fixed-point configuration object.

fixptcfg = coder.config('fixpt');
fixptcfg.TestBenchName = 'custom_test';
fixptcfg.TestNumerics = true;
fixptcfg.addApproximation(q);

Generate fixed-point MATLAB code.

codegen -float2fixed fixptcfg call_custom_fcn

codegen generates fixed-point MATLAB code in call_custom_fcn_fixpt.m.

To view the generated fixed-point code, click the link to call_custom_fcn_fixpt.

The generated code contains a lookup table approximation, replacement_custom_fcn, for the custom_fcn function. The fixed-point conversion process infers the ranges for the function and then uses an interpolated lookup table to replace the function. The lookup table uses 50 points as specified. By default, it uses linear interpolation and the minimum and maximum values detected by running the test file.

The generated fixed-point function, call_custom_fcn_fixpt, calls this approximation instead of calling custom_fcn.

function y = call_custom_fcn_fixpt(x)
  fm = get_fimath();

  y = fi(replacement_custom_fcn(x), 0, 14, 14, fm);
end

You can now test the generated fixed-point code and compare the results against the original MATLAB function. 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 code.