Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird MATLAB behavior when having containers.Map as a class property

I create my own class as below:

classdef testClass < handle
    properties
        value;
        map = containers.Map('KeyType','double','ValueType','any');
    end
end

My goal is for each object of testClass to maintain its own map. However, it turns out that there is only one map object that for the whole class: all objects of testClass access to the same containers.Map. For example, if I create two objects as follows

a = testClass;
b = testClass;

a.value = 'a';
b.value = 'b';

a.map(1) = 123;
b.map(2) = 321;

It ends up both a and b's map contains two key-value pairs:

>> a
a = 
  testClass handle

    Properties:
      value: 'a'
        map: [2x1 containers.Map]

>> b
b = 
  testClass handle

    Properties:
      value: 'b'
        map: [2x1 containers.Map]
    Methods, Events, Superclasses

Both (key,value) pairs (1,123) and (2,321) appears in both a.map and b.map

>> a.map.keys
ans = 
    [1]    [2]
>> a.map.values
ans = 
    [123]    [321]

>> b.map.keys
ans = 
    [1]    [2]
>> b.map.values
ans = 
    [123]    [321]

Is this a bug? How can I keep independent containers.Map for each class object?

like image 986
chriscow Avatar asked Oct 23 '25 14:10

chriscow


1 Answers

The problem is not that testClass is a handle, but rather that the initial value specified in the properties block is not evaluated when you think it is. MATLAB calculates the default value of class properties only once when the class is loaded, and then gives that value to each new instance of your class.

You can see this by looking at the metaclass for your testClass. For example:

c = testClass;
c.map(1) = 42;
hc = ?testClass;
hc.PropertyList(2).DefaultValue.keys % returns [1]
hc.PropertyList(2).DefaultValue.values % returns [42]

If you want each instance to have a different map, you must construct the map explicitly in the constructor. (And yes, I've been there, done that).

like image 52
Edric Avatar answered Oct 26 '25 04:10

Edric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!