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

use*_*194 7 matlab

我试图绘制序列,我写了一个函数

function show_seq(seq)
 plot (seq)
end
Run Code Online (Sandbox Code Playgroud)

我现在想要重载这个show_seq以显示2个类似的序列

function show_seq(seq1, seq2)
  plot(seq1,'color','r');
  plot(seq2, 'color', 'b');
end
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*nas 10

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

但是,在您的情况下,最简单的方法是修改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
Run Code Online (Sandbox Code Playgroud)

  • 耶稣,所以你不能把这两个重载放在一个文件中,就像我到目前为止遇到的其他语言一样? (21认同)
  • 在普通的编程语言中,您通常会创建一个具有实际实现的所有可能参数的函数,以及一些具有更多专用参数的函数,这些函数只需调整参数,提供一些默认值等,并通过实现调用函数.复制粘贴的主要内容是函数名称...... (15认同)
  • @Grzenio:没有技巧,你确实无法将多个独立函数放在一个文件中.但是,您是否真的认为为不同的签名多次复制粘贴大部分函数更容易,更有效,而不是编写一个可以处理多个签名的函数? (2认同)