MATLAB: How are objects converted from one type to another when collected together in an array in MATLAB 7.6 (R2008a)

concatenateMATLABmergetype casttypecast

I have a handle class "SuperClass" and a class "SubClass" which derives from SuperClass, with the following definitions:
classdef SuperClass < handle
properties
prop1
prop2
end
methods
function obj = SuperClass(prop1,prop2)
obj.prop1 = prop1;
obj.prop2 = prop2;
end
end
end
classdef SubClass < SuperClass
properties
newprop
end
methods
function obj = SubClass(prop1,prop2,newprop)
obj = obj@SuperClass(prop1,prop2);
obj.newprop = newprop;
end
end
end
I would like to aggregate objects of these classes into a single vector as follows:
supobj = SuperClass(1,2);
subobj = SubClass(3,4,5);
vec(1) = supobj;
vec(2) = subobj;
Conceptually, this should be possible because subobj is an object of SuperClass. However, this gives me the following error:
??? The following error occurred converting from SubClass to SuperClass:
Input argument "prop2" is undefined.

Best Answer

When MATLAB sees a subscripted assignment to an existing variable, MATLAB checks the class of the right-hand-side against the class of the left-hand-side (LHS) variable. If different, it attempts to convert the right-hand-side (RHS) variable to the type of the LHS class.
To achieve this, MATLAB first looks for a method of the RHS class that has the same name as the LHS class. This is a converter method from one class to another and similar in some ways to a cast operator in C++.
If there is no specific converter, then MATLAB calls the LHS constructor and passes the RHS variable as input. This is irrespective of the class relationship between the LHS and RHS variable.
In the above example, the LHS class is SuperClass and the RHS class is SubClass. When the following line is executed,
vec(2) = subobj
since SubClass does not have a method SuperClass, MATLAB calls the SuperClass constructor with subobj as the single input, resulting in an error.
To facilitate the conversion from SubClass to SuperClass, you can create a method named SuperClass in class SubClass with the following signature
function obj = SuperClass(subobj)
obj = SuperClass(subobj.prop1, subobj.prop2);
end
Alternatively, you can modify the constructor of SuperClass to accommodate single inputs of type SuperClass. One implementation of the constructor could be,
function obj = SuperClass(prop1, prop2)
if isa(prop1,'SuperClass')
obj.prop1 = prop1.prop1;
obj.prop2 = prop1.prop2;
else
obj.prop1 = prop1;
obj.prop2 = prop2;
end
end
One drawback of the previous methods is that a copy of the object is created.
As an alternative, you can preserve the original class of the objects and still aggregate the objects by using a cell array as follows:
vec{1} = supobj;
vec{2} = subobj;
Related Question