我可以使用相同功能的不同类型的参数输入 [英] can I use same functions with the different type of argument inputs
问题描述
如果我有一个MATLAB的实验室文件包含函数富
If I have a MATLAB lab file contains function foo
function [test] = foo(a,b);
test = a+b
如果我想修改函数foo也是在我的输入接收另外的数据 C
在相同的MATLAB文件
If I want to modified that function foo also receive the addition data c
in my input
in the same MATLAB file
function [test] = foo(a,b,c);
test = a+b+c;
我能做到这一点? (我尝试类似的,但是当我尝试使用它说我有很多的说法。)
Can I do this? (I try the similar but when I try to use it said that I have to many argument.)
推荐答案
varargin
方法是适合这里,但我会做到这一点略有不同(见下文)。但是,你可以简单地测试了第三个参数的存在与 存在
(或通过 nargin
,但就是那么直接和容易出错)。
The varargin
approach is suitable here, although I would do it slightly differently (see below). However, you can simply test for the existence of the third argument with exist
(or via nargin
, but that is less direct and error prone).
function test = foo(a,b,c)
if exist('c','var'), % nargin>2
test = a + b + c;
else
test = a + b;
end
由于在code评论,在测试 nargin
也是可以的,但存在
通话远不如含糊不清,如果参数列表被修改(例如排序)将不需要改变。
As in the code comment, a test on nargin
is also possible, but the exist
call is far less ambiguous and will not need a change if the argument list is modified (e.g. order).
注意 varargin
并不需要在函数声明的唯一参数:
Note that varargin
does not need to be the only argument in the function declaration:
function test = foo(a,b,varargin)
if nargin>2, % numel(varargin)>0
test = a + b + varargin{1};
else
test = a + b;
end
另外,说你想有任何数量的额外输入(例如:美孚(A,B,C,D,...)
),你可以做招数与 varargin
单元阵列。举例来说,你可以做 [varargin {:}]
来串联水平在一个新的数组中的元素。对于垂直串联,你可以做 vertcat(varargin {:})
。我假设 A + B + C
的例子是的只是一个例子的,所以我不会在实践中证明这一点,但你可以使用这些阵列任何你喜欢的方式。
Also, say you want to have any number of extra inputs (e.g. foo(a,b,c,d,...)
), you can do to tricks with the varargin
cell array. For instance, you can do [varargin{:}]
to horizontally concatenate the elements in to an a new array. For vertical concatenation, you can do vertcat(varargin{:})
. I'm assuming the a+b+c
example was just an example, so I won't show this in practice, but you can use these arrays any way you like.
这篇关于我可以使用相同功能的不同类型的参数输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!