How to rearrange the rows of a matrix?
105 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Andrew Newell
2014-4-28
The trick is to use the index from sorting the first column:
[~,idx] = sort(A(:,1));
B = A(idx,:);
0 个评论
更多回答(1 个)
Roberto
2014-4-28
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!