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

24 views (last 30 days)
MathWorks Support Team
MathWorks Support Team on 19 Sep 2012
STRUCT を使用して作成した MATLAB の構造体が2つあります。それらを連結できるのかどうか教えてください。

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 19 Sep 2012
同じフィールド名の構造体であれば、[] や 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

More Answers (0)

Categories

Find more on 構造体 in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!