如何确定结构体和元胞数组之间的相等性

How to determine equality between structures and cell arrays

我很困惑为什么 isequal 在以下两个用例中不起作用:

>> tempStruct = struct('a', 1, 'b', 2, 'c', 3)

tempStruct =

  scalar structure containing the fields:

    a =  1
    b =  2
    c =  3

>> tempCArray = {1 2 3}

tempCArray =
{
  [1,1] =  1
  [1,2] =  2
  [1,3] =  3
}

在我看来 tempStructtempCArray 在概念上是相等的,但是

>> isequal(tempStruct, tempCArray)

ans = 0

如果说这是因为 tempStruct 的索引结构与 tempCArray 不同,对吗?例如:

>> tempStruct(2)
error: A(I): index out of bounds; value 2 out of bound 1
>> tempCArray(2)
ans =
{
  [1,1] =  2
}

但是,然后我尝试将 tempStruct 转换为元胞数组:

>> struct2cell(tempStruct)

ans =
{
  [1,1] =  1
  [2,1] =  2
  [3,1] =  3
}

这现在看起来与 tempCArray 相同。然而...

>> isequal(struct2cell(tempStruct), tempCArray)

ans = 0

为什么会这样?

struct2cell(tempStruct)tempCArray 不相同。

  • tempCArray中,索引为[1,1], [1,2], [1,3]
  • struct2cell(tempStruct)中,索引是[1,1], [2,1], [3,1]

这些显然不是同一个元胞数组。 tempCArray 是行元胞向量,而 struct2cell(tempStruct) 是列元胞向量。

如果你想让两者相等,这样做:

>> isequal(struct2cell(tempStruct)', tempCArray)

ans = 1

如果您使用 ' 转置任一元胞数组,则它们将相等。

编辑:

如果您希望成为 row/column 不可知论者,请改用以下代码:

tempStructCell = struct2cell(tempStruct);    
isequal(tempStructCell(:), tempCArray(:));