Contenido principal

Convert Code Containing Global Variables to Fixed-Point

This example shows how to convert a MATLAB® algorithm containing global variables to fixed point.

  1. 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;

  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);

  3. At the command line, create a coder.FixPtConfig object, and specify the test bench as use_globals_tb.m.

    fixptcfg = coder.config('fixpt');
    fixptcfg.TestBenchName = 'use_globals_tb';
  4. Convert use_globals to fixed point using the fiaccel function.

    fiaccel -float2fixed fixptcfg use_globals
    The software generates the fixed-point code and issues a warning:
    Warning: 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. 
    Generate code again using fiaccel. Use the -globals option to define B as a constant value and assign B for type proposal.

    fiaccel -float2fixed fixptcfg use_globals -globals {'B', coder.Constant([1 2 3])} use_globals -args {0}
  5. In the command window, click use_globals_fixpt to view the converted fixed-point function

    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-cast AR, and AR is set equal to a double cast 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