Variable argument pairs in MATLAB functions

人走茶凉 提交于 2019-12-24 07:59:18

问题


I'm trying to develop a function that contains multiple arguments. To be as robust as possible, I want to be able to call my function as follows:

foo( x, y, z, 'OptionalArg1', bar, 'OptionalArg2', blah, 'OptionalArg3', val )

I want my function to be robust enough to contain any combination of these arguments in any order. I also need to be able to set defaults if the argument is not provided. Is there a standard way to do this in MATLAB?


回答1:


The best way would be to use the inputParser class, with the addParameters function.

In short, your code would look like:

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

Alternatively, you could write your own as I did (example here). The code there is easily modifiable to have your own input parser (you just need to change the opts, and add a switch for each new opt.

But the inputParser is easier, and clearer to use.



来源:https://stackoverflow.com/questions/50276776/variable-argument-pairs-in-matlab-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!