笔记: Matlab中怎样将两个结构体合并为一个结构体?
问题举例: 现有两个结构体变量,s1 = {‘a’, 1, ‘b’, 2},s2 = {‘c’, 3},想要合并为s3 = {‘a’, 1, ‘b’, 2, ‘c’, 3}。
解决办法:(构造自定义函数如下)
function [c] = appendStruct(a,b)
%APPENDSTRUCT Appends two structures ignoring duplicates
% Developed to append two structs while handling cases of non-unique
% fieldnames. The default keeps the last occurance of the duplicates in
% the appended structure.
ab = [struct2cell(a); struct2cell(b)];
abNames = [fieldnames(a); fieldnames(b)];
[~,iab] = unique(abNames,'last');
c = cell2struct(ab(iab),abNames(iab));
end
代码源链接: link