问题描述:

This question already has an answer here:

  • Overloading functions

    2 answers

网友答案:

You have many possibilities. You can use varargin, it will pass a cell array with all arguments to your function:

function f1(varargin)
switch numel(varargin)
    case 1
        disp(varargin{1})
    case 2
        disp(varargin{1})
        disp(varargin{2})
end
end

You could also check the number of input arguments using nargin and not use the second input argument if it not exists.

function f2(x,y)
switch nargin
    case 1
        disp(x)
    case 2
        disp(x)
        disp(y)
end
end

A third possibility is to check if y exists. It will not exist if you don't pass an argument:

function f3(x,y)
if not(exist('y','var'))
        disp(x)
else
        disp(x)
        disp(y)
end
end
相关阅读:
Top