Overloaded matlab functions.
23 ビュー (過去 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!