如何创建使用数组作为键的Matlab字典

huangapple go评论49阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年6月16日 00:06:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483539.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定