如何在Matlab中重载用户定义的函数?

时间:2011-08-27 22:01:56

标签: matlab

我正在尝试绘制序列,我已经编写了一个函数

function show_seq(seq)
 plot (seq)
end

我现在想要重载此show_seq以显示类似

的2个序列
function show_seq(seq1, seq2)
  plot(seq1,'color','r');
  plot(seq2, 'color', 'b');
end

但这不起作用,有没有人知道如何在MATLAB中重载函数?

1 个答案:

答案 0 :(得分:10)

如果将重载函数放在具有更高优先级的路径中,则可以重载自己的一个函数。有关路径优先级的更多详细信息,请参阅this question

但是,在您的情况下,最简单的方法是修改show_seq,以便它接受多个可选输入:

function show_seq(varargin)
  hold on %# make sure subsequent plots don't overwrite the figure
  colors = 'rb'; %# define more colors here, 
                 %# or use distingushable_colors from the
                 %# file exchange, if you want to plot more than two

  %# loop through the inputs and plot
  for iArg = 1:nargin
      plot(varargin{iArg},'color',colors(iArg));
  end
end
相关问题