inputparser addOptional seems broken

12 visualizaciones (últimos 30 días)
ErikJ GiesenLoo
ErikJ GiesenLoo el 27 de Feb. de 2023
Respondida: ErikJ GiesenLoo el 27 de Feb. de 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 comentarios
Morten Sparre Andersen
Morten Sparre Andersen el 27 de Feb. de 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 el 27 de Feb. de 2023
Editada: ErikJ GiesenLoo el 27 de Feb. de 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

Iniciar sesión para comentar.

Respuestas (1)

ErikJ GiesenLoo
ErikJ GiesenLoo el 27 de Feb. de 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

Categorías

Más información sobre Argument Definitions en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by