Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

structures in matlab

%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?

like image 576
Emma Avatar asked Mar 28 '26 17:03

Emma


1 Answers

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
like image 110
Andrey Rubshtein Avatar answered Mar 31 '26 09:03

Andrey Rubshtein