在同一结构中加入两个不同大小的单元格

Join two different size cells in the same struct

我想将 2 个不同大小的单元格放在同一个 struct 中。例如:

a = {'one', 'two', 'three'};
b = {'four', 'five', 'six', 'seven'};

struct("setA", a, "setB", b);

每当我尝试这样做时,MATLAB 都会抛出以下错误:

error: struct: dimensions of parameter 2 do not match those of parameter 4

根据错误消息,问题出在单元格的尺寸上。此外,如果我从单元格 b 中删除一个元素,则该过程将无错误地完成:

a = {'one', 'two', 'three'};
b = {'four', 'five', 'six'};

struct("setA", a, "setB", b);

有什么建议吗?

您需要将单元格包裹在 另一个 单元格中以创建一个 标量 struct 在其字段中包含单元格。

struct('setA', {a}, 'setB', {b})

%   setA: {'one'  'two'  'three'}
%   setB: {'four'  'five'  'six'  'seven'}

默认情况下,struct 假定一个单元格意味着您需要一个多元素 struct,其中每个单元格元素将属于不同的 struct。它使用这些单元格的尺寸来确定结果 struct 的大小。在您的情况下,两个元胞数组(ab)的大小不同,因此会造成混淆。

通过将它们中的每一个包装在另一个元胞内,MATLAB 将创建一个包含您期望的元胞数组的标量结构。