Stacking matrices from a cell array on top of each other (MATLAB)
I have an array of cells, each cell contains a three column matrix.
How can I add all these matrices together so that there are 3 very long columns of data?
I know I could:
stacked_matrix = [cellArray{1,1} ; cellArray{1,2} ; cellArray{1,N}];
but I want not to manually write everything because the cell array is 1x40
+3
source to share
2 answers
You can achieve this by using cat
the first dimension like this:
cat(1,cellArray{:})
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
+3
source to share
You can also use vertcat
:
out = vertcat(cellArray{:});
However, the implementation vertcat
is essentially a syntactic sugar for cat(1,cellArray{:})
at Matt? Answer .
To check:
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
+2
source to share