我想知道 MATLAB 中是否有一种方法可以像 Python 一样创建字典。
我有几个端口名称和端口类型,我想创建一个像这样的字典:
dict = {PortName : PortType, PortName : PortType, ...}
Run Code Online (Sandbox Code Playgroud)
编辑:由于 R2022b Matlab 有一个dictionary类型,建议在containers.Map.
最接近的类比是containers.Map:
\n\n\n
containers.Map:将值映射到唯一键的对象
键是字符向量、字符串或数字。这些值可以具有任意类型。
\n要创建映射,您需要传递containers.Map一个键元胞数组和一个值元胞数组(还有其他可选输入参数):
>> dict = containers.Map({ \'a\' \'bb\' \'ccc\' }, { [1 2 3 4], \'Hey\', {2 3; 4 5} });\n>> dict(\'a\')\nans =\n 1 2 3 4\n>> dict(\'bb\')\nans =\n \'Hey\'\n>> dict(\'ccc\')\nans =\n 2\xc3\x972 cell array\n {[2]} {[3]}\n {[4]} {[5]}\nRun Code Online (Sandbox Code Playgroud)\n您还可以将键值对附加到现有映射:
\n>> dict(\'dddd\') = eye(3);\n>> dict(\'dddd\')\nans =\n 1 0 0\n 0 1 0\n 0 0 1\nRun Code Online (Sandbox Code Playgroud)\n然而,根据您想要做什么,可能还有更多类似于 Matlab 的方法可以实现。地图在 Matlab 中的使用并不像字典在 Python 中那样广泛。
\n您可以使用containers.Map按照 Luis Mendo 在另一个答案中的建议使用,但我认为在这种情况下 astruct更简单:
>> dict = struct(\'a\',[1 2 3 4], \'bb\',\'Hey\', \'ccc\',{2 3; 4 5});\n>> dict.(\'a\')\nans =\n 1 2 3 4\n>> dict.a\nans =\n 1 2 3 4\n>> dict.b\nans =\n \'Hey\'\n>> dict.ccc\nans =\n 2\xc3\x972 cell array\n {[2]} {[3]}\n {[4]} {[5]}\n\n>> dict.dddd = eye(3);\n>> dict.(\'eee\') = eye(3);\n>> dict.dddd\nans =\n 1 0 0\n 0 1 0\n 0 0 1\nRun Code Online (Sandbox Code Playgroud)\n\n也就是说,该结构始终使用.(\'name\')或 简单地进行索引.name。但与“name”不同,“name”的含义是有限制的(必须是有效的变量名)Map.
请参阅另一个答案以了解这两种方法之间的重要区别。
\nMATLAB R2022b 有一种新的dictionary数据类型,明显优于containers.Map. 描述它的教程可以在 MATLAB 博客上找到:https://blogs.mathworks.com/matlab/2022/09/15/an-introduction-to-dictionaries-associative-arrays-in-matlab/
例如:
\nnames = ["Mike","Dave","Bob"];\nweights = [89,75,68]; % weight in kilograms\ngym = dictionary(names,weights) % Vectorised constructor. Performs elementwise mapping.\nRun Code Online (Sandbox Code Playgroud)\n给出
\ngym = \n\n dictionary (string \xe2\x9f\xbc double) with 3 entries:\n \n "Mike" \xe2\x9f\xbc 89\n "Dave" \xe2\x9f\xbc 75\n "Bob" \xe2\x9f\xbc 68\nRun Code Online (Sandbox Code Playgroud)\n