Home Ask Login Register

Developers Planet

Your answer is one click away!

user3716193 February 2016

How do I use containers.Map in Matlab with a cell array as the keys and a vector of integers as the values

I have a cell array that contains words like 'a', 'b', and 'c' for example. What I want to be able to do is use Matlab's containers.Map to make a hash table that I can add values to for each key and be able to look them up quickly. I am able to do this if I do not initialize my containers.Map object beforehand as follows but it does not allow me (or at least I haven't found a way) to add more key/value pairs later and makes it so that I have to reinitialize the object during each iteration of a loop:

    key = {'a','b','c'};
    newmap = containers.Map(key,[1,2,3]);

My problem is that I need to be able to continually add new keys to the hash table and therefore cannot keep initializing the containers.Map object each time, I want one long hash table with all the keys and values that I get while in a loop.

Here is the code that I am trying to get working, I want to be able to add the keys to the containers.Map object newmap and their corresponding values at the same time. The keys are always strings in a cell array and the values are always integers:

    key = {'a','b','c'};
    val = [1,2,3];
    newmap = containers.Map(); % containers.Map object initialization
    newmap(key) = val;

My desired output would something like this:

    ans = 1 2 3

Attempts at solving this:

I have tried converting the cell array of keys using cellstr() and char() but haven't had any luck with these. I seem to keep getting this error when trying this:

    Error using containers.Map/subsref
    Specified key type does not match the type expected for this container.

Thanks for any help.


Oleg February 2016

% Initialize
map = containers.Map('KeyType','char','ValueType','double');

% Assume you get these incrementally
key = {'a','b','c'};
val = [1,2,3];

% Add incrementally
for ii = 1:numel(key)
    map(key{ii}) = val(ii);

You can retrieve all values at once for a given set of keys, but you will get a cell array. No way around it, but you can convert with cell2mat(), or retrieve incrementally with a loop map(key{ii})

% Retrieve all

ans = 
    [1]    [2]    [3]

Post Status

Asked in February 2016
Viewed 1,270 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life