using parse to deal with input arguments

8 ビュー (過去 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 Center および File ExchangeArgument Definitions についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by