Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting entire matrix according to one column in matlab

I have the matrix as follows

a =

 1     3
 2     5
 3     2
 4     8
 5     9

I want to sort the second column in the a matrix. I want the corresponding rows of column one to be printed as follows :

a =

 3     2
 1     3
 2     5
 4     8
 5     9

I tried sort(a), but it is sorting only the second column of matrix a.

like image 968
Mrk Avatar asked Feb 25 '13 09:02

Mrk


People also ask

How do you sort a column of a matrix in Matlab?

B = sort( A ) sorts the elements of A in ascending order. If A is a vector, then sort(A) sorts the vector elements. If A is a matrix, then sort(A) treats the columns of A as vectors and sorts each column.

How do you sort a whole matrix?

Approach: Create a temp[] array of size n^2. Starting with the first row one by one copy the elements of the given matrix into temp[]. Sort temp[]. Now one by one copy the elements of temp[] back to the given matrix.

How do you sort a column by a matrix?

On the "Modeling" tab of the Data view, click the "Sort by Column" button and choose [Sort Order]. Go back to the Report view and add your matrix, adding row, column, and value fields. If the columns are sorted in the order you wanted, you win!

How do I select all elements in a column in Matlab?

To access elements in a range of rows or columns, use the colon . For example, access the elements in the first through third row and the second through fourth column of A . An alternative way to compute r is to use the keyword end to specify the second column through the last column.


2 Answers

Try this:

sortrows(a,2)

This should sort according to the second column.

like image 87
ThijsW Avatar answered Oct 20 '22 12:10

ThijsW


or use:

[val idx]=sort(a(:,2));
ans = [a(idx,1) val]
like image 39
bla Avatar answered Oct 20 '22 11:10

bla