How to rearrange the rows of a matrix?

123 ビュー (過去 30 日間)
MRC
MRC 2014 年 4 月 28 日
回答済み: Roberto 2014 年 4 月 28 日
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.

採用された回答

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

その他の回答 (1 件)

Roberto
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
or simply use the matlab command sort

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by