如何将字段名称及其内容复制到 matlab 中的另一个结构变量

How do I copy fields names and their contents to another struct variable in matlab

假设我有这个代码:

a=struct;
a(1).a='a1';
a(1).b='b1';
a(1).c='c1';

a(2).d='a1';
a(2).e='b1';
a(2).f='c1';

a(3).g='a1';
a(3).h='b1';
a(3).i='c1';

现在,我只想将 a(2) 及其所有字段复制到 b(1),但我不知道 a 中有哪些字段。例如:

b=struct;
b(1)=a(2);
b(2)=a(3);

(如果我这样做,我会收到错误消息: 'Subscripted assignment between dissimilar structures.') 我该怎么做?

s1为输入结构,s2为所需的输出结构。这是一种基于 struct2cellcell2struct 的方法来获得 s2 -

%// Given input struct
s1=struct;
s1(1).a='A';
s1(1).b='B';
s1(1).c='C';

s1(2).d='D';
s1(2).e='E';
s1(2).f='F';

s1(3).g='G';
s1(3).h='H';
s1(3).i='I';

idx = [2 3]; %// indices of struct data to be copied over from s1 to s2

fn = fieldnames(s1)   %// get fieldnames
s1c = struct2cell(s1) %// Convert s1 to its cell array equivalent

%// Row indices for the cell array that has non-empty cells for the given idx
valid_rowidx = ~all(cellfun('isempty',s1c(:,:,idx)),3)

%// Construct output struct
s2 = cell2struct(s1c(valid_rowidx,:,idx),fn(valid_rowidx))

因此,您最终会得到输出 -

s2 = 
1x2 struct array with fields:
    d
    e
    f
    g
    h
    i

最后,您可以像这样验证输出结构的内容 -

%// Verify results
check1 = [s1(2).d s1(2).e s1(2).f]
check2 = [s2(1).d s2(1).e s2(1).f]

check3 = [s1(3).g s1(3).h s1(3).i]
check4 = [s2(2).g s2(2).h s2(2).i]

产生 -

check1 =
DEF
check2 =
DEF
check3 =
GHI
check4 =
GHI

不要声明 b。然后使用 deal:

a=struct;
a(1).a='a1';
a(1).b='b1';
a(1).c='c1';

a(2).d='a1';
a(2).e='b1';
a(2).f='c1';

a(3).g='a1';
a(3).h='b1';
a(3).i='c1';

b(1) = deal(a(2));
b(2) = deal(a(3));

如果在使用 deal 之前声明 b,则必须将 b 声明为包含 a 具有的所有字段的结构。在这种情况下,您不再需要 'deal',只需像您一样正常分配它们即可。