Bug, feature, or misuse? Issue with map container

I'm using Matlab 2012a and I'm trying out map containers and I came across what I think is a bug. I have a variable which is a structure and one of the elements in this structure is a map container. I want to make a copy of the map container and make it a new element in the structure. I then update a value on one of the container values and I find that both containers are updated with the new value.
For example:
X = 10;
Test.Obj1 = containers.Map({'X'},{X});
when I examine the contents, Test.Obj1('X'), I get 10. Now I make a new container and set it equal to the Obj1 container
Obj2 = Test.Obj1;
Now change the value in this new container
Obj2('X') = 20;
Now if I examine Test.Obj1('X') it now equals 20 instead of 10.
Is this a bug or am I misunderstanding containers?
Thanks!

3 件のコメント

Jason
Jason 2013 年 2 月 27 日
Ok, I just read that because this is a handle class, a copy points back to the original.
I'm not familiar with working with objects in general, so how do I make a copy of a map container that doesn't point back to the original?
Jason
Jason 2013 年 2 月 27 日
Ok, the solution I came up with was to create a function that creates a the container and when call that function to create the "copy".
Not sure if there's a better solution out there so would welcome comments.
Thanks!
Honglei Chen
Honglei Chen 2013 年 2 月 27 日
I don't know what's in your function but I have an example below in my answer.

サインインしてコメントする。

回答 (1 件)

Honglei Chen
Honglei Chen 2013 年 2 月 27 日

0 投票

Here is an example
h1 = containers.Map({'X','Y'},{'X','Y'})
h2 = containers.Map(h1.keys,h1.values)
h2('Z') = 'Z'
h1
HTH

1 件のコメント

P Lepage
P Lepage 2020 年 10 月 29 日
It's crazy that there is no official feature to do that, but can manage to find a workaround.
I have data structure made of map<char, map<... etc>>. Since maps stays handles when put in other maps, the solution you provided does not work.
One day I was experimenting with Data Dictionaries (Simulink) and found that the wrapper class Entry returns a deep clone of the object it holds when you call getEntry.
I ended up writing a function that uses this accidental feature to clone my data structure, but it's to slow to be used in a program.
Conclusion : Matlab can break deep references to handle objects, but it wont let you.

サインインしてコメントする。

カテゴリ

質問済み:

2013 年 2 月 27 日

コメント済み:

2020 年 10 月 29 日

Community Treasure Hunt

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

Start Hunting!

Translated by