필터 지우기
필터 지우기

How to add (combine) together two structures with the same fields?

조회 수: 268 (최근 30일)
Benson Gou
Benson Gou 2021년 6월 11일
편집: dleal 2022년 4월 20일
Dear All,
I have two structures A and B with the same fields. How can I combine them together to form a new structure?
For example, A = struct('field1', array1, 'field2', array2); B = struct('field1', array3, 'field2', array4). A and B have the same fields 'field1' and 'field2'. I want to combine A and B together to obtain structure C = struct('field1', [array1; array3], 'field2', [array2; array4]). array1 and array3 have the same number of columns, and array2 and array4 have the same number of columns.
Thanks.
Benson
  댓글 수: 2
Geoff Hayes
Geoff Hayes 2021년 6월 11일
Benson - what should the new structure look like? If A and B have the same fields, then does that mean that the combined A and B have array fields? Please illustrate with a small example.
Benson Gou
Benson Gou 2021년 6월 11일
Hi, Geoff,
Please see my question again.
Thanks.
Benson

댓글을 달려면 로그인하십시오.

채택된 답변

KSSV
KSSV 2021년 6월 11일
clc; clear ;
s1.name = 'Tom' ;
s1.sex = 'm';
s1.age = 25 ;
s2.name = 'Harry' ;
s2.sex = 'f';
s2.age = 26 ;
% Structure array
s = [s1 ; s2]
% Single structure
S = struct ;
aField = fields(s1);
for i = 1:3
S.(aField{i}) = {s1.(aField{i}) s2.(aField{i})} ;
end
S
  댓글 수: 4
Stephen23
Stephen23 2021년 6월 11일
Note that the loop does not concatenate the field data as your qustion shows, but instead nests the field data within a 1x2 cell array.
dleal
dleal 2022년 4월 20일
편집: dleal 2022년 4월 20일
Hi, I have a similar question..
given two structs with numerical values:
S1 = struct; S2 = struct;
S1.A = [1,2]; S1.B = [3, 4];
S2.A = [9,10]; S2.B = [11,12];
is there a way to combine them into S3 so that S3.A = [1,2,9,10] and S3.B = [3,4,11,12]?
I would just do it with a for loop, but I wonder if there is a way that might be less expensive:
S3.A = [];
S3.B = [];
fNames = fieldnames(S1);
for jj = 1:numel(fNames)
S3.(fNames(jj) = [S1.(fNames(jj)) , S2.(fNames(jj)) ];
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by