Merge structures with subfields
显示 更早的评论
Hi guys,
I have multiple structures (around 50, with equal fieldnames). Some fields go up to three levels deep (s.a.b.c). I want to concatenate all the fields. So suppose I have:
s1.time = [240x1 double]
s1.a.b.c = [240x3 double]
s1.a.b.d = [240x3 double]
s2.time = [120x1 double]
s2.a.b.c = [120x3 double]
s2.a.b.d = [120x3 double]
I want to achieve:
s3.time = [360x1double]
s3.a.b.c = [360x3 double]
s3.a.b.d = [360x3 double]
In s3 the time should be increasing while in s1 and s2 the time starts at 0 everytime. I wrote the following which works up till 3 levels but I have the idea this could be done much simpler..
function [ out ] = Concatenate_3rd_level_structs( in , timename)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
fieldsL1 = fieldnames(in); % Level 1 fields
out = in(1);
for i = 2:length(in)
for j = 1:length(fieldsL1)
if strcmp(fieldsL1{j},timename)
out.(timename) = [out.(timename); in(i).(timename)+out.(timename)(end)+out.(timename)(2)]; % For the time vector create an increasing signal
else
if isstruct(in(i).(fieldsL1{j}))
fieldsL2 = fieldnames(in(i).(fieldsL1{j}));
else
fieldsL2 = [];
end
if ~isempty(fieldsL2) % In case of a level 2 nested structure
for jj = 1:length(fieldsL2)
if isstruct(in(i).(fieldsL1{j}).(fieldsL2{jj}))
fieldsL3 = fieldnames(in(i).(fieldsL1{j}).(fieldsL2{jj}));
else
fieldsL3 = [];
end
if ~isempty(fieldsL3)% In case of a level 3 nested structure
for jjj = 1:length(fieldsL3)
out.(fieldsL1{j}).(fieldsL2{jj}).(fieldsL3{jjj}) = ...
[ out.(fieldsL1{j}).(fieldsL2{jj}).(fieldsL3{jjj}); in(i).(fieldsL1{j}).(fieldsL2{jj}).(fieldsL3{jjj})];
end
else
out.(fieldsL1{j}).(fieldsL2{jj}) = [out.(fieldsL1{j}).(fieldsL2{jj}); in(i).(fieldsL1{j}).(fieldsL2{jj})] ;
end
end
else
out.(fieldsL1{j}) = [out.(fieldsL1{j}); in(i).(fieldsL1{j})] ;
end
end
end
end
end
采纳的回答
更多回答(1 个)
Titus Edelhofer
2015-1-12
编辑:Titus Edelhofer
2015-1-12
Hi Jan,
it probably might be too easy (that's why I don't try here ;-)), but my guess is, that with a recursive call you might be better off.
It could be though that you have to carry the time vector down the levels with you, i.e., instead of recursively calling your function with in.(fieldnames{1}), you will create an intermediate structure
inIntermediate = struct(timename, in.(timename), fieldnames{1}, in.(fieldnames{1}));
which then is used to call the function recursively.
Maybe this helps...
Titus
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!