MATLAB: Class Property: Array of Objects

arrayclassdependentMATLABobjectoopproperties

I would like to create a "Dependent Property" inside a "Main Class" that will handle a array of objects of "Sub Class".
Exemple:
classdef main_class
properties
number
end
properties (Dependent)
% prop will be a array of sub_class object
% the size of this array will depend/change on the "number" property
prop = sub_class();
end
end
If I set:
main = main_class();
main.number = 3;
I would like to get:
main.prop = [sub_class(1) sub_class(2) sub_class(3)]
To me is important that "prop" be a dependent property to automatic change the number of the elements in the array.
How could I do that? Thanks!

Best Answer

I'm with Adam, I don't think you want a dependent property. dependent does not mean that the property value is recalculated when some other property change, it means that property value is created every time you ask for it. That value is not stored in the class.
In your case, you would be better off creating a setter method for your number property that automatically update the array size of the normal prop property:
classdef main_class
properties
number
prop
end
methods
function this = main_class(number) %constructor
if nargin == 0
this.number = 0;
else
this.number = number;
end
this = this.create_subarray;
end
function this = set.number(this, value) %set method for number. reset prop at the same time
this.number = value;
this = this.create_subarray;
end
function this = create_subarray(this)
this.prop = sub_class.empty;
for n = 1:this.number
this.prop(n) = sub_class(n);
end
end
end
end
As Adam and Andrew have commented, hopefully sub_class is not actually a subclass of main class.