Anyone know how to create a multidimensional subclass constructor?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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!
0 commentaires
Réponse acceptée
Guillaume
le 13 Oct 2016
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.
2 commentaires
Andrew Stamps
le 7 Nov 2023
This may only be my personal preference in avoiding eval wherever possible, but it could be replaced by str2fun as follows.
...
con = str2func(class(this));
this(numel(arg1), 1) = con(); %use str2func to invoke the correct constructor
...
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Construct and Work with Object Arrays dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!