¿Cómo sobrecargar las funciones definidas por el usuario en Matlab?

I am trying to plot sequences, I have written a function

function show_seq(seq)
 plot (seq)

I now want to overload this show_seq to show 2 sequences something like

function show_seq(seq1, seq2)
  plot(seq2, 'color', 'b');

but this does not work, does anyone have idea about how to overload functions in MATLAB?

preguntado el 27 de agosto de 11 a las 22:08

1 Respuestas

You can overload one of your own functions if you put the overloading function in a path that with higher precedence. For more details on path precedence, see esta pregunta.

However, in your case, the easiest would be to modify show_seq so that it accepts multiple optional inputs:

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

contestado el 23 de mayo de 17 a las 13:05

Jesus, so you can't just put these two overloads in one file as you would do in every other language I came across so far? - Grzenio

@Grzenio: Without tricks, you indeed cannot put multiple independent functions in one file. However, do you really think it is easier and more efficient to copy-paste most of the function multiple times for different signatures, rather than writing one function that can handle multiple signatures? - Jonas

In normal programming languages you would usually create one function with all the possible parameters with the actual implementation, and a few functions with more specialized set of parameters, which just adapt the parameters, provide some default values etc. and call the function with implementation. The main thing you copy-paste is, well, the function name... - Grzenio

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.