0

I can't seem to figure out how containers.Map works. It's doing okay with characters and numbers, but flips out when I try to feed it arrays. How do I make something like this?

function test
global a

a = containers.Map();
a(pi) = 3:14;
a(5) = 4:2:10;

end
horchler
  • 18,384
  • 4
  • 37
  • 73
Raksha
  • 1,572
  • 2
  • 28
  • 53

2 Answers2

4

The problem is that you're using the default constructor for the containers.Map class. From the help:

myMap = containers.Map() creates an empty object myMap that is an
instance of the MATLAB containers.Map class. The properties of myMap
are Count (set to 0), KeyType (set to 'char'), and ValueType (set to
'any').

In other words, you can only use strings as keys in this form. If you want to use arbitrary double precision values as keys, you need to specify the 'KeyType' and 'ValueType' in the constructor:

myMap = containers.Map('KeyType', kType, 'ValueType', vType) constructs
a Map object with no data that uses a key type of kType, and a value
type of vType. Valid values for kType are the strings: 'char',
'double', 'single', 'int32', 'uint32', 'int64', 'uint64'. Valid values
for vType are the strings: 'char', 'double', 'single', 'int8', 'uint8',
'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'logical', or
'any'. The order of the key type and value type arguments is not
important, but both must be provided.

In your example:

a = containers.Map('KeyType','double','ValueType','any');
a(pi) = 3:14;
a(5) = 4:2:10;

Note, however, that a 'ValueType' of 'double' will not work for non-scalar values. Alternatively, you can specify your keys and values directly with cell arrays via the constructor and let it do the work of figuring out what types to use:

a = containers.Map({pi,5},{3:14 4:2:10});
horchler
  • 18,384
  • 4
  • 37
  • 73
  • Yay! Perfect, thank you :] would you mind also answering a follow-up question please? :D http://stackoverflow.com/questions/30407920/non-scalar-in-uniform-output-error-in-arrayfun-how-to-fix – Raksha May 23 '15 at 01:15
0

There is no issue with putting arrays, cells, even other maps inside a map. The issue is your key field. As far as I know, Maps use strings as keys. So your current code won't work, but this would

function test
    global a

    a = containers.Map();
    a('pi') = 3:14;
    a('5') = 4:2:10;

end
andrew
  • 2,451
  • 1
  • 15
  • 22
  • containers.Map can use 'char', 'double', 'single', 'int32', 'uint32', 'int64', or 'uint64' as input ... so a number pi should be fine ... i don't think that's the problem ... I think it might be trying to pull "pi"'th element from a, kind of like y(2) would output "2" if y is an array y = 1 2. But I'm not sure how to tell it that a(pi) is an array, not an element of an array – Raksha May 23 '15 at 00:10