Functions with a flexible list of ordered/unordered and labeled/unlabeled inputs in MATLAB

后端 未结 1 1164
一向
一向 2020-12-06 08:03

A lot of MATLAB functions have an input structure such as:

output = function MyFun(a,b,c,\'-setting1\',s1,\'-setting2\',s2,\'-setting3\',s3)
<
相关标签:
1条回答
  • 2020-12-06 08:23

    The InputParser class addresses all of these issues. You can specify any number of:

    1. Required parameters (ordered, unlabeled)
    2. Optional parameters (ordered, unlabeled)
    3. String parameter-value pairs in any order (unordered, labeled)

    A very clear tutorial with examples is provided by MathWorks. For a function defined as function printPhoto(filename,varargin), the example boils down to the following.

    Create the inputParser:

    p = inputParser;
    

    Specify defaults and define validation criteria:

    defaultFinish = 'glossy';
    validFinishes = {'glossy','matte'};
    checkFinish = @(x) any(validatestring(x,validFinishes));
    
    defaultColor = 'RGB';
    validColors = {'RGB','CMYK'};
    checkColor = @(x) any(validatestring(x,validColors));
    
    defaultWidth = 6;
    defaultHeight = 4;
    

    Define required/optional/parameter input names, set their default values and validation functions:

    addRequired(p,'filename',@ischar);
    addOptional(p,'finish',defaultFinish,checkFinish);
    addOptional(p,'color',defaultColor,checkColor);
    addParameter(p,'width',defaultWidth,@isnumeric);
    addParameter(p,'height',defaultHeight,@isnumeric);
    

    Parse the inputs into a struct:

    parse(p,filename,varargin{:});
    

    Then you have the input arguments and their values in p.Results.

    The InputParser class is used throughout newer MathWorks functions, so don't be afraid to use it yourself!

    0 讨论(0)
提交回复
热议问题