2013-07-23 44 views
4

如何将新元素添加到结构数组中?我无法与空结构连接:如何在Matlab中将新元素添加到结构数组中?

>> 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. 

那么是否有可能添加空字段的新元素?

UPDATE

我发现我可以添加新的元素,如果我同时添加新的领域:

>> 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 

令人难以置信的是,没有直通!可能有一些冒号相当于结构?

+0

你可以这样做:'a(n)= a(1)' – Dan

回答

3

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

让我们用b来表示你的第二个结构。正如你已经检查,下面就不行的,因为结构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
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: [] 
相关问题