Search code examples
matlabcell-array

Concatenate certain elements from a cell array into a numeric array - MATLAB


I have a nested cell array A, for example A is 1 x 6 cell.

Each cell of A contains another array of cells (for ex. A{1} = 1 x n cell).

Each cell of A{1}{1} contains other cell arrays A{1}{1} = 1 x n cell

I would like to list the content of the cell in a unique array.

A = cell(1,2);
A{1} = cell(1,2);
A{2} = cell(1,1);
A{1}{1} = [{1} {2}];
A{1}{2} = [{3} {4}];
A{2}{1} = [{5} {6}];

vec = [];
for i = 1 : size(A,2)

 for j = 1 : size(A{1,i},2)
    vec = [vec; cell2mat(A{1,i}{1,j}(:,2))];
 end

end

vec = [2;4;6]

Is there a way to avoid the for loop?

Thanks


Solution

  • See is this works for you -

    A_horzcat = horzcat(A{:})
    out = cell2mat(vertcat(A_horzcat{:}))
    vec = out(:,2)
    

    Another approach (a one-liner! and I like it better) -

    vec = arrayfun(@(x) x{1}{2}, [A{:}]).'