Problem with addOptional
Afficher commentaires plus anciens
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.
Réponses (1)
Jiro Doke
le 25 Fév 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 commentaires
Derik Rudd
le 25 Fév 2011
Andrew Davis
le 25 Fév 2011
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
le 25 Fév 2011
@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.
Catégories
En savoir plus sur Argument Definitions dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!