This question already has an answer here:
- Collapsing matrix into columns 8 answers
Let's say I have A = [1:8; 11:18; 21:28; 31:38; 41:48]
Now I would like to move everything from column 4 onward to the row position. How do I achieve this?
A =
1 2 3 4 5 6 7 8
11 12 13 14 15 16 17 18
21 22 23 24 25 26 27 28
31 32 33 34 35 36 37 38
41 42 43 44 45 46 47 48
to
A2 =
1 2 3 4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
5 6 7 8
15 16 17 18
35 36 37 38
45 46 47 48
reshape
doesn't seem to do the trick
Here's a vectorized approach with
reshape
andpermute
-Sample run -
Use Matrix indexing!
In a loop...
One more... perhaps unoptimized way would be to decompose the matrix into cells row-wise, transpose the cell array then concatenate everything back together:
The above first uses
mat2cell
to decompose the matrix into non-overlapping cells. Each cell has the same number of rows asA
but the total number of columns is 4 and there are exactlysize(A, 2) / 4
of them. As such, we need to indicate a vector of ones where each element is 4 and there aresize(A, 2) / 4
of these to tell us the number of columns for each cell. This creates a row-wise cell array and so we transpose this cell array and merge all of the cells together into one final matrix withcell2mat
.