Problem with addOptional

I'm writing a function that has 5 arguments, only one of which is required. So, I'm using a parser and adding the required argument and the optional arguments. It looks something like this:
p = inputparser;
validateN = @(x)validateattributes(x, {'numeric'},{'scalar', 'integer', 'positive', 'even', '>=', 2});
validateInteger = @(x)validateattributes(x, {'numeric'},{'scalar', 'integer'});
validateP = @(x)validateattributes(x, {'numeric'},{'scalar', 'integer', '>=', 1, '<=', N+1});
p.addRequired('N', validateN);
p.addOptional('u', 1, validateInteger);
p.addOptional('t', 1, validateInteger);
p.addOptional('p', 1, validateP);
p.parse(N, varargin{:});
fprintf('\n');
disp 'List of all arguments:';
disp(p.Results);
The output of which is:
List of all arguments:
N: (whatever's been passed)
u: 1
t: 1
p: 1
However, when the program continues to run, it errors out saying that variables, which I assume addOptional declares with the default value, don't exist. Am I misunderstanding how the addOptional works? Or, am I doing something wrong? It would be nice to not have to have if statements for each possible nargin.

답변 (1개)

Jiro Doke
Jiro Doke 2011년 2월 25일

2 개 추천

Those variable u, t, and p are available as fields of p.Results. So if you need to use them in the rest of the program, refer to them as those fields, or add this after your block of code above:
u = p.Results.u;
t = p.Results.t;
p = p.Results.p;

댓글 수: 3

Derik Rudd
Derik Rudd 2011년 2월 25일
Thank you.
Andrew Davis
Andrew Davis 2011년 2월 25일
p = p.Results.p;
this seems potentially problematic to me! Maybe |args = inputparser;| instead? Then |p = args.Results.p;|, and I'll be able to sleep at night. :-)
Jiro Doke
Jiro Doke 2011년 2월 25일
@Andrew: Good point. While MATLAB will work fine as above, it could lead to unexpected mistakes. For instance, if I switch the order of those commands, I could get an error.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Argument Definitions에 대해 자세히 알아보기

질문:

2011년 2월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by