MATLAB函数中的变量参数对 [英] Variable argument pairs in MATLAB functions
问题描述
我正在尝试开发一个包含多个参数的函数.为了尽可能强大,我希望能够如下调用我的函数:
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 )
我希望我的函数足够健壮,以任何顺序包含这些参数的任何组合.如果未提供参数,我还需要能够设置默认值.在MATLAB中有标准的方法可以做到这一点吗?
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?
推荐答案
最好的方法是使用 inputParser
类,并带有addParameters
函数.
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
.
但是inputParser
更容易使用,更清晰.
But the inputParser
is easier, and clearer to use.
这篇关于MATLAB函数中的变量参数对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!