This example shows how to convert a MATLAB® algorithm containing global variables to fixed point using the Fixed-Point Converter app.
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.m
that
calls the function.
u = 55;
global AR B;
AR = ones(4);
B=[1 2 3];
y = use_globals(u);
On the MATLAB toolstrip, in the Apps tab, under Code Generation, click the Fixed-Point Converter app icon.
To add the entry-point function, use_globals.m
to
the project, on the Select Source Files page,
browse to the file, and click Open. Click Next.
On the Define Input Types page, add use_globals_tb.m
as
the test file. Click Autodefine Input Types.
The app determines from the test file that the input type of
the input u
is double(1x1)
.
Select Yes next to Does
this code use global variables. By default, the Fixed-Point
Converter app names the first global variable in a project g
.
Type in the names of the global variables in your code.
In the field to the right of the global variable AR
,
specify its type as double(4x4)
.
The global variable B
is not assigned
in the use_globals
function. Define this variable
as a global constant by clicking the field to the right of the constant
and selecting Define Constant Value
. Type
in the value of B
as it is defined in the test
file, [1 2 3]
. The app indicates that B
has
the value[1 2 3]
. The app indicates that AR
is
not initialized.
Click Next. The app generates an instrumented MEX function for your entry-point MATLAB function. On the Convert to Fixed-Point page, click Simulate to simulate the function, gather range information, and get proposed data types.
Click Convert to accept the proposed data types and convert the function to fixed-point.
In the generated fixed-point code, the global variable AR
is
now AR_g
.
The wrapper function contains three global variables: AR
, AR_g
,
and B
, where AR_g
is set equal
to a fi-casted AR
, and AR
is
set equal to a double casted AR_g
. The global variable B
does
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