user2287094
user2287094

Reputation: 277

How to create a Map Container (HashMap) of an object array in matlab?

Hy!

I have an Object array: bs_ek (objects with fields, methods). I would like to create a hashmap.

    for i= 1: length(bs_ek)
    k(i)=bs_ek(i).id;
    end


    rainfallMap = containers.Map(k, bs_ek)

But I get this error message:

Error using containers.Map Specified value type does not match the type expected for this container.

I created a new CELL array with bs_ek elements:

    value2  = {bs_ek(1), bs_ek(2), bs_ek(3),bs_ek(4), bs_ek(5), bs_ek(6), bs_ek(7),    bs_ek(8), bs_ek(9), bs_ek(10), bs_ek(11) };

and it's work:

    rainfallMap = containers.Map(k, value2)

This made a Map. But the lenght of bs_ek not fixed (not 11 every time) and I would like to change this number each start.

Thanks in advance.

Upvotes: 1

Views: 630

Answers (1)

Ali
Ali

Reputation: 451

This can easily be fixed with (assuming that the id is a signed integer):

rainfallMap = containers.Map('KeyType', 'int32', 'ValueType', 'any');
for i = 1:length(bs_ek)
    rainfallMap(bs_ek(i).id) = bs_ek(i);
end

But there is a problem that I don't have an answer for: The above method, will merely copy bs_ek(i) to the hash map, so if you change bs_ek later, the changes will not be reflected in the hash map.

Upvotes: 1

Related Questions