%example
clear all
a1 = struct('data1',rand(12,2),'data2',rand(12,2),'data3',rand(12,3));
a2 = struct('data1',rand(12,2),'data2',rand(12,2),'data3',rand(12,3));
a3 = struct('data1',rand(12,2),'data2',rand(12,2),'data3',rand(12,3));
a4 = struct('data1',rand(12,2),'data2',rand(12,2),'data3',rand(12,3));
Pretend that the structures represent a time series where a1 represents the first 5 day (for example), a2 represents day 5-10 and so on... I'm trying to combine every fieldname in the structures so that I have one continuous series (instead of having them split into different structures. For example...
data1 = [a1.data1;a2.data1;a3.data1;a4.data1];
and then do the same for data2 and data3
What would be the best way to do this?
The best way is to define the structures as array of structures beforehand:
a(1) = struct('data1',rand(12,2),'data2',rand(12,2),'data3',rand(12,3));
a(2) = struct('data1',rand(12,2),'data2',rand(12,2),'data3',rand(12,3));
a(3) = struct('data1',rand(12,2),'data2',rand(12,2),'data3',rand(12,3));
a(4) = struct('data1',rand(12,2),'data2',rand(12,2),'data3',rand(12,3));
Which allows you to get the data quite easily:
cat(1,a.data1)
But if you insist on using N structs, then try this:
function so3
a1 = struct('data1',rand(12,2),'data2',rand(12,2),'data3',rand(12,3));
a2 = struct('data1',rand(12,2),'data2',rand(12,2),'data3',rand(12,3));
a3 = struct('data1',rand(12,2),'data2',rand(12,2),'data3',rand(12,3));
a4 = struct('data1',rand(12,2),'data2',rand(12,2),'data3',rand(12,3));
s{1} = struct2cell(a1);
s{2} = struct2cell(a2);
s{3} = struct2cell(a3);
s{4} = struct2cell(a4);
N = numel(fieldnames(a1));
data = cell([1 N]);
for i=1:N
data{i} = cell2mat(cellfun(@(x){x{i}'},s));
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With