Reputation: 53
I am confused on how to use handle objects as properties in matlab. For example, I defined the following classes:
classdef Page < handle
properties
word1;
word2;
end
classdef Book < handle
properties
page1 = Page;
page2 = Page;
end
Now I instantiate two books:
iliad = Book;
odyssey = Book;
If I check if iliad and odyssey are the same:
eq(iliad, odyssey)
I get:
ans = logical 0
So far so good
But if I check if page1 of iliad and odyssey are the same:
eq(iliad.page1, odyssey.page1)
I get:
ans = logical 1
This is not good! It means that if I change page1 of odyssey, page1 of iliad will also change. What am I misunderstanding? How do I deal with this issue?
Upvotes: 5
Views: 137
Reputation: 12214
This appears to be related to how MATLAB evaluates property default values. Per the documentation for Properties Containing Objects:
MATLAB® evaluates property default values only once when loading the class. MATLAB does not reevaluate the assignment each time you create an object of that class. If you assign an object as a default property value in the class definition, MATLAB calls the constructor for that object only once when loading the class.
It goes on to further note that:
Evaluation of property default values occurs only when the value is first needed, and only once when MATLAB first initializes the class. MATLAB does not reevaluate the expression each time you create an instance of the class.
Which describes the equality you're seeing between books. MATLAB essentially caches class definitions, so while your Page
objects are different within the book, they're going to be the same across books because MATLAB is only constructing the defaults once.
To avoid this, you can instantiate your Page
objects in Book
's constructor:
classdef Book < handle
properties
page1
page2
end
methods
function self = Book()
self.page1 = Page;
self.page2 = Page;
end
end
end
Which gives you the desired behavior:
>> iliad = Book;
>> odyssey = Book;
>> eq(iliad.page1, odyssey.page1)
ans =
logical
0
Upvotes: 6