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

22 ビュー (過去 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 Center および File Exchange構造体 についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!