I am trying to understand the Matlab inputParser
, as it seems from previous questions people deem it best practice to use this class for validating inputs to a function. Therefore, I am fooling around with it a little and I've written the following function.
function output = inputParseTester(reqArg, varargin)
parser = inputParser;
addRequired(parser, 'reqArg')
addOptional(parser, 'posArg', NaN)
addParameter(parser, 'kwArg', NaN)
parse(parser, reqArg, varargin{:})
reqArg = parser.Results.reqArg;
posArg = parser.Results.posArg;
kwArg = parser.Results.kwArg;
output = {reqArg, posArg, kwArg};
end
Given the previous function, why is the positional argument accepted when I input a numeric value, but why is posArg
not accepted when it's being input as a string
or char
array? I haven't defined any validation function at this point, and I might want posArg
to be a non-numeric variable, right?
>> inputParseTester('arg1', 2, 'kwArg', 2)
ans =
1×3 cell array
{'arg1'} {[2]} {[2]}
>> inputParseTester('arg1', 'posArg', 'arg2', 'kwArg', 2)
ans =
1×3 cell array
{'arg1'} {'arg2'} {[2]}
>> inputParseTester('arg1', 'arg2', 'kwArg', 2)
Error using inputParseTester (line 7)
The argument 'arg2' is a string scalar or character vector and does not match any parameter names. It failed validation for the argument 'posArg'.
Given this outcome, I'd think that addOptional
does the same as addParameter
, except for adding some unwanted and undefined validation. This is probably not the case, so what is happening?
While by no means intuitive, you observe the behavior as documented:
For optional string arguments, specify a validation function. Without a validation function, the input parser interprets a string argument as an invalid parameter name and throws an error.
https://mathworks.com/help/matlab/ref/inputparser.addoptional.html