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

30 views (last 30 days)
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!
  1 Comment
Kyle Brozek
Kyle Brozek on 9 Jun 2020
I figured it out but if anyone has a more elegant solution feel free to let me know:
A = [1,2,3;4,5,6;7,8,9;10,11,12]
B = reshape(A', 4, 3)'

Sign in to comment.

Accepted Answer

Cris LaPierre
Cris LaPierre on 9 Jun 2020
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)'

More Answers (1)

madhan ravi
madhan ravi on 9 Jun 2020
Edited: madhan ravi on 9 Jun 2020
The one you have is good. One remark please use .'

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!