Overloaded matlab functions.

22 Ansichten (letzte 30 Tage)
Tyler Waugh
Tyler Waugh am 15 Apr. 2011
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

Antworten (2)

Jan
Jan am 15 Apr. 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})".

James Tursa
James Tursa am 15 Apr. 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.

Kategorien

Mehr zu Function Creation finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by