The InputParser
class addresses all of these issues. You can specify any number of:
- Required parameters (ordered, unlabeled)
- Optional parameters (ordered, unlabeled)
- 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!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…