Overloaded matlab functions.
20 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
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})".
0 个评论
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!