USGS logo - Archived Page (no longer updated)

Object-Oriented Programming

Dr. Charles R. Denham, U.S. Geological Survey, Woods Hole, MA 02543


Matlab OOP

Overloading Operators

All of Matlab's operators are available for "overloading", including arithmetic, logic, and indexing. The operators have intuitive names, such as "plus". Distinction between matrix and scalar operators is apparent, as in "mtimes" for matrix-multiply and "times" for scalar-multiply. Division can be done to the right or to the left, as in "rdivide" and "ldivide". The matrix versions are "mrdivide" and "mldivide". The unitary sign operators are "uplus" and "uminus". There are many others.

The most difficult operators to overload are those involved with indexing, using "()", "{}", and "." There are two flavors, depending on whether the indices are on the right-side of the equal-sign ("subsref") or on the left-side ("subsasgn").

The "subsref" operator calls "subsref(self, theStruct)", where "self" is the object, and "theStruct" is a Matlab "struct" whose fields are "type" and "subs". The former is a string, containing "()", "{}", or ".". The latter is a cell containing the list of indices. See "help subsref".

The "subsasgn" operator calls "subsasgn(self, theStruct, other)", where "other" is the right-side information to be assigned to the left-side item. See "help subsasgn".

The "subsref" and "subsasgn" operators are the only ones available for extracting private data from an object. Users may wish to expose some or all of the private data by overloading these methods to handle the "." operator.

Caveat: In the case of colon-notation, the colon is represented by a string ":", which the user will have to detect and interpret.

Caveat: If the "subs" field is not a cell, turn it into a cell immediately, and only then proceed with the interpretion of the call. This inconsistency will occur whenever there is only one subscripting index.

Caveat: There is only one "subsref" and one "subsasgn" per class. This means that all three subscripting operators will have to be processed if these methods are overloaded, even though the user may have wished to overload just one or two of the types of subscripts.

One other operator, "subsindex", is called whenever the object is used as an index in an expression. If such a context can arise in your class, the "subsindex" method will have to be overloaded. See "help subsindex".

To process "end" as an index, create an "end" method in your class, whose purpose is to translate the given "end" to the proper value, depending on context. See "help end".

Also see the Matlab B.O.O.T Camp.


lighthouse graphic