addprop Adds Properties To Multiple Instances?

3 views (last 30 days)
I have a class defintion similar to the following:
classdef A < hgsetget & dynamicprops
%...
end
Then I have another class defintion similar to the following
classdef B < hgsetget
properties
a = A();
b = A();
end
end
Now here is where it gets weird I, I wrote the following code:
r = B();
e = B();
addprop( get( r, 'a' ), 'p' );
%These two have p.%
disp( properties( get( r, 'a' ) ) );
disp( properties( get( e, 'a' ) ) );
%But these two do not.%
disp( properties( get( r, 'b' ) ) );
disp( properties( get( e, 'b' ) ) );
I double checked the documentation, it states that 'addprop()' adds a property to a class instance. I have taken a few steps after this but none have really worked to well. Could someone explain this behavior to me, or how to work around it, or fix it?
P.s I am using MATLAB R2011b. P.s.s I am a tad new to MATLAB, please excuse any "nooby - ness".

Accepted Answer

Chris
Chris on 24 Jul 2013
Okay this was a weird one. Apparently when you construct class instances like so:
classdef A
properties
b = B();
end
end
For all instances of that class, 'b' is regarded as the same instance, (static) at least in this context (I have not tested it for other contexts). The solution is to do the following instead:
classdef B < hgsetget
properties
a;
b;
end
methods
function this = B()
this.a = B();
this.b = B();
end
end
end
This way the interpreter doesent make them (effectivly) static. Sorry if this is a "nooby" reilization, I have only just begun to work with MATLAB.

More Answers (1)

Jim Hokanson
Jim Hokanson on 10 Aug 2013
It seems like you have two different issues going on, first, from your question:
classdef B < hgsetget
properties
a = A();
b = A();
end
end
'a' and 'b' point to different objects, so modifying the properties in 'a' will not change 'b', since they are different instances, and addprop modifies instances, not class definitions. So I would expect that 'b' doesn't have a 'p' property.
From your answer you bring up another issue which was non-obvious to me as well at one point. Matlab evaluates the default properties of each class once unless it is redefined. This means that in your example code (from the original question) 'a' and 'b' will only ever point to two objects, and creating a new B() will not give you new instances.
Final note, I'm surprised your answer doesn't throw a recursion overflow error, perhaps you meant to assign A() to the properties in the constructor?

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!