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,
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;
Best Answer