using parse to deal with input arguments
이전 댓글 표시
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
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
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
Martin
2015년 3월 16일
Thanks,
I should clarify that I want the default value (provided in the call to addOptional) to be used if I input [], like for example the way interp1 works. Note that interp1 does not use the inputparser but rather a specific parsing function written for interp1 (only?).
So, is there a way to get the default value for "empty" ([]) argument using the inputparser tools, or do I need to write my own?
Regards, Martin
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
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
카테고리
도움말 센터 및 File Exchange에서 Argument Definitions에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!