使用MATLAB Map Containers而不首先转换为单元阵列

时间:2012-03-08 15:57:28

标签: matlab

说我有以下两个数组:

keys   = uint32([1:100])';
values = uint32([100:-1:1])';

我可以按如下方式定义地图容器:

newMap = containers.Map(keys,values);

newMap = 
  containers.Map handle
  Package: containers

  Properties:
        Count: 100
      KeyType: 'uint32'
    ValueType: 'uint32'
  Methods, Events, Superclasses

键和值的类型相同,uint32

但是,如果我想使用容器来映射新数组:

other_keys = uint32([5 9 10]);

我在文档中读到了我必须首先将other_keys转换为单元格数组:

>> newMap(other_keys)
Error using containers.Map/subsref
Specified key type does not match the type expected
for this container.

或:

values(newMap, other_keys);

Error using subsindex
Function 'subsindex' is not defined for values of
class 'containers.Map'.

使其发挥作用的唯一方法是:

values(newMap, num2cell(other_keys));

这可能需要很长的时间和很多内存!例如,如果我有1亿个数字,我会得到:

tic
my_uint32_array = uint32(1:100000000)
my_cell_array   = num2cell(my_uint32_array);
toc

Elapsed time is 27.956496 seconds.

其中:

  • my_uint32_array的大小为381.5 MB
  • my_cell array的大小为10.8GB 100x 大一倍!,即使这只是一个时间变量,因为我感兴趣在毕竟映射我的值)

考虑到我可以创建映射容器而不必先转换为单元格数组,有没有办法使用它们而不必先将我的键转换为单元格数组?

1 个答案:

答案 0 :(得分:2)

等等,我不明白。代码

values(newMap, num2cell(other_keys));

相当于

newMap.values(num2cell(other_keys));

仅在您的密钥是1:N数组时才有效。 否则,您没有采用正确的值。但如果密钥是1:N的数组,则不应使用Map。您只需定义uint32数组即可。

如果你的意思是你想做这样的事情:

for key=other_keys
   vals(end+1) = newMap(key);
end

你也可以尝试进行以下矢量化:

vals = arrayfun( @(x)(newMap(x)),other_keys);

虽然我不确定它会更快地运作。