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?
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.
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.
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.
I think the sortrows function is what you're looking for.
>> sortrows(data,1) ans = -1 4 1 3 5 7
An alternative to sortrows()
, which can be applied to broader scenarios.
save the sorting indices of the row/column you want to order by:
[~,idx]=sort(data(:,1));
reorder all the rows/columns according to the previous sorted indices
data=data(idx,:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With