Replace the exp
Function with a Lookup
Table
This example shows how to replace the exp
function
with a lookup table approximation in the generated fixed-point code
using the codegen
function.
Prerequisites
To complete this example, you must install the following products:
MATLAB®
MATLAB Coder™
Fixed-Point Designer™
C compiler
See Supported Compilers.
You can use
mex -setup
to change the default compiler. See Change Default Compiler.
Create Algorithm and Test Files
Create a MATLAB function,
my_fcn.m
, that calls theexp
function.function y = my_fcn(x) y = exp(x); end
Create a test file,
my_fcn_test.m
, that usesmy_fcn.m
.close all x = linspace(-10,10,1e3); for itr = 1e3:-1:1 y(itr) = my_fcn( x(itr) ); end plot( x, y );
Configure Approximation
Create a function replacement configuration object to approximate
the exp
function, using the default settings of
linear interpolation and 1000 points in the lookup table.
q = coder.approximation('exp');
Set Up Configuration Object
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 = 'my_fcn_test'; fixptcfg.TestNumerics = true; fixptcfg.DefaultWordLength = 16; fixptcfg.addApproximation(q);
Convert to Fixed Point
Generate fixed-point MATLAB code.
codegen -float2fixed fixptcfg my_fcn
View Generated Fixed-Point Code
To view the generated fixed-point code, click the link to my_fcn_fixpt
.
The generated code contains a lookup table approximation, replacement_exp
,
for the exp
function. 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.
The generated fixed-point function, my_fcn_fixpt
,
calls this approximation instead of calling exp
.
function y = my_fcn_fixpt(x) fm = get_fimath(); y = fi(replacement_exp(x), 0, 16, 1, 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.