MATLAB: How to overload built-in MATLAB functions

builtfunctioninMATLABoverloadoverloadedoverloading

I would like to overload built-in MATLAB functions with my own functions. For example, when I execute the command:
x = rand(100);
I would like MATLAB to call my RAND function rather than the built-in MATLAB RAND function.

Best Answer

To overload the RAND function with your own function myrand.m, place myrand.m in a directory on the MATLAB path. Then, create the following function and save it as rand.m:
function varargout = rand(varargin)
[varargout{1:nargout}] = myrand(varargin{:});
The built-in RAND function accepts both double and char inputs. Therefore, you will need this to save this file in a directory named @double and a directory named @char.
If the state of the new RAND is other than double datatype (e.g., uint32) you will have to create another copy of rand.m in another @<class> directory. Note that it is not recommended to have more than one @double directory on your search path, as this can create confusion on which @double folder is being used. Place all files overloaded for a specific data type <foo> within the same @<foo> directory.
The on-line documentation containing information about function overloading can be found at:
If you would like to use the Launch Pad in MATLAB 6.x and higher to find this information, follow this menu path:
MATLAB Help --> Using MATLAB --> Programming and Data Types --> MATLAB Classes and Objects --> Overloading Operators and Functions.
Alternatively, you could also search for "overloading" in the documentation by using the search tab in the Help Browser.