Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a 2-D array in MATLAB with respect to one column?

I would like to sort a matrix according to a particular column. There is a sort function, but it sorts all columns independently.

For example, if my matrix data is:

 1     3  5     7 -1     4 

Then the desired output (sorting by the first column) would be:

-1     4  1     3  5     7 

But the output of sort(data) is:

-1     3  1     4  5     7 

How can I sort this matrix by the first column?

like image 343
Midhat Avatar asked Sep 25 '08 17:09

Midhat


People also ask

How do you sort a 2D array based on one column in MATLAB?

B = sortrows( A , column ) sorts A based on the columns specified in the vector column . For example, sortrows(A,4) sorts the rows of A in ascending order based on the elements in the fourth column.

How do I sort an array of columns 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 2D array?

Make the 2D array into a separate simple (1D) array (STEP 1). Then use the Arrays. sort() method to sort the simple array (STEP 2). Then set each space of the 2D array to be the number of columns across (X-coordinate where the space will be changed) multiplied by the number of spaces per row in the 2D array.


2 Answers

I think the sortrows function is what you're looking for.

>> sortrows(data,1)  ans =      -1     4      1     3      5     7 
like image 92
Kena Avatar answered Sep 24 '22 14:09

Kena


An alternative to sortrows(), which can be applied to broader scenarios.

  1. save the sorting indices of the row/column you want to order by:

    [~,idx]=sort(data(:,1)); 
  2. reorder all the rows/columns according to the previous sorted indices

    data=data(idx,:) 
like image 44
AlessioX Avatar answered Sep 22 '22 14:09

AlessioX