# Sort an Array with sortrows ( ) with two columns

77 views (last 30 days)
Patrick Benz on 19 Feb 2021
Edited: Stephen Cobeldick on 5 Mar 2021
Hey guys,
I'm sorting an 82x4 arraywith sortrows. I want it to be sorted in a descending way. First the second column shall be significant and for tiebreakers the third column.
My code is:
Knotenpaare=sortrows(Auswertung,[2 3],'descend')
where Auswertung is the array. The first 40 rows of the array are sorted beautifully. But at the moment the values in the second column switch from positive to negative the sorting changes.
Why are the values in the third column now ascending?
Is there a better way to sort these kinds of arrays ?
dpb on 24 Feb 2021
"Is there an option to cut the number after 5 digits off? and not only visual."
node_Num=sign(node_Num).*floor(abs(node_Num)*1E5)/1E5;

Stephen Cobeldick on 24 Feb 2021
There are probably nicer ways to do this, as this unfortunately changes the data itself. If required, you could use the index output from sortrows to sort the original data matrix.
format long g
A = S.Auswertung
A = 82×4
24 -20.8047 19.15862 0 26 20.8047 19.15862 0 953 19.76845 19.04576 0 954 18.73158 18.93867 0 955 17.69413 18.83735 0 956 16.65614 18.74179 0 957 15.61763 18.65202 0 958 14.57864 18.56802 0 959 13.53919 18.48981 0 960 12.49933 18.41738 0
for k = 1:size(A,2)
[U,X,Y] = uniquetol(A(:,k),1e-3);
A(:,k) = U(Y);
end
A
A = 82×4
24 -20.8047 19.15862 0 24 20.8047 19.15862 0 953 19.76844 19.04576 0 953 18.73156 18.93867 0 953 17.69411 18.83735 0 953 16.65611 18.74179 0 953 15.61759 18.65202 0 953 14.57859 18.56802 0 953 13.53915 18.48981 0 953 12.49928 18.40115 0
B = sortrows(A,[-2,-3])
B = 82×4
24 20.8047 19.15862 0 145416 20.8047 18.90707 0 953 19.76844 19.04576 0 145016 19.76844 18.79436 0 953 18.73156 18.93867 0 144616 18.73156 18.68741 0 953 17.69411 18.83735 0 144216 17.69411 18.56802 0 953 16.65611 18.74179 0 143816 16.65611 18.48981 0
B(38:48,:)
ans = 11×4
138216 2.08471 17.75 0 953 1.04237 17.9845 0 137816 1.04237 17.75 0 953 0 17.9845 0 137416 0 17.75 0 953 -1.04238 17.9845 0 137016 -1.04238 17.75 0 953 -2.08473 18.0116 0 136616 -2.08473 17.75 0 953 -3.12701 18.0116 0
Stephen Cobeldick on 5 Mar 2021
Perhaps:
Sortierung(:,1) = Auswertung(index,1)

the cyclist on 19 Feb 2021
See my answer (and other comments) to this very similar question. (As with the comments above, the premise is that the displayed value is not sufficient to see a tiny difference between the numbers.)