views:

38

answers:

1

I have the following structure in matlab

superClass < handle

subClassA < superClass

subClassB < superClass

say I have a vector A of subClassA and a vector B of subClassB.

I would like to combine them like this:

superVector = [A B];

but Matlab doesn't like this. What's the proper way to cast the subclass back to the superclass?

+2  A: 

Nevermind - it's impossible

matlab oop help

MATLAB does not allow you to create arrays containing a mix of superclass and subclass objects because an array can be of only one class. If you attempt to concatenate objects of different classes, MATLAB looks for a converter method defined by the less dominant class (generally, the left-most object in the expression is the dominant class).

Marc
BTW: I think my workaround is going to be to use cells instead.
Marc
I wouldn't say it's *impossible*. It simply requires that you have the ability to convert one subclass to the other using a [converter method](http://www.mathworks.es/access/helpdesk/help/techdoc/matlab_oop/br2vkky.html). The drawback is that you don't always want to do that for fear of losing properties specific to the unconverted object. In addition, you can also specify the [precedence of classes](http://www.mathworks.es/access/helpdesk/help/techdoc/matlab_oop/brf5okb-1.html) to control which one gets converted to the other.
gnovice
Well no, it's still impossible. Say my super class is Shape, my subclasses are Square and Circle, and Shape defines but does not implement an area method. If I wanted to make an array of Circles and Squares, then sort them by area, I couldn't convert them to Shapes, because in order to compute the area, the object needs to know if it's a square or a circle. The same problem applies to any overridden method.
Marc
@Marc: I was actually speaking in a more general sense of combining two different classes into an array. For example, if you had a converter method that changed a Square into a Circle, you could combine Squares and Circles in an array. However, this is not a conversion you would necessarily *want* or *be able* to make in many cases, like in the specific example you gave. Alternatively, consider a superclass Person with subclasses Employee and Friend. You could have a converter method that changes the Employee class to a Friend class, allowing concatenation of Employee and Friend objects.
gnovice
Marc