MATLAB: Anyone know how to create a multidimensional subclass constructor

MATLABmultidimensional classesoop

Hello!
My problem is, that I'm trying to write a subclass to my multidimensional superclass, but i run into errors trying to call the superclasses constructor in the subclass constructor.
The superclasses constructor looks somewhat like this:
function obj = A( arg1, arg2, arg3 )
if nargin == 0
return;
end
n = numel( arg1 );
obj( n , 1 ) = A();
for i=1:n
% some code
end
end
Now I would like to build a subclass to this one, with some additional parameters, but I have no idea about the syntax for the subclass. The syntax written in the Matlab Documentation doesn't help at all for this kinda multidimensional cases.
Thanks in advance!

Best Answer

That's a very interesting question and I think it shows another problem with matlab class design.
The problem you'll encounter when constructing a derived object (let's call it B) is that in the superclass constructor, obj is still of class B and thus the line obj(n, 1) = A is going to cause an error, since A can't be converted to B. In A constructor obj should never be of type B.
There is an ugly workaround, use eval to construct the array of the required type. You'll end up with:
classdef A
properties
a;
end
methods
function this = A(arg1, arg2, arg3)
if nargin == 0 %to support array construction
return;
else
this(numel(arg1), 1) = eval(class(this)); %use eval to invoke the correct constructor
arg1 = num2cell(arg1); [this.a] = arg1{:}; %distribute arg1 into each object
end
end
end
end
classdef B < A
properties
b;
end
methods
function this = B(Barg, arg1, arg2, arg3)
if nargin == 0 %can't call base constructor inside if, so build base constructor arguments
args = {};
else
args = {arg1, arg2, arg3};
end
this@A(args{:}); %and call base constructor
if nargin > 0
Barg = num2cell(Barg);
[this.b] = Barg{:};
end
end
end
end
I'm going to raise that as an issue with mathworks as this shows that there is no decent way of initialising an object array. Assigning to the last element of array is fragile and breaks under your circumstances. I really hate that constructing an object and an array of object is done in the same constructor.