Programming |
Overloading Operators and Functions
In many cases, you may want to change the behavior of the MATLAB operators and functions for cases when the arguments are objects. You can accomplish this by overloading the relevant functions. Overloading enables a function to handle different types and numbers of input arguments and perform whatever operation is appropriate for the highest-precedence object. See Object Precedence for more information on object precedence.
Overloading Operators
Each built-in MATLAB operator has an associated function name (e.g., the + operator has an associated plus.m
function). You can overload any operator by creating an M-file with the appropriate name in the class directory. For example, if either p
or q
is an object of type classname
, the expression
generates a call to a function @classname/plus.m
, if it exists. If p
and q
are both objects of different classes, then MATLAB applies the rules of precedence to determine which method to use.
Examples of Overloaded Operators
See the following sections for examples of overloaded operators:
The following table lists the function names for most of the MATLAB operators.
Operation |
M-File |
Description |
a + b |
|
Binary addition |
a - b |
|
Binary subtraction |
-a |
|
Unary minus |
+a |
|
Unary plus |
a.*b |
|
Element-wise multiplication |
a*b |
|
Matrix multiplication |
a./b |
|
Right element-wise division |
a.\b |
|
Left element-wise division |
a/b |
|
Matrix right division |
a\b |
|
Matrix left division |
a.^b |
|
Element-wise power |
a^b |
|
Matrix power |
a < b |
|
Less than |
a > b |
|
Greater than |
a <= b |
|
Less than or equal to |
a >= b |
|
Greater than or equal to |
a ~= b |
|
Not equal to |
a == b |
|
Equality |
a & b |
|
Logical AND |
a | b |
|
Logical OR |
~a |
|
Logical NOT |
a:d:b a:b |
|
Colon operator |
a' |
|
Complex conjugate transpose |
a.' |
|
Matrix transpose |
command window output |
|
Display method |
[a b] |
|
Horizontal concatenation |
[a; b] |
|
Vertical concatenation |
a(s1,s2,...sn) |
|
Subscripted reference |
a(s1,...,sn) = b |
|
Subscripted assignment |
b(a) |
|
Subscript index |
Converter Methods | Overloading Functions |
© 1994-2005 The MathWorks, Inc.