inputparser addOptional seems broken

12 vues (au cours des 30 derniers jours)
ErikJ GiesenLoo
ErikJ GiesenLoo le 27 Fév 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 commentaires
Morten Sparre Andersen
Morten Sparre Andersen le 27 Fév 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 le 27 Fév 2023
Modifié(e) : ErikJ GiesenLoo le 27 Fév 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

Connectez-vous pour commenter.

Réponses (1)

ErikJ GiesenLoo
ErikJ GiesenLoo le 27 Fév 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

Catégories

En savoir plus sur Argument Definitions dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by