Contenu principal

Convert Code Containing Structures to Fixed Point

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

  1. In a local writable folder, create the function struct_fcn.m

    function [out, y] = struct_fcn(in)
        % create a nested struct
        z = struct('prop1', struct('subprop1', 0, 'subprop2', [3 4 45]));
        % copy over the struct
        y = z;
        y.prop1.subprop1 = y.prop1.subprop1 + in;
        out = y.prop1.subprop1;
    end

  2. In the same folder, create a test file, struct_fcn_tb.m, that calls the function.

    for ii = 1:10
        struct_fcn(ii);
    end

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

    fixptcfg = coder.config('fixpt');
    fixptcfg.TestBenchName = 'struct_fcn_tb';
  4. Generate fixed-point code for struct_fcn.m

    fiaccel -float2fixed fixptcfg struct_fcn
    Since no input types are specified, the fixed-point conversion process simulates the test bench to infer types. To specify input types, use the -args option when you enter the fiaccel command.

  5. The automated fixed-point conversion process uses the test bench to simulate the function, gather range information, and propose data types. After fixed-point conversion is complete, in the command window, click struct_fcn_report.html to inspect the fixed-point data types.

    When the names, number, and types of fields of two or more structures match, automated fixed-point conversion proposes a unified type. In this example, the range of z.prop1.subprop1 is [0,0], while the range of y.prop1.subprop1 is [0,10]. The app proposes a data type of numerictype(0,4,0) for both z.prop1.subprop1 and y.prop1.subprop1 based on the union of the ranges of the two fields.

    The fixed-point report for struct_fcn displays a table with the names and data types of the variables in the function after fixed-point conversion.

  6. Click View Report to see the project summary details and links to the fixed-point MATLAB code and conversion report.