help using sortrows please

5 views (last 30 days)
Tom
Tom on 4 Feb 2014
Edited: Wayne King on 4 Feb 2014
Hello,
I can't seem to achieve my desired result of sorting the rows of a matrix into ascending order. The documentation seems to imply that given:
A =
109.8896 102.4908 113.1280 102.8650 114.9918 112.3057
100.3598 110.5698 117.1109 118.4460 105.3406 105.4840
112.6144 106.1511 111.6523 95.3905 117.2843 112.1545
110.3889 114.4477 113.2061 106.8088 101.0697 109.9096
Applying
B = sortrows(A)
would leave the columns in their original positions while placing the row entries into ascending order. However the results I am getting (the numbers are different as the matrix is actually much larger) is like:
95.9296 106.7975 107.7761 107.4120 107.8763 120.1204
97.9841 111.7957 109.5949 112.5619 111.7358 114.5569
98.2657 119.9416 113.8693 104.8464 111.4648 101.0478
98.7183 115.0606 109.6277 99.3238 109.5562 112.9906
98.8091 100.8632 105.0307 109.2623 105.0774 107.9541
As you can see the rows elements do not ascend as I wanted.
Could someone tell me what I am doing wrong?
Kind regards,
Tom
  1 Comment
Azzi Abdelmalek
Azzi Abdelmalek on 4 Feb 2014
To explain your problem, you don't need to post all your data, just post a short example, and show the expected result

Sign in to comment.

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 4 Feb 2014
Maybe you want
a=[2 3 1;4 0 8; 7 3 9]
sort(a,2)

More Answers (1)

Wayne King
Wayne King on 4 Feb 2014
Edited: Wayne King on 4 Feb 2014
Hi Tom,
sortrows(A) sorts the rows of the matrix A based on the entries in column 1.
so:
A = [100.3598 110.5698 117.1109 118.4460 105.3406 105.4840
109.8896 102.4908 113.1280 102.8650 114.9918 112.3057
110.3889 114.4477 113.2061 106.8088 101.0697 109.9096
112.6144 106.1511 111.6523 95.3905 117.2843 112.1545];
sortrows(A)
is equivalent to:
sortrows(A,1)
So you see in your extract above the matrix is sorted by the elements in the first column.
If you want to sort based on other columns you can put those columns in as a positive integer to sort in ascending order, or a negative integer to sort in descending order
sortrows(A,-2)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!