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.)
Probably, the easiest way to support this, is with
This will allow for any number of inputs. f you want to limit to 2, 3 inputs, do
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:EDIT: I am unsure about this, but the above method to set defaults, may be Octave only and not yet implemented in Matlab.
you can write in this way:
you can supply as many arguments as you want.you can read more about varargin here: enter link description here
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 withexist
(or vianargin
, but that is less direct and error prone).exist
As in the code comment, a test on
nargin
is also possible, but theexist
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:Also, say you want to have any number of extra inputs (e.g.
foo(a,b,c,d,...)
), you can do to tricks with thevarargin
cell array. For instance, you can do[varargin{:}]
to horizontally concatenate the elements in to an a new array. For vertical concatenation, you can dovertcat(varargin{:})
. I'm assuming thea+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.