inputparser addOptional seems broken

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

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일

0 개 추천

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

카테고리

도움말 센터File Exchange에서 Argument Definitions에 대해 자세히 알아보기

태그

질문:

2023년 2월 27일

답변:

2023년 2월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by