Overloaded matlab functions.

20 次查看(过去 30 天)
Tyler Waugh
Tyler Waugh 2011-4-15
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

回答(2 个)

Jan
Jan 2011-4-15
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 2011-4-15
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.

类别

Help CenterFile Exchange 中查找有关 Function Creation 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by