inputparser addOptional seems broken

12 views (last 30 days)
ErikJ GiesenLoo
ErikJ GiesenLoo on 27 Feb 2023
Answered: ErikJ GiesenLoo on 27 Feb 2023
It seems that if I use addOptional I cannot skip arguments
For example, if I wish to have an optional array but I simply pass a color (e.g., 'g') it will always throw 'The Value of 'Yu' is invalid. It must satisfy ...' Is there no way to have real optional arguments like in e.g. Python?
p = inputParser();
p.addOptional('Yu', [], @(x) isnumeric(x) && numel(x) > 3)
p.addOptional('Color', 'r', @(x) ischar(x) || isstring(x) || (isnumeric(x) && numel(x) <= 4))
p.KeepUnmatched = true;
p.parse(varargin{:})
  2 Comments
Morten Sparre Andersen
Morten Sparre Andersen on 27 Feb 2023
If you define several optional arguments to an inputParser, then Matlab relies on argument order, so you can't assign 'Color' without having assigned 'Yu'.
You could use named parameters (with the addParameter method).
good luck
Morten
ErikJ GiesenLoo
ErikJ GiesenLoo on 27 Feb 2023
Edited: ErikJ GiesenLoo on 27 Feb 2023
Thanks. I think that answers my question. I had a plotting function that took a mean and standard deviation to plot a line and patch (based on the s.dev) and wanted a similar function to plot a central value, and a patch made of a lower bound (yl - which could be interpreted as the lower bound or s.dev depending on whether yu is empty) and upper bound (yu) but felt it would be good to have this be part of that same function, but also without breakding backwards compatibility (i.e. without having to pass an empty array).
Edit: I guess for my use case, I could just take in varargin and check what is inside

Sign in to comment.

Answers (1)

ErikJ GiesenLoo
ErikJ GiesenLoo on 27 Feb 2023
its always a bit strange to answer your own question, but here's the code to take 1 or 2 optional parameters
assert(numel(varargin) > 1)
yu = varargin{1};
if ~(isnumeric(yu) && numel(yu) > 3)
yu = []; c = varargin{1};
varargin = varargin(2:end);
else
c = varargin{2};
varargin = varargin(3:end);
end

Categories

Find more on Argument Definitions in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!