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

烈酒焚心 提交于 2019-11-27 23:16:59

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!