最好的方法是使用
inputParser
类,具有
addParameters
作用
简而言之,您的代码如下所示:
function foo(x,y,z,varargin)
p=inputParser;
validationFcn=@(x)isa(x,'double')&&(x<5); % just a random example, add anything
addParameter(p,'OptionalArg1',defaultvalue, validationFcn);
% same for the other 2, with your conditions
%execute
parse(p,varargin{:});
% get the variables
bar=p.Results.OptionalArg1;
% same for the other 2
% foo
或者,你可以像我一样写你自己的(
example here
)。那里的代码很容易修改,以便拥有自己的输入解析器(您只需更改
opts
,并添加
switch
对于每个新的
opt
。
但是
输入解析器
使用起来更简单、更清晰。