rap2009 发表于 2007-11-17 15:28

matlab能实现类似c的重载功能吗?

比如我设置参数个数或类型来区别函数,怎么存放函数,我做了个函数,为什么matlab找到一个函数后,发现参数不匹配,但不继续寻找了呢,而matlab内置函数却可以实现此种功能,比如:plot可以带多种参数,请各位帮帮忙哦,期待ing........

sogooda 发表于 2007-11-17 16:16

类型的重载不大清楚,不过,参数的个数肯定是可以的。
在一个函数中,nargin, nargout中将返回函数的输入参数和输出参数个数,再加上if 判断,就可以实现参数个数的重载。

使用方法
n = nargin
n = nargin(fun)
n = nargout
n = nargout(fun)
一个例子函数,可以实现参数个数变化的输入和输出。这里面也可以看到matlab中实现参数默认值的一种方法。
function = myplot(x, y, npts, angle, subdiv)
% MYPLOTPlot a function.
% MYPLOT(x, y, npts, angle, subdiv)
%   The first two input arguments are
%   required; the other three have default values.
...
if nargin < 5, subdiv = 20; end
if nargin < 4, angle = 10; end
if nargin < 3, npts = 25; end
...
if nargout == 0
   plot(x, y)
else
   x0 = x;
   y0 = y;
end
enjoy~

[ 本帖最后由 sogooda 于 2007-11-17 16:17 编辑 ]

rap2009 发表于 2007-11-17 19:13

多谢,多谢,这样就足够了
页: [1]
查看完整版本: matlab能实现类似c的重载功能吗?