如何制作数组字典?

How to make a dictionary of arrays?

我似乎无法弄清楚 containers.Map 是如何工作的。它可以处理字符和数字,但当我尝试向它提供数组时,它就会出错。我该如何制作这样的东西?

function test
global a

a = containers.Map();
a(pi) = 3:14;
a(5) = 4:2:10;

end

在地图中放置数组、单元格甚至其他地图都没有问题。问题是你的关键领域。据我所知,地图使用字符串作为键。所以您当前的代码将不起作用,但这会

function test
    global a

    a = containers.Map();
    a('pi') = 3:14;
    a('5') = 4:2:10;

end

问题是您正在使用 containers.Map class 的默认构造函数。来自帮助:

myMap = containers.Map() creates an empty object myMap that is an
instance of the MATLAB containers.Map class. The properties of myMap
are Count (set to 0), KeyType (set to 'char'), and ValueType (set to
'any').

换句话说,您只能使用字符串作为这种形式的键。如果要使用任意双精度值作为键,需要在构造函数中指定'KeyType''ValueType'

myMap = containers.Map('KeyType', kType, 'ValueType', vType) constructs
a Map object with no data that uses a key type of kType, and a value
type of vType. Valid values for kType are the strings: 'char',
'double', 'single', 'int32', 'uint32', 'int64', 'uint64'. Valid values
for vType are the strings: 'char', 'double', 'single', 'int8', 'uint8',
'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'logical', or
'any'. The order of the key type and value type arguments is not
important, but both must be provided.

在你的例子中:

a = containers.Map('KeyType','double','ValueType','any');
a(pi) = 3:14;
a(5) = 4:2:10;

但是请注意,'double''ValueType' 不适用于非标量值。或者,您可以通过构造函数直接使用 cell arrays 指定键和值,并让它完成确定要使用的类型的工作:

a = containers.Map({pi,5},{3:14 4:2:10});