필터 지우기
필터 지우기

How to rearrange the rows of a matrix?

조회 수: 143 (최근 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 CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by