Search code examples
matlabmatrixvectorconcatenationcell-array

How to concatenate one element with other across rows in a cell array?


i had a cell array C of dimension 64x8 in which each row is comprised of the following dimension,

Say,

10x26 double    10x26 double    10x26 double    10x26 double    10x26 double    10x26 double    10x26 double    10x26 double

i used the following command to convert each element of the cell array to a matrix,

D = cellfun(@(x) {x(:)}, C);

which gave me the following output,

260x1 double    260x1 double    260x1 double    260x1 double    260x1 double    260x1 double    260x1 double    260x1 double

Now, i need to horizontally concatenate each 260x1 element across the 8 rows of the cell array, so i would get a

2080x1 dimension-ed value in a single cell

where 2080 is the product of 260x8 (along 8 rows). and this should transform the 64x8 Cell array to 64x1 array.

So i must get the output like the below,

2080x1
2080x1
......
......
......
2080x1

I hope cellfun cannot be used since it applies the functions to each element of the cell array. but i need to concatenate the elements of cell array itself, also let me know if there is a way to do it without loops.


Solution

  • The trick here is to use vertcat:

    array = vertcat(cellArray{:});
    

    The {:} part returns the contents of all cells as a list of outputs, and vertcat takes these as inputs and concatenates them along the first dimension. If you wanted to concatenate along the second dimension you can use horzcat, and if you wanted to concatenate along some other dimension you can use the general cat.

    horzcat(A, B, ...) and vertcat(A, B, ...) are the functional forms of the syntax [A, B, ...] and [A; B; ...], respectively.

    Note you could also have used these functions on your original C without using cellfun as you did. Experiment with these methods to better understand their functionality.