Overloaded matlab functions.
23 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
In other programming languages there is the ability to have multiple functions/methods with the same name so long as they have different inputs, for example: foo(int i), foo(cell c), and foo(int i, cell c). Is there a way to do this in MATLAB? -Tyler
0 comentarios
Respuestas (2)
Jan
el 15 de Abr. de 2011
You can create functions in subfolders called '@char', '@double' etc., which are called for the specific types. E.g. created the function "D:\MFiles\MyTools\@cell\fileparts.m", which handels cell strings. Now 'D:\MFiles\MyTools' is inserted in the path, but not 'D:\MFiles\MyTools\@cell'.
Now the @cell method is called automatically for "fileparts({tempdir})".
0 comentarios
James Tursa
el 15 de Abr. de 2011
You can get this functionality for intrinsic types with a single function. e.g.,
function foo(a,b)
if( iscell(a) )
% stuff
elseif( isa(a,'double') )
% other stuff
etc.
You should also look into using nargin, nargout, varargin, and varargout for more versatility.
For user-defined classes, MATLAB will automatically call the overloaded function associated with that class object if it is one of the arguments. If you have multiple user defined objects as arguments then there is a pecking order that is followed to determine which function is called.
0 comentarios
Ver también
Categorías
Más información sobre Function Creation en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!