如何在Matlab中向结构数组中添加新元素?

时间:2013-07-23 08:38:36

标签: arrays matlab struct

如何向结构数组添加新元素?我无法与空结构连接:

>> a=struct;
>> a.f1='hi'

a = 

    f1: 'hi'

>> a.f2='bye'

a = 

    f1: 'hi'
    f2: 'bye'

>> a=cat(1,a,struct)
Error using cat
Number of fields in structure arrays being concatenated do not match. Concatenation of structure arrays requires that these arrays have the same set of
fields.

那么可以添加带空字段的新元素吗?

更新

我发现如果我同时添加新字段,我可以添加新元素:

>> a=struct()

a = 

struct with no fields.

>> a.f1='hi';
>> a.f2='bye';
>> a(end+1).iamexist=true

a = 

1x2 struct array with fields:

    f1
    f2
    iamexist

令人难以置信的是,没有直道!结构可能有一些冒号吗?

2 个答案:

答案 0 :(得分:3)

您只能连接具有相同字段的结构。

让我们用b来表示你的第二个结构。正如您已经检查过的,以下内容不起作用,因为struct a有两个字段而b没有:

a = struct('f1', 'hi', 'f2', 'bye');
b = struct;
[a; b]

然而,这有效:

a = struct('f1', 'hi', 'f2', 'bye');
b = struct('f1', [], 'f2', []);
[a; b]

如果您想“自动”创建一个与a字段相同的空结构(无需键入所有字段),您可以使用Dan's trick或执行此操作:

a = struct('f1', 'hi', 'f2', 'bye');

C = reshape(fieldnames(a), 1, []); %// Field names
C(2, :) = {[]};                    %// Empty values
b = struct(C{:});

[a; b]

我还建议您阅读以下内容:

  1. Stack Overflow - What are some efficient ways to combine two structures
  2. Stack Overflow - Update struct via another struct
  3. Loren on the Art of MATLAB - Concatenating structs

答案 1 :(得分:3)

如果你懒得再次输入字段或者有太多字段,那么这里有一个捷径来获得一个空字段的结构

a.f1='hi'
a.f2='bye'

%assuming there is not yet a variable called EmptyStruct
EmptyStruct(2) = a;
EmptyStruct = EmptyStruct(1);

现在EmptyStruct是您想要的空结构。所以要添加新的

a(2) = EmptyStruct; %or cat(1, a, EmptyStruct) or [a, EmptyStruct] etc...



a(2)

ans = 

    f1: []
    f2: []