Parse function parameters using InputParser class with unknown number of parameters and optional name-value pairs parameters
Show older comments
Hi Community,
What would it be the right way to parse a function with inputParser class that accepts an aribitrary number of parameters assigned through the usual varargin with some optional name-value pairs parameters?
This example showing two different function calls of vprintf should illustrate the problem:
verbosity = 2;
vprintf(verbosity, "onNewLine", true, "this is a string: '%s', and this is a number: '%g'\n", "tuna" , 100.1);
vprintf(verbosity, "this is a string: '%s', and this is a number: '%g'\n", "tuna" , 100.1);
where:
- verbosity is mandatory,
- onNewLine name with its following value true are optional ,
- and everything after is essentially optional.
This crude attempt did't work because the parser seems to accept name-value pairs arguments only:
function vprintf(verbosity, varargin)
p = inputParser;
addOptional(p,'onNewLine', 0);
parse(p, varargin{:});
disp(p.Results);
end
And it gives the following error
vprintf(1,"onNewLine", true, "aaaaaaaaaaa");
Error using vprintf (line 4)
'aaaaaaaaaaa' is not a recognized parameter.
Accepted Answer
More Answers (2)
Hi,
From my understanding, you want to use a variable number of optional parameters without having explicitly declared them in the input parser. And you want these arbitrary number of parameters assigned through the “varargin” functionality.
The “KeepUnmatched” property of the “inputParser” is a matching indicator that throws an error when an input is not found in the input parser scheme. By default, the parse function throws an error if an input argument name does not match one defined in the input parser scheme.
To suppress the error and store the input argument name and value, set “KeepUnmatched” to “true” (or “1”). The “inputParser” object stores unmatched input argument names and values in the “Unmatched” property. Refer to this link for more details about this property - https://www.mathworks.com/help/matlab/ref/inputparser.html#:~:text=KeepUnmatched%20%E2%80%94%20Matching%20indicator.
Here is some example code to illustrate this functionality –
function p = vprintf(verbosity, varargin)
p = inputParser;
p.KeepUnmatched=true;
addOptional(p,'onNewLine', 0);
parse(p, varargin{:});
disp("Result property")
disp(p.Results)
disp("Unmatched property")
disp(p.Unmatched);
end
p = vprintf(1,"onNewLine", true, "aaaaaaaaaaa", 6);
For additional reference please, refer to this MATLAB Answer post that discusses the “KeepUnmatched” property in detail - https://www.mathworks.com/matlabcentral/answers/395295-allowing-unknown-parameters-in-an-inputparser.
Hope this helps!
1 Comment
Bob Randall
on 28 Oct 2024
Categories
Find more on Argument Definitions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!