How to rearrange the rows of a matrix?

106 views (last 30 days)
MRC
MRC on 28 Apr 2014
Answered: Roberto on 28 Apr 2014
Hi, I want to reshape a matrix A of dimension rxc in a matrix B of the same dimension but with rows rearranged following the index in the first column
E.g.
A=[ 1 1 4 7 10; 2 2 5 8 11; 3 3 6 9 12; 4 13 16 19 22; 5 14 17 20 23; 6 15 18 21 24; 1 25 26 27 28; 2 29 30 31 32; 3 33 34 35 36; 4 37 38 39 40; 5 41 42 43 44; 1 46 47 48 49; 2 50 51 52 53; 5 54 55 56 57; 6 58 59 60 61]
I want
B=[1 1 4 7 10; 1 25 26 27 28; 1 46 47 48 49; 2 2 5 8 11;2 29 30 31 32;2 50 51 52 53; 3 3 6 9 12; 3 33 34 35 36; 4 13 16 19 22; 4 37 38 39 40; 5 14 17 20 23; 5 41 42 43 44; 5 54 55 56 57; 6 15 18 21 24; 6 58 59 60 61]
The features of A on which I can rely are:
-the max of the first column is m=6;
-the elements in the first column of A are increasing until m and then they restart;
-each element of the first column of A can appear for at most n=3 times.
I prefer not to use loops.

Accepted Answer

Andrew Newell
Andrew Newell on 28 Apr 2014
The trick is to use the index from sorting the first column:
[~,idx] = sort(A(:,1));
B = A(idx,:);

More Answers (1)

Roberto
Roberto on 28 Apr 2014
try accessing the matrices subscripts, for example:
% have this matrix
a =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
% change the order of rows:
a([3 2 4 1],:)
ans =
9 7 6 12
5 11 10 8
4 14 15 1
16 2 3 13
or simply use the matlab command sort

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!