Lepidopterist
Lepidopterist

Reputation: 411

Sorting the columns of a matrix by "largest element" in matlab

In matlab, how can I sort a matrices columns in ascending order by the largest element in a given column.

For example, given a matrix A=[1 300 5; 100 1 2; 2 200 7], I would like to output A=[300 1 5; 1 100 2; 200 2 7].

I can do this using a for loop, but I've been hammered with the idea that I should always look for a matrix operation to do anything in matlab.

Upvotes: 1

Views: 162

Answers (1)

Marc Claesen
Marc Claesen

Reputation: 17026

Find maxima per column in A and sort them. We need the indices of the sort (I).

>> [sortedmaxs,I]=sort(max(A,[],1),'descend')

sortedmaxs =

   300   100     7


I =

     2     1     3

Sort A based on the indices I:

>> Asort=A(:,I)

Asort =

   300     1     5
     1   100     2
   200     2     7

So in short, you simply need these two lines:

[~,I]=sort(max(A,[],1),'descend');
Asort=A(:,I);

Upvotes: 2

Related Questions