필터 지우기
필터 지우기

Sorting Rows in a Matrix by Column Containing Largest Value

조회 수: 2 (최근 30일)
Henry Hallock
Henry Hallock 2015년 6월 12일
편집: dpb 2015년 6월 13일
Hello,
I would like to know if there is an easy way to sort rows in a matrix by column position containing the largest value.
For example, if I have a 5 x 5 matrix, A:
A = [12 14 16 18 20; 4 10 6 2 8; 24 22 20 18 16; 8 10 12 6 4; 12 14 16 20 18];
A =
12 14 16 18 20
4 10 6 2 8
24 22 20 18 16
8 10 12 6 4
12 14 16 20 18
I would like to sort the matrix rows in descending order according to which column in each row contains that row's largest value. So, I would like A to become:
A =
24 22 20 18 16
4 10 6 2 8
8 10 12 6 4
12 14 16 20 18
12 14 16 18 20
Because the index of the largest value of row 1 is column 1, the index of the largest value of row 2 is column 2, the index of the largest value of row 3 is column 3, etc.
Thank you!
  댓글 수: 2
Image Analyst
Image Analyst 2015년 6월 13일
I'm confused. You say "the index of the largest value of row 1 is column 1" yet row 1 is [12 14 16 18 20] and the largest value (20) is in column 5, not column 1.
And what do you do if the largest value of all rows is in column 1 for every single row? Then how would you re-order the rows?
dpb
dpb 2015년 6월 13일
편집: dpb 2015년 6월 13일
Same reaction I had initially, IA. But, if there are duplicates, Matlab has default ordering for which order in which max values are returned and also for sort so there's always an answer based on that existing order and the internal logic of the two functions. If that's not good enough, OP then will have to come up with the tiebreaker rules he wants. Or, perhaps he's got a specialized case where there's always a unique answer owing to the manner in which the array is generated.
Oh, and on the confusion noted--he's speaking of the sorted array order, not the initial...the end result is that the max for each row is on the diagonal but the diagonal itself actually isn't sorted as is where I thought he was heading first...

댓글을 달려면 로그인하십시오.

답변 (1개)

dpb
dpb 2015년 6월 13일
편집: dpb 2015년 6월 13일
>> [~,imax]=max(A,[],2);
>> [~,idx]=sort(imax);
>> A(idx,:)
ans =
24 22 20 18 16
4 10 6 2 8
8 10 12 6 4
12 14 16 20 18
12 14 16 18 20
>>
It's too bad there's no syntax to be able to get the second return value for use in the functional form but the intermediary variables are bestest one can do...you can, of course, reuse one for the second; I kept two for clarity purposes here...

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by