Thursday, 29 May 2014

How to get all the elements of a structure into single array, in Matlab?

 %Structure definition


% Case 1: Each element in the structure has same number of columns but different
% number of rows.

a(1).res = ones(4,2)*100;
a(2).res = ones(2,2)*2;
a(3).res = ones(3,2)*40;
a(4).res = ones(5,2)*253;

% For Case 1, [a.res] = horzcat will not work because it requires rows of
% all the elements in the structure to be equal. However, we can do
% vertical concatenation as columns of all the elements are equal.


vertCatAres = vertcat(a.res)

%Case 2: Each element in the structure has same number of rows but
%different number of columns

a(1).res = ones(2,4)*100;
a(2).res = ones(2,2)*2;
a(3).res = ones(2,3)*40;
a(4).res = ones(2,5)*253;
horzCatAres = [a.res] % horzcat(a.res)

%Results
vertCatAres =
   100   100
   100   100
   100   100
   100   100
     2     2
     2     2
    40    40
    40    40
    40    40
   253   253
   253   253
   253   253
   253   253
   253   253

horzCatAres =
   100   100   100   100     2     2    40    40    40   253   253   253   253   253
   100   100   100   100     2     2    40    40    40   253   253   253   253   253