2015-10-27 45 views
0

我在使用特定鍵(我使用containers.Map)訪問值時遇到了一些麻煩。我已經成立了一個名爲地圖team_dict看起來像:MATLAB:容器混淆行爲。地圖

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

我嘗試做

url = team_dict(currentKey); 

對應於關鍵currentKey地圖來訪問值。

下面是相關代碼:

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 

我得到這個錯誤:

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); 

奇怪的是, '哥倫比亞' 正確打印出來,當我打電話disp(currentKey)。另外,在交互式提示中,當我做

team_dict('Columbia') 

我找回正確的URL。

任何想法爲什麼會發生這種情況?

感謝

回答

1

由於allKeys = keys(team_dict);返回鍵的單元陣列,當你得到currentKey = allKeys(i);你將有包含密鑰的單元格。

由於您的密鑰都是字符串,所以disp(currentKey);仍然有效。但url = team_dict(currentKey);將導致錯誤,因爲currentKey現在是一個字符串的單元格。

,你所要做的僅僅是修飾這一行:

currentKey = allKeys(i); 

currentKey = allKeys{i}; 
+1

你介意擬訂之間{的差異}和[]或指着我的多方向關於它的信息?忽略,只是發現:http://www.mathworks.com/help/matlab/matlab_prog/what-is-a-cell-array.html – bclayman

+0

是的,這是鏈接。如果你的問題得到解決,你介意接受答案嗎? – scmg