Matlab - handle object properties of unique objects for a single object?

I am confused about 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 am creating two books:

 iliad = Book; odyssey = Book; 

If I check if the Iliad and Odyssey are the same:

 eq(iliad, odyssey) 

I get:

 ans = logical 0 

So far so good

But if I check if the pages 1 or the idea are the same:

 eq(iliad.page1, odyssey.page1) 

I get:

 ans = logical 1 

This is not good! This means that if I change Odyssey page1, the iliad page will also change. What do I misunderstand? How do I solve this problem?

+5
source share
1 answer

This seems to be related to how MATLAB evaluates the default values. In the documentation for Properties containing objects :

MATLAB® evaluates default property values ​​only once when loading a class. MATLAB does not overestimate the purpose of each time you create an object of this class. If you assign an object as the default property to the value in the class definition, MATLAB calls the constructor for this object only once when the class is loaded.

It should further be noted that:

The evaluation of default property values ​​occurs only when the value is first needed, and only once when MATLAB initializes the class first. MATLAB does not overestimate the expression every time you instantiate a class.

Which describes the equality that you see between books. MATLAB essentially defines class definitions , so as long as your Page objects are different from each other in the book, they will be the same in the books, because MATLAB only sets default values ​​once.

To avoid this, you can instantiate Page objects in the Book constructor:

 classdef Book < handle properties page1 page2 end methods function self = Book() self.page1 = Page; self.page2 = Page; end end end 

Which gives the desired behavior:

 >> iliad = Book; >> odyssey = Book; >> eq(iliad.page1, odyssey.page1) ans = logical 0 
+6
source

Source: https://habr.com/ru/post/1275961/


All Articles