Main Content

Convert Identical Functions Called with Different Data Types

This example shows how to convert a MATLAB® algorithm containing specialized functions to fixed point using automated fixed-point conversion. Each instance of the specialized function can have a different data type after conversion. This example uses the MATLAB Coder™ codegen command. You can also perform the conversion using fiaccel.

  1. In a local writable folder, create the function mtictac.m. The input is a Tic-Tac-Toe game board. The output is the winning player. The output is 0 if there is no winner.

    function a = mtictac(b)
    % Input is a Tic-Tac-Toe board.
    % The output is the winning player 
    % or zero if none.
    
    %   Copyright 2022 The MathWorks, Inc.
    
    for i = 1:3
        a = winner(b(i,:));
        if a > 0
            return;
        end
        a = winner(b(:,i));
        if a > 0
            return;
        end
    end
    
    a = winner(diag(b));
    if a>0
        return;
    end
    
    a = winner(diag(flip(b)));

  2. In the same folder, create the function, winner.m. The winner.m function is called by the function mtictac.m.

    function a = winner(b)
    
    %   Copyright 2022 The MathWorks, Inc.
    
    x = mean(b);
    
    if x <= - 1
        a = 1;
    elseif x >= 1
        a = 2;
    else
        a = 0;
    end

  3. In the same folder, create a test file, mtictac_test.m, that calls the mtictac function.

    mtictac([-1 0 0; 0 -1 0; 0 0 0]);
    mtictac([1 0 0; 0 1 0; 0 0 1]);
    mtictac([0 0 -1; 0 0 -1; 0 0 -1]);
    

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

    fixptcfg = coder.config('fixpt');
    fixptcfg.TestBenchName = 'mtictac_test';
  5. Generate fixed-point code for mtictac.m

    codegen -float2fixed fixptcfg mtictac
  6. When code generation is complete, click View report in the command window.

  7. Observe that the data types for each individual call of the winner function are customized to use different data types.

    The code generation report displays two versions of the converted winner function. Each function has a different fixed-point data type.