The InputParser class addresses all of these issues. You can specify any number:
- Required parameters (ordered, unlabeled)
- Additional parameters (ordered, unlabeled)
- Parameter value of a pair of lines 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 is as follows.
Create an InputParser :
p = inputParser;
Specify default values ββ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 the required / optional / names of input parameters, 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 in a struct:
parse(p,filename,varargin{:});
Then you have the input arguments and their values ββin p.Results .
The InputParser class InputParser used in all of the new MathWorks features, so don't be afraid to use it yourself!