using parse to deal with input arguments

11 次查看(过去 30 天)
Pieter
Pieter 2012-10-24
评论: Martin 2015-3-16
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 个评论
Martin
Martin 2015-3-16
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

请先登录,再进行评论。

回答(1 个)

Adam
Adam 2015-3-16
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 个评论
Adam
Adam 2015-3-16
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 2015-3-16
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

请先登录,再进行评论。

类别

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