Products & Services Solutions Academia Support User Community Company

Learn more about MATLAB   

Converting Objects to Another Class

Why Implement a Converter

You can convert an object of one class to an object of another class. A converter method has the same name as the class it converts to, such as char or double. Think of a converter method as an overloaded constructor method of another class—it takes an instance of its own class and returns an object of a different class.

Converters enable you to:

For example, suppose you have defined a polynomial class, but you have not overloaded any of the MATLAB functions that operate on the coefficients of polynomials, which are doubles. If you create a double method for the polynomial class, you can use it to call other functions that require inputs of type double.

Use the double converter method to call other functions:

roots(double(p))

p is a polynomial object, double is a method of the polynomial class, and roots is a standard MATLAB function whose input arguments are the coefficients of a polynomial.

Converters and Subscripted Assignment

When you make a subscripted assignment statement such as:

A(1) = myobj;

MATLAB software compares the class of the Right-Hand-Side (RHS) variable to the class of the Left-Hand-Side (LHS) variable. If the classes are different, MATLAB attempts to convert the RHS variable to the class of the LHS variable. To do this, MATLAB first searches for a method of the RHS class that has the same name as the LHS class. Such a method is a converter method, which is similar to a typecast operation in other languages.

If the RHS class does not define a method to convert from the RHS class to the LHS class, then MATLAB software calls the LHS class constructor and passes it to the RHS variable.

For example, suppose you make the following assignments:

A(1) = objA; % Object of class ClassA
A(2) = objB; % Object of class ClassB

MATLAB attempts to call a method of ClassB named ClassA. If no such converter method exists, MATLAB software calls the ClassA constructor, passing objB as an argument. If the ClassA constructor cannot accept objB as an argument, then MATLAB returns an error.

You can create arrays of objects of different classes using cell arrays (see cell for more information on cell arrays).

Examples of Converter Methods

See the following sections for examples of converter methods:

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

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