MATLAB: How to “use structures for function arguments”

function argumentsMATLABstructures

The MATLAB Stye Guidelines 2.0 (Johnson 2014) contains the following advice:
Use structures for function arguments.
Usability of a function decreases as the number of arguments grows, especially when some arguments are optional. Consider using structures whenever arguments lists exceed three.
Structures can allow a change to the number of values passed to or from the function that is compatible with existing external code.
Structures can remove the need for arguments to be in fixed order. Structures can be more graceful for optional values than having a long and ordered list of variables.
—–
I don't know how to implement this advice!
If I have
function [y1,y2] = myfun(x1,x2,text1,cmap1,cmap2,cmap3,cmapA,...
cmapH,text2,x3,x4,x5)
end
how do I put all those real variables (x's), integer arrays of various dimensions, character arrays, etc. into a structure?
How would doing this "allow a change to the number of values passed" or "remove the need for arguments to be in a fixed order"?

Best Answer

  • Try this
    S.x1 = 17 ;
    S.x2 = 18 ;
    S.text1 = 'ABC';
    S.cmap1 = magic(3);
    S.cmap2 = magic(3);
    S.cmap3 = magic(3);
    S.cmapA = magic(3);
    S.cmapH = magic(3);
    S.text2 = 'DEF';
    S.x3 = 19 ;
    S.x4 = 20 ;
    S.x5 = 21 ;
    %

    [y1,y2] = myfun( S );
    %
    function [y1,y2] = myfun( S )
    if not( isfield( S, 'cmapB' ) )
    S.cmapB = rand(3); % default value
    end
    y1 = S.x1;
    y2 = S.x2;
    end