MATLAB: Use reshape or transpose to change the order of a matrix while preserving the row order

column-orderreshapetranspose

Hello,
I'd like to turn matrix A into matrix B.
A =
1 2 3
4 5 6
7 8 9
10 11 12
B =
1 2 3 4
5 6 7 8
9 10 11 12
Unfortunately, I can't seem to get reshape() to work as it preserves the column order instead of the row order.
Maybe there's some combination of reshape + transpose that I haven't tried yet. Any suggestions would be appreciated.
Thank You!

Best Answer

MATLAB uses column major order. You can read more about that here. An array is stored in memory as a continuous list of numbers. Systems that use column major order stores the columns of data, head to tail. The manipulation you want to do assumes the data is stored in row major order instead.
The simplest way to transform data between the two systems is to transpose it. That means transpose A, reshape it, and transpose it back. That can be done easily enough with the following code.
B = reshape(A',4,3)'