Convert Code Containing Global Variables to Fixed-Point
This example shows how to convert a MATLAB® algorithm containing global variables to fixed point.
In a local writable folder, create the function
use_globals.m.function y = use_globals(u) %#codegen % Declare AR and B as global variables global AR; global B; AR(1) = u + B(1); y = AR * 2;
In the same folder, create a test file,
use_globals_tb.mthat calls the function.u = 55; global AR B; AR = ones(4); B=[1 2 3]; y = use_globals(u);At the command line, create a
coder.FixPtConfigobject, and specify the test bench asuse_globals_tb.m.fixptcfg = coder.config('fixpt'); fixptcfg.TestBenchName = 'use_globals_tb';
Convert
use_globalsto fixed point using thefiaccelfunction.The software generates the fixed-point code and issues a warning:fiaccel -float2fixed fixptcfg use_globals
Generate code again usingWarning: Global variable 'B' is not a constant and is not assigned in the design. If a global variable is used as a read-only variable, then consider making it a constant or insert the statement 'B=B;'. Global variables must be assigned to get a data type proposal.
fiaccel. Use the-globalsoption to defineBas a constant value and assignBfor type proposal.fiaccel -float2fixed fixptcfg use_globals -globals {'B', coder.Constant([1 2 3])} use_globals -args {0}
In the command window, click use_globals_fixpt to view the converted fixed-point function
In the generated fixed-point code, the global variable
ARis nowAR_g.The wrapper function contains three global variables:
AR,AR_g, andB, whereAR_gis set equal to a fi-castAR, andARis set equal to a double castAR_g. The global variableBdoes not have a separate variable in the fixed-point code because it is a constant.function y = use_globals_fixpt(u) %#codegen % Declare AR and B as global variables fm = get_fimath(); global AR_g; global B; AR_g(1) = fi(u + B(1), 0, 6, 0, fm); y = fi(AR_g * fi(2, 0, 2, 0, fm), 0, 7, 0, fm); end function fm = get_fimath() fm = fimath('RoundingMethod', 'Floor',... 'OverflowAction', 'Wrap',... 'ProductMode','FullPrecision',... 'MaxProductWordLength', 128,... 'SumMode','FullPrecision',... 'MaxSumWordLength', 128); end