Programming Previous page   Next Page

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
plus(a,b)
Binary addition
a - b
minus(a,b)
Binary subtraction
-a
uminus(a)
Unary minus
+a
uplus(a)
Unary plus
a.*b
times(a,b)
Element-wise multiplication
a*b
mtimes(a,b)
Matrix multiplication
a./b
rdivide(a,b)
Right element-wise division
a.\b
ldivide(a,b)
Left element-wise division
a/b
mrdivide(a,b)
Matrix right division
a\b
mldivide(a,b)
Matrix left division
a.^b
power(a,b)
Element-wise power
a^b
mpower(a,b)
Matrix power
a < b
lt(a,b)
Less than
a > b
gt(a,b)
Greater than
a <= b
le(a,b)
Less than or equal to
a >= b
ge(a,b)
Greater than or equal to
a ~= b
ne(a,b)
Not equal to
a == b
eq(a,b)
Equality
a & b
and(a,b)
Logical AND
a | b
or(a,b)
Logical OR
~a
not(a)
Logical NOT
a:d:b
a:b
colon(a,d,b)
colon(a,b)
Colon operator
a'
ctranspose(a)
Complex conjugate transpose
a.'
transpose(a)
Matrix transpose
command window output
display(a)
Display method
[a b]
horzcat(a,b,...)
Horizontal concatenation
[a; b]
vertcat(a,b,...)
Vertical concatenation
a(s1,s2,...sn)
subsref(a,s)
Subscripted reference
a(s1,...,sn) = b
subsasgn(a,s,b)
Subscripted assignment
b(a)
subsindex(a)
Subscript index


Previous page  Converter Methods Overloading Functions Next page

© 1994-2005 The MathWorks, Inc.