MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1
defaultColor = 'RGB';
validColors = {'RGB','CMYK'};
checkColor = @(x) any(validatestring(x,validColors));

defaultWidth = 6;
defaultHeight = 4;

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

Inputs that you add with addRequired or addOptional are positional arguments. When
you call a function with positional inputs, specify those values in the order they are added
to the parsing scheme.

Inputs added with addParameter are not positional, so you can pass values for height
before or after values for width. However, parameter value inputs require that you pass
the input name ('height' or 'width') along with the value of the input.

If your function accepts optional input strings or character vectors and parameter name
and value pairs, specify validation functions for the optional inputs. Otherwise, the Input
Parser interprets the optional strings or character vectors as parameter names. For
example, the checkFinish validation function ensures that printPhoto interprets
'glossy' as a value for finish and not as an invalid parameter name.

Step 4. Set properties to adjust parsing (optional).

By default, the Input Parser makes assumptions about case sensitivity, function names,
structure array inputs, and whether to allow additional parameter names and values that
are not in the scheme. Properties allow you to explicitly define the behavior. Set
properties using dot notation, similar to assigning values to a structure array.

Allow printPhoto to accept additional parameter value inputs that do not match the
input scheme by setting the KeepUnmatched property of the Input Parser.

p.KeepUnmatched = true;

If KeepUnmatched is false (default), the Input Parser issues an error when inputs do
not match the scheme.

21 Function Arguments

Free download pdf