Effacer les filtres
Effacer les filtres

Sorting Rows in a Matrix by Column Containing Largest Value

2 vues (au cours des 30 derniers jours)
Henry Hallock
Henry Hallock le 12 Juin 2015
Modifié(e) : dpb le 13 Juin 2015
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 commentaires
Image Analyst
Image Analyst le 13 Juin 2015
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 le 13 Juin 2015
Modifié(e) : dpb le 13 Juin 2015
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...

Connectez-vous pour commenter.

Réponses (1)

dpb
dpb le 13 Juin 2015
Modifié(e) : dpb le 13 Juin 2015
>> [~,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...

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by