2つの構造体を連結することは可能ですか?

조회 수: 24 (최근 30일)
MathWorks Support Team
MathWorks Support Team 2012년 9월 19일
STRUCT を使用して作成した MATLAB の構造体が2つあります。それらを連結できるのかどうか教えてください。

채택된 답변

MathWorks Support Team
MathWorks Support Team 2012년 9월 19일
同じフィールド名の構造体であれば、[] や HORZCAT あるいは VERTCAT で連結することができます。例えば以下のようになります。
S1 = struct('type', {'big1','little1'}, 'color', {'red1'}, 'x', {3 4})
S2 = struct('type', {'big2','little2'}, 'color', {'red2'}, 'x',{12,13})
% 以下の全ての方法が実行可能です。
[S1 S2]
[S1;S2]
horzcat(S1,S2)
cat(1,S1,S2)
cat(2,S1,S2)
異なる構造の構造体(フィールド名も異なる場合)は MATLAB では連結できません。例えば以下のようなデータがある場合、
S1 = struct('type1', {'big1','little1'}, 'color1', {'red1'}, 'x1', {3 4})
S2 = struct('type2', {'big2','little2'}, 'color2', {'red2'}, 'x2',{12,13})
セル配列を作成することは可能です。
S = {S1, S1}
あるいは、以下の方法で、フィールド名のユニオンの構造体を作成します。共通でないフィールドに関しては [] に設定されます。
S = S1;
F = fieldnames(S2);
for i = length(S)+1:length(S)+length(S2)
for j = 1:length(F)
S(i).(F{j}) = S2.(F{j});
end
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 構造体에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!