using parse to deal with input arguments

11 visualizaciones (últimos 30 días)
Pieter
Pieter el 24 de Oct. de 2012
Comentada: Martin el 16 de Mzo. de 2015
Using R2008a, I created the following function:
function output = lm_applySAPO(Si, So, varargin)
p=inputparser;
p.addOptional('Si', 0.85, @(x) isscalar(x))
% parse(p, Si)
p.addOptional('So', 0.98, @(x) isscalar(x) && gt(x, p.Results.Si))
parse(p, Si, So)
output.Si = p.Results.Si;
output.So = p.Results.So;
end
Now when I call the function, I want to be able to call it with empty inputarguments for Si or So. As follows:
result = lm_applySAPO([] , 0.99)
This throws the following error message:
Error using lm_applySAPO (line 8)
Argument 'Si' failed validation @(x)isscalar(x).
My questions are as follows:
How can I use the inputparser object in combination with no values (using [ ]) for certain variables? I would really like to use [ ] when i can't provide a value for the input variable.
For the second addOptional I use p.Results.Si. This field in the struct seems already available without parsing the input (parse(p, Si) is commented). How is this possible?
Thanks,
  1 comentario
Martin
Martin el 16 de Mzo. de 2015
Does this question have an answer yet?
I also would like to be able to call functions using inputparser with "empty" arguments, like in the call max([1 2;3 4],[],2).
Regards, Martin

Iniciar sesión para comentar.

Respuestas (1)

Adam
Adam el 16 de Mzo. de 2015
Does it not work to just replace
isscalar(x)
with something like
validationFcn = @(x) isempty(x) || isscalar(x);
p.addOptional('Si', 0.85, @(x) validationFcn (x));
to deal with empty inputs?
  3 comentarios
Adam
Adam el 16 de Mzo. de 2015
As far as I can see this is not possible with the builtin options for the inputparser though I may be wrong. I have looked at it numerous times, but have never actually used it as I don't generally have functions with varargin inputs.
You could do a post-parser check of attributes to assign defaults to any that are empty, but that is not especially neat I admit.
Martin
Martin el 16 de Mzo. de 2015
Yes, did a hack to get this functionality. I simply did a setdiff "between" all fieldnames in p.Results and p.UsingDefaults to get the fields having values supplied using varargin. Then I looped over those and reset the empty ones to the default values. Problem solved.
Thanks, Martin

Iniciar sesión para comentar.

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