Hikul
Hikul

Reputation: 59

Stacking matrices from a cell array on top of one another (MATLAB)

I have a cell array, with each cell containing a 3 column matrix.

How can I stack all of these matrices together, so that there are 3 very long columns of data?

I know I could do:

stacked_matrix = [cellArray{1,1} ; cellArray{1,2} ; cellArray{1,N}];

but I want to avoid manually writing everything out because the cell array is 1x40

Upvotes: 3

Views: 263

Answers (2)

rayryeng
rayryeng

Reputation: 104545

You can also use vertcat as well:

out = vertcat(cellArray{:});

However, doing vertcat is essentially syntactic sugar for cat(1,cellArray{:}) as per Matt's answer.

To test:

cellArray{1} = [ 1  2  3];
cellArray{2} = [ 4  5  6];
cellArray{3} = [ 7  8  9];
cellArray{4} = [10 11 12];
out = vertcat(cellArray{:});

... and we get:

out =

     1     2     3
     4     5     6
     7     8     9
    10    11    12

Upvotes: 2

Matt
Matt

Reputation: 13953

You can achieve this using cat along the first dimension like this:

cat(1,cellArray{:})

Let's test it:

>> cellArray{1} = [ 1  2  3];
>> cellArray{2} = [ 4  5  6];
>> cellArray{3} = [ 7  8  9];
>> cellArray{4} = [10 11 12];

>> stacked_matrix = cat(1,cellArray{:})

stacked_matrix =
     1     2     3
     4     5     6
     7     8     9
    10    11    12

Upvotes: 3

Related Questions