Search code examples
arraysmatlabcellconcatenation

Concatenate arrays from rows in a cell of varible size to single column vector in Matlab


I am sorry for what could be a silly question. I have a cell array containing several row vectors (I do not know how many, this can vary) and I want to concatenate them in a single column array. For instance:

A = {[1 2 3]; [4 6 5 4 3 2 21 1]; [3 2 1 1 5 6 78 4]; [3 4]}

And I want to obtain B like:

B = [1;2;3;4;6;5;4;3;2;21;1;3;2;1;1;5;6;78;4;3;4]

I tried to do it in a for loop because I do not know how many arrays are contained in A, they are 4 in this example but their number can vary, so I wrote something like:

for i= 1:length(A)
    B= [vertcat(cell2mat(A(i)))'];
end

But this writes in a column only the results of the last array of A. How do I solve this?


Solution

  • If you transpose A, you can use cell2mat on the entire cell, which results in a row vector. Another transpose gives you the desired result.

    B = cell2mat(A.').';