MATLAB Answers

1

Why do array of dynamical properties not behave like array of properties ?

Asked by Thibaut Jacqmin on 25 Jan 2017
Latest activity Commented on by Thibaut Jacqmin on 27 Jan 2017
Why do dynamical properties behave differently than usual properties when getting them ?
Let us say I have one array of object my_class1 in an object of class my_class2. Then I add dynamically a property to all the elements of this arry.
classdef my_class1 < dynamicprops
property
Pressure
end
end
classdef my_class2 < handle
properties
my_prop = my_class1
end
end
my_object = my_class1;
for i = 1:10
my_object.my_prop(i) = my_class2;
my_object.my_prop(i).addprop('Temperature');
end
Then if I try to retrieve all the properties in one vector, what I would do with a non dynamical property would be
vec = [my_object.my_prop.Pressure];
However with a dynamical property it does not work I need to make a for loop :
for i = 1:10
vec(i) = my_object.my_prop(i).Temperature;
end
Thanks a lot.

  1 Comment

That is certainly something else that would put me off using these. I have pondered on classes inheriting from dynamicprops numerous times, trying to think of a scenario when I would find it useful, but I never have done despite writing probably > 2000 classes in Matlab so far.
Every time I think of it I come to the same conclusion - if the property makes sense on the class then why isn't it a permanent property? I have many classes where I have such properties which, for some objects, I just leave empty and run an isempty test on when using. This tends to be my solution to this.
It's not necessarily better, it's just a preference because one of the (many many) reasons I like classes better than structs, even for simple stuff with no real methods, is that I can see the properties of the objects of that class just by looking at the class file - there are no hidden surprises like the christmas tree style of a struct to just hang things off anyhow. Dynamic properties feel to me a bit more like a cross between a class and a struct in a direction I'm not keen on. I've often thought of trying them out, see if I change my mind, but something like this would dissuade me further I think.

Sign in to comment.

1 Answer