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?
Certain kinds of MATLAB® objects are handles. When a variable holds a handle, it actually holds a reference to the object. Handle objects enable more than one variable to refer to the same object. Handle-object behavior affects what happens when you copy handle objects and when you pass them to functions.
When you copy a handle object, MATLAB copies the handle, but does not copy the data stored in the object properties. The copy refers to the same object as the original handle. If you change a property value on the original object, the copied handle references the same change.
Use isequal when you want to determine if different handle objects have the same data in all object properties. Use == when you want to determine if handle variables refer to the same object. When comparing objects that contain dynamic properties, isequal always returns false .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With