inputParser
Parses and validates the arguments of a function.
Category: Programming > Functions
Syntax
p = inputParser
Creates an empty parser object.
parse(p, args...)
Matches args against the declared arguments and fills p.Results.
p.Results, p.UsingDefaults, p.Unmatched
Read the parsed values, the names left at their defaults, and the unrecognized pairs.
Description
An inputParser is a handle object. You declare the arguments with addRequired, addOptional and addParameter, then call parse(p, varargin{:}) inside your function. Required arguments are positional and must come first, optional ones follow, and name-value pairs come last.
A failed validation raises an error that names the argument and the validation function. p.Results lists fields in alphabetical order, p.UsingDefaults names the arguments that were not supplied, and p.Unmatched holds the unrecognized pairs when KeepUnmatched is on.
Input arguments
FunctionName- Property: name shown in error messages.
CaseSensitive- Property: match parameter names with case (default
false). KeepUnmatched- Property: when
true, unknown name-value pairs go toUnmatchedinstead of causing an error (defaultfalse). PartialMatching- Property: accept unique abbreviations of parameter names (default
true). StructExpand- Property: accept a struct in place of name-value pairs (default
true).
Output arguments
p- The parser object. After
parse,p.Resultsis a struct with one field per declared argument.
Example
Required, optional and name-value arguments
p = inputParser;
p.FunctionName = 'demo';
addRequired(p, 'n', @isnumeric);
addOptional(p, 'mode', 'fast', @ischar);
addParameter(p, 'Tol', 1e-3, @(x) x > 0);
parse(p, 4, 'slow', 'Tol', 0.1);
r = p.Results
p.UsingDefaults
try
parse(p, 4, 'fast', 'Tol', -1);
catch err
disp(err.message)
end
r = struct with fields:
Tol: 0.1000
mode: 'slow'
n: 4
ans =
0×0 empty cell array
The value of 'Tol' is invalid. It must satisfy the function: @(x)x>0.
Notes
MatLivre does not provide addSwitch.