Reputation: 813
C = {'hello', 'goodbye', 'hola', 'hello hellen', 'helmet', 'hellorheaven', 'hillsboro', 'say hello', 'myfellow'}
defaultval = 100
key = {'hello', 'goodbye', 'hola', 'hello hellen', 'helmet', 'hellorheaven', 'hillsboro', 'say hello', 'myfellow'}
value = [defaultval, defaultval, defaultval,defaultval,defaultval,defaultval,defaultval,defaultval,defaultval]
mapObj = containers.Map(key,value )
for n = 1:length(C)
d1 = strdist('goodfellow', C(n) )
disp(C(n) )
disp(mapObj('hello' ) )
mapObj(C(n) ) = d1
end
In this case, I am trying to calculate string distance with a library function and save the distance into the map I created. But even though C is a array of char and so is the key type for my map. I can not use mapObj(C(n) ) to access and change my values. How do I fix this?
mapObj =
Map with properties:
Count: 9
KeyType: char
ValueType: double
I am trying to follow the example here https://www.mathworks.com/help/matlab/matlab_prog/modifying-keys-and-values-in-the-map.html where ticketMap('A479GY')
ans =
Sarah Latham
However, with my code, the error I receive
Error using containers.Map/subsasgn Specified key type does not match the type expected for this container.
Error in exercise01 (line 76) mapObj(C(n) ) = d1
Upvotes: 0
Views: 501
Reputation: 23685
As @excaza pointed out in his comment, the problem is all about indexing. Using round parentheses, you retrieve a cell. But your dictionary key is actually typed as string (to be exact, a char array). In order to extract the a char array from your cell array, you have to use curly braces. For more information about accessing data in cells, read this documentation.
keys = {'hello', 'goodbye', 'hola', 'hello hellen', 'helmet', 'hellorheaven', 'hillsboro', 'say hello', 'myfellow'};
keys_len = numel(keys);
vals = repmat(100,1,keys_len);
map = containers.Map(keys,vals);
for n = 1:keys_len
key = keys{n};
map(key) = strdist('goodfellow',key);
end
Upvotes: 1