inputparser addOptional seems broken

12 次查看(过去 30 天)
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 个评论
Morten Sparre Andersen
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 2023-2-27
编辑:ErikJ GiesenLoo 2023-2-27
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

请先登录,再进行评论。

回答(1 个)

ErikJ GiesenLoo
ErikJ GiesenLoo 2023-2-27
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

类别

Help CenterFile Exchange 中查找有关 Argument Definitions 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by