| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
| On this page… |
|---|
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:
Use methods defined for another class
Ensure that expressions involving objects of mixed class types execute properly
Control how instances are interpreted in other contexts
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.
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).
See the following sections for examples of converter methods:
![]() | Displaying Objects in the Command Window | Indexed Reference and Assignment | ![]() |

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 |