puzzles on using mutiple "addOptional" in function definitions

14 次查看(过去 30 天)
How to use multiple addOptional in function definitions? addOptional is to add positional arguments. So I want to use it in the following way.
  • First I define the function and use two addOptional there.
  • Then I thought I can call in the following two ways: myfunc('Jim', 12) and myfunc('Jim', 12, 'cm').However, the latter one throws an error:
The argument 'cm' is a string and does not match any parameter names. It failed validation for the argument 'units'.
But I can use as myfunc('Jim', 12, 'units', 'cm'), which seems the second addOptional behaves as addParameter, no longer like positional arguments. What's the mistake I made? Did I misunderstand something about addOptional? Many thanks!
Here is the definition of myfunc():
function myfunc(name, varargin)
par = inputParser;
defaultHeight = 1;
defaultUnits = 'inches';
defaultShape = 'rectangle';
expectedShape = {'square', 'rectangle', 'parallelogram'};
addRequired(par, 'name', @ischar);
addOptional(par, 'height', defaultHeight, @isnumeric);
addOptional(par, 'units', defaultUnits);
% addParameter(par, 'shape', defaultShape, ...
% @(x) any(validatestring(x,expectedShape)));
parse(par, name, varargin{:});
disp(par.Results)
---------
Updates:
I found that if the positional arguments are NOT literal string (maybe called as character array in helpdoc, the type shown by whos is char, e.g. 'any words'), there would be no problems. For example, use myfunc('Jim', 3, 4) which is defined as
function myfunc(name, varargin)
p = inputParser;
addRequired(p, 'name');
addOptional(p, 'i', 1);
addOptional(p, 'j', 2);
parse(p, name, varargin{:});
disp(p.Results)
The MATLAB help doc doesn't mention anything about the limitations in data types of additional positional arguments. Does it imply this is a bug?
Info:
  • MATLAB: 2016a
  • OS: OS X Sierra

回答(1 个)

Zhe Chen
Zhe Chen 2024-6-28,17:29
编辑:Zhe Chen 2024-7-1,2:43
I am having the exact same issue.
I think the official help document neglects two things:
1): The optional positional arguments can be called like a name-value argument.
myfunc('Jim', 12, 'units', 'cm') or myfunc('Jim', 12, units='cm')
2): If the value assigned to optional positional argument is a char vector or a string, it will not considered as an optional positional argument if there is no validation function for the optional argument.
3): In the case you have a validation function for the optional argument, if the input value pass the validation check, it will be considered as an optional argument. If the input value does not pass the validation check, it will be considered as a name-value parameter, as in case 2.

类别

Help CenterFile Exchange 中查找有关 Argument Definitions 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by