can I use same functions with the different type o

2019-01-29 09:54发布

If I have a MATLAB lab file contains function foo

function [test] = foo(a,b);
test = a+b

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.)

3条回答
虎瘦雄心在
2楼-- · 2019-01-29 10:20

Probably, the easiest way to support this, is with

function [test] = foo (varargin)
  test = sum ([varargin{:}]);
end

This will allow for any number of inputs. f you want to limit to 2, 3 inputs, do

function [test] = foo (varargin)
  narginchk (2, 3);
  test = sum ([varargin{:}]);
end

Another method, if you want to avoid varargin, is to set the last element to default to 0 so it doesn't affect the operation in case it is not defined:

function [test] = foo (a, b, c = 0)
  test = a + b + c;
end

EDIT: I am unsure about this, but the above method to set defaults, may be Octave only and not yet implemented in Matlab.

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-29 10:21

you can write in this way:

function [test] = foo (varargin)
y = 0 ;
for i = 1:length(varargin)
y = y+ varargin(i) ;
end
test = y ;
end

you can supply as many arguments as you want.you can read more about varargin here: enter link description here

查看更多
你好瞎i
4楼-- · 2019-01-29 10:27

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).

exist

function test = foo(a,b,c)

if exist('c','var'), % nargin>2
    test = a + b + c;
else
    test = a + b;
end

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

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.

查看更多
登录 后发表回答