How to reshape a n x m matrix into n*m,1 matrix?
3 views (last 30 days)
Show older comments
Danial Ahmed
on 6 Nov 2018
Commented: Walter Roberson
on 6 Nov 2018
For example I have a matrix B with n=3,m=7
B =[ 0 0 0 0 0 0 -100;
0 0 0 0 0 0 -100;
0 0 0 0 0 0 -100;]
I want to reshape it to n*m,1 (21,1)
B = [0; 0; 0; 0; 0; 0; -100; 0; 0; 0; 0; 0; 0; -100; 0; 0; 0; 0; 0; 0; -100;];
I tried using reshape(B,21,1) or reshape(B,[],1) or reshape(B,[21,1]) but it converts it into
B = [0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; -100; -100; -100;];
0 Comments
Accepted Answer
Walter Roberson
on 6 Nov 2018
reshape(B.',[],1)
3 Comments
Walter Roberson
on 6 Nov 2018
The reshape() operation does not change linear indexing at all: something that was (say) the 17th element in the original matrix will always be the 17th element in the reshaped matrix. For ordinary datatypes, reshape() keeps the exact same pointer to the data and just puts a new header on it giving the new shape.
Linear indexing is defined as following the in-memory order: B(1) is always the first in-memory element of B, B(2) is always the second in-memory element, and so on.
Now the bit you need to know is that the in-memory order goes down columns most quickly. B(1,1) is followed by B(2,1) is followed by B(3,1) is followed by B(1,2) is followed by B(2,2) and so on. That is why when you did the plain reshape, all of the -100 ended up at the end, because they are stored last in the array.
The order that you wanted corresponds to following row by row instead of column by column. And the way to get row elements to be consecutive in memory is to transpose the data.
So you do B.' to temporarily get
[ 0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
-100 -100 -100 ]
and now that the in-memory order is 6 0's then -100, repeated three times, you can reshape() that to get the array you wanted.
More Answers (0)
See Also
Categories
Find more on Matrices and Arrays 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!