inputParser with only a value, not a name-value pair

17 ビュー (過去 30 日間)
Gregory Dachner
Gregory Dachner 2018 年 7 月 13 日
コメント済み: Fangjun Jiang 2018 年 7 月 18 日
Is it possible to use inputParser with only a value, not a name-value pair. So that when you send a function a specific argument, the argument is automatically set to a variable, without a variable name needed to be given in the function call?
Instead of
a = findArea(13,'shape','square');
You could just send findArea 'square', like:
a = findArea(13,'square');
And within the function, it would recognize that square can only be a shape and set shape's value to 'square'.

回答 (1 件)

Fangjun Jiang
Fangjun Jiang 2018 年 7 月 13 日
Yes. You would make that a required argument, not an optional argument.
function a = findArea(width,Shape,varargin)
....
addRequired(p,'shape',defaultShape,... @(x) any(validatestring(x,expectedShapes)));
  2 件のコメント
Gregory Dachner
Gregory Dachner 2018 年 7 月 17 日
I'm not sure what you expect this to do, but it breaks the function, causes all inputs to return the error:
Error using inputParser/addRequired Too many input arguments.
Fangjun Jiang
Fangjun Jiang 2018 年 7 月 18 日
should be
addRequired(p,'shape', @(x) any(validatestring(x,expectedShapes)));

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

タグ

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by