Search code examples
matlabconcatenationcell-array

Concatenate cells


I have a 6 x 12 cell (called M) like this

[1 1 1 1] [2 2 2 2] ... [12 12 12 12]
[13 13 13 13] [14 14 14 14] ... [24 24 24 24]
...
[61 61 61 61] [62 62 62 62] ... [72 72 72 72]

I would like to vertically concatenate so the matrix would become 1 x 12 cell which should look like this:

[1 1 1 1 13 13 13 13 ... 61 61 61 61] [ 2 2 2 2 14 14 14 14 14 ... 62 62 62 62] ...
...

I've tried vertcat, for instance vertcat(M{1,1}, M{2,1}) but that doesn't seem to work. Could anyone please help?


Solution

  • If all the cells' contents have the same size, as in your example, you can concatenate everything into a matrix and then convert to a cell array:

    result = mat2cell(cell2mat(M.'), ones(1,size(M,2))).';
    

    As an example, for

    M = { [1 1 1 1] [2 2 2 2]
          [13 13 13 13] [14 14 14 14]
          [61 61 61 61] [62 62 62 62] };
    

    this produces

    result{1} =
         1     1     1     1    13    13    13    13    61    61    61    61
    result{2} =
         2     2     2     2    14    14    14    14    62    62    62    62