我有一个函数,我想通过varargin传递参数,并使用inputParser确保输入是理智的.有些论据是必需的,有些则不是.这是一个例子:

function myFunc(varargin)

p = inputParser;

p.addRequired(...

'numStates', ...

@(x) validateattributes(x, {'numeric'}, ...

{'scalar', 'integer', 'positive'}));

p.addRequired(...

'numInps', ...

@(x) validateattributes(x, {'numeric'}, ...

{'scalar', 'integer', 'positive'}));

p.addRequired(...

'numOuts', ...

@(x) validateattributes(x, {'numeric'}, ...

{'scalar', 'integer', 'positive'}));

p.addRequired(...

'X0', ...

@(x) validateattributes(x, {'numeric'}, ...

{'vector'}));

p.addOptional(...

'freq', 10, ...

@(x) validateattributes(x, {'numeric'}, ...

{'scalar', 'integer', 'positive'}));

p.addOptional(...

'SimulinkVariables', struct(), ...

@(x) isa(x, 'struct'));

p.parse(varargin{:});

%# do stuff with variables

end

我希望能够传递如下参数;只要有必要的那一对,那么哪一对传入就没关系.所以示例调用可能是:

myFunc('numStates', 4, 'numInps', 2, 'numOUts', 3, 'X0', [4;0]);

显然,这种语法是非法的; parse()期望其中的第一个参数是必需的值,但不应该显式命名它们,即,如:

function myFunc(numStates, numInps, numOuts, X0, varargin)

...

p.parse(numStates, numInps, numOuts, X0, varargin{:});

end

有没有一种简单的方法可以做到我想要的,即第一个功能?我想最简单的事情是做一些事情来重新排序varargin的元素并踢出参数名称,但这并不是非常优雅.

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐