Implementing Operators for Your Class

Overloading Operators

You can implement MATLAB® operators (+, *, >, etc.) to work with objects of your class. Do this by defining the relevant functions as class methods.

Each built-in MATLAB operator has an associated function (e.g., the + operator has an associated plus.m function). You can overload any operator by creating a class method with the appropriate name.

Overloading enables operators to handle different types and numbers of input arguments and perform whatever operation is appropriate for the highest precedence object:

Object Precedence

User-defined classes have a higher precedence than built-in classes. For example, if q is an object of class double and p is a user-defined class, polynomial, the expression

q + p

generates a call to the plus method in the @polynomial directory, if it exists. Whether this method can add objects of class double and class polynomial depends on how you implement it.

When p and q are objects of different classes, MATLAB applies the rules of precedence to determine which method to use.

Object Precedence in Expressions Using Operators provides information on how MATLAB determines which overloaded method to call.

Examples of Overloaded Operators

Defining Arithmetic Operators for DocPolynom provides examples of overloaded operators.

MATLAB® Operators and Associated Functions

The following table lists the function names for common MATLAB operators.

Operation

Method to Define

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

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS