anon_swe
anon_swe

Reputation: 9345

MATLAB: Confusing behavior with containers.Map

I'm having some trouble accessing the value using a particular key (I'm using containers.Map). I've set up a Map called team_dict that looks something like:

{ 'Columbia' : 'www.columbia.com', 'Bates' : 'www.bates.com', ... }

I try to do

url = team_dict(currentKey); 

to access the value in the Map corresponding to the key currentKey.

Here's the relevant code:

allKeys = keys(team_dict);

%loop through all keys
for i = 1 : length(allKeys)
    %for current key (team name), getTeam
    currentKey = allKeys(i);
    disp(currentKey);
    url = team_dict(currentKey);
end

I get this error:

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

Error in project (line 27)
    teamPlayers = getTeam(team_dict(currentKey), currentKey);

The strange thing is that 'Columbia' prints out correctly when I call disp(currentKey). Also, in the interactive prompt, when I do

team_dict('Columbia')

I get back the correct URL.

Any idea why this is happening?

Thanks

Upvotes: 0

Views: 210

Answers (1)

scmg
scmg

Reputation: 1894

Since allKeys = keys(team_dict); returns a cell array of keys, when you get currentKey = allKeys(i); you will have a cell containing the key.

Since your keys are all string, disp(currentKey); still works. But url = team_dict(currentKey); will result in error since currentKey is now a cell of string.

What you have to do is just modification this line:

currentKey = allKeys(i);

to

currentKey = allKeys{i};

Upvotes: 1

Related Questions