【问题标题】:MATLAB: Confusing behavior with containers.MapMATLAB:使用containers.Map 混淆行为
【发布时间】:2015-10-27 22:16:57
【问题描述】:

我在使用特定键访问值时遇到了一些问题(我使用的是 containers.Map)。我设置了一个名为team_dict 的地图,看起来像:

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

我试着去做

url = team_dict(currentKey); 

访问 Map 中 key 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。

知道为什么会这样吗?

谢谢

【问题讨论】:

    标签: matlab


    【解决方案1】:

    由于allKeys = keys(team_dict); 返回一个键的单元格数组,当您获得currentKey = allKeys(i); 时,您将拥有一个包含该键的单元格。

    由于您的键都是字符串,disp(currentKey); 仍然有效。但是url = team_dict(currentKey); 会导致错误,因为currentKey 现在是一个字符串单元格。

    你要做的就是修改这一行:

    currentKey = allKeys(i);
    

    currentKey = allKeys{i};
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 2016-06-27
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多