英文:
How to create Matlab dictionaries that use arrays as keys
问题
为了将以1x2双精度数组给出的方向简单翻译成字符串,我想要使用新的字典功能。然而,将数组用作键会导致字典的意外行为。
为了将方向翻译成字符串,我尝试在MATLAB中使用新的字典功能,如下面的示例所示。
orientation_dict = dictionary([1, 0], "south", [-1, 0], "north", [0, 1], "east", [0, -1], "west");
然而,这将导致以下结果。
orientation_dict =
dictionary (double ⟼ string) with 3 entries:
1 ⟼ "east"
0 ⟼ "west"
-1 ⟼ "west"
我想要的字典应该如下所示。
orientation_dict =
dictionary (1x2 double ⟼ string) with 4 entries:
[1, 0] ⟼ "south"
[-1, 0] ⟼ "north"
[0, 1] ⟼ "east"
[0, -1] ⟼ "west"
在当前的MATLAB 2023a版本中,是否可以将数组用作键?
英文:
To simply translate directions given as a 1x2 double array into strings, I want to use the new dictionary function. However giving arrays as a key results in an unexpected behavior of the dictionary.
To translate orientations into strings I tried to use the new dictionary function in MATLAB like the following example.
orientation_dict = dictionary([1, 0],"south", [-1, 0],"north", [0, 1],"east", [0, -1],"west");
However this results in
orientation_dict =
dictionary (double ⟼ string) with 3 entries:
1 ⟼ "east"
0 ⟼ "west"
-1 ⟼ "west"
The dictionary I want would look like this
orientation_dict =
dictionary (1x2 double ⟼ string) with 4 entries:
[1, 0] ⟼ "south"
[-1, 0] ⟼ "north"
[0, 1] ⟼ "east"
[0, -1] ⟼ "west"
Is using arrays as keys even possible in the current MATLAB 2023a version?
答案1
得分: 3
这个技巧是使用标量 cell
实例作为键:
>> orientation_dict = dictionary({[1, 0]},"south", {[-1, 0]}, ...
"north", {[0, 1]},"east", {[0, -1]},"west")
orientation_dict =
dictionary (cell ⟼ string) with 4 entries:
{[1 0]} ⟼ "south"
{[-1 0]} ⟼ "north"
{[0 1]} ⟼ "east"
{[0 -1]} ⟼ "west"
(如果您想存储非标量值,也需要采用相同的方法)
英文:
The trick is to use scalar cell
instances as the key:
>> orientation_dict = dictionary({[1, 0]},"south", {[-1, 0]}, ...
"north", {[0, 1]},"east", {[0, -1]},"west")
orientation_dict =
dictionary (cell ⟼ string) with 4 entries:
{[1 0]} ⟼ "south"
{[-1 0]} ⟼ "north"
{[0 1]} ⟼ "east"
{[0 -1]} ⟼ "west"
(The same approach is required if you want to store non-scalar values too)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论