首页 > 解决方案 > 如何在matlab的for循环中向地图添加值?

问题描述

考虑到这段代码:

T = table(categorical({'M';'F';'M'}),[45;32;34],logical([1;0;0]),...
          'VariableNames',{'Gender','Age','Vote'},...
          'RowNames',{'NY';'CA';'MA'});
M = containers.Map('KeyType','int32','ValueType','any');
M(1) = T;

现在,我想通过在循环内的映射中添加另一个表(这里是同一个表)M到现有键来扩展这些值。我试过了:

for i=1:5
    if isKey(M, 1)
        cur_content = M.values;
        cur_content{end+1} = T;
        M(1) = cur_content;
    end
end

所以,我在地图中的预期内容应该是这样的:

Key: 1, {table_1}, {table_2}, {table_3}, {table_4}, {table_5}
Key: n, {table_1}, ... {table_k}

我在这里做错了什么?

标签: matlab

解决方案


首先,您希望将单元格数组作为分配给键的值:

M(1) = {T};

接下来,您要扩展此元胞数组,而不是values地图的内部数组:

cur = M(1);
cur{end+1} = T;
M(1) = cur;

那有意义吗?


推荐阅读