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.

Answers (1)

Jiro Doke
Jiro Doke on 25 Feb 2011
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 Comments

Thank you.
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. :-)
@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.

Sign in to comment.

Categories

Find more on Argument Definitions in Help Center and File Exchange

Asked:

on 25 Feb 2011

Community Treasure Hunt

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

Start Hunting!