Problem with addOptional
3 ビュー (過去 30 日間)
古いコメントを表示
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.
0 件のコメント
回答 (1 件)
Jiro Doke
2011 年 2 月 25 日
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 件のコメント
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
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.
参考
カテゴリ
Help Center および File Exchange で Argument Definitions についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!