我正在尝试开发一个包含多个参数的函数。为了尽可能健壮,我希望能够按如下方式调用我的函数:
foo( x, y, z, 'OptionalArg1', bar, 'OptionalArg2', blah, 'OptionalArg3', val )
我希望我的函数足够健壮,可以按任何顺序包含这些参数的任意组合。如果没有提供参数,我还需要能够设置默认值。在MATLAB中有一种标准的方法吗?
最好的方法是使用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
。
但inputParser
更容易使用,更清晰。