### 在MATLAB中组合两个结构有哪些有效的方法？

17753 观看

5回复

536 作者的声誉

``````A.field1 = 1;
A.field2 = 'a';

B.field3 = 2;
B.field4 = 'b';
``````

``````C.field1 = 1;
C.field2 = 'a';
C.field3 = 2;
C.field4 = 'b';
``````

### 回应 (5)

2

4678 作者的声誉

psuedocode：我不记得实际的语法。

``````A.field1 = 1;
A.field2 = 'a';
A.field3 = struct B;
``````

``````C.A = struct A;
C.B = struct B;
``````

``````C.A.field1;
C.A.field2;
C.B.field3;
C.B.field4;
``````

18

7356 作者的声誉

``````M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];
C=struct(M{:});
``````

``````M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];

[tmp, rows] = unique(M(1,:), 'last');
M=M(:, rows);

C=struct(M{:});
``````

4

110305 作者的声誉

``````% SETDEFAULTS sets the default structure values
%    SOUT = SETDEFAULTS(S, SDEF) reproduces in S
%    all the structure fields, and their values,  that exist in
%    SDEF that do not exist in S.
%    SOUT = SETDEFAULTS(S, SDEF, OVERRIDE) does
%    the same function as above, but if OVERRIDE is 1,
%    it copies all fields of SDEF to SOUT.

function sout = setdefaults(s,sdef,override)
if (not(exist('override','var')))
override = 0;
end

sout = s;
for f = fieldnames(sdef)'
cf = char(f);
if (override | not(isfield(sout,cf)))
sout = setfield(sout,cf,getfield(sdef,cf));
end
end
``````

``````% SETDEFAULTS2 sets the default structure values
%    SOUT = SETDEFAULTS(S, SDEF) reproduces in S
%    all the structure fields, and their values,  that exist in
%    SDEF that do not exist in S.

function sout = setdefaults2(s,sdef)
sout = sdef;
for f = fieldnames(s)'
sout = setfield(sout,f{1},getfield(s,f{1}));
end
``````

``````>> S1 = struct('a',1,'b',2,'c',3);
>> S2 = struct('b',4,'c',5,'d',6);
>> setdefaults2(S1,S2)

ans =

b: 2
c: 3
d: 6
a: 1

>> setdefaults2(S2,S1)

ans =

a: 1
b: 4
c: 5
d: 6
``````

5

16939 作者的声誉

``````a.f1 = 1;
a.f2 = 2;
b.f2 = 3;
b.f4 = 4;

s = catstruct(a,b)
``````

``````s =

f1: 1
f2: 3
f3: 4
``````

8

28521 作者的声誉

`help setstructfields`

`````` setstructfields Set fields of a structure using another structure
setstructfields(STRUCTIN, NEWFIELDS) Set fields of STRUCTIN using
another structure NEWFIELDS fields.  If fields exist in STRUCTIN
but not in NEWFIELDS, they will not be changed.
``````

“原始”结构：

``````% struct with fields 'color' and 'count'
s = struct('color','orange','count',2)

s =
color: 'orange'
count: 2
``````

``````% struct with fields 'count' and 'shape'
s2 = struct('count',4,'shape','round')

s2 =
count: 4
shape: 'round'
``````

``````>> s = setstructfields(s,s2)
s =
color: 'orange'
count: 4
shape: 'round'
``````