# alternate row sorting on changing row value

2 views (last 30 days)
STEPHEN BARRETT on 10 Dec 2019
Commented: STEPHEN BARRETT on 11 Dec 2019
This one seems like a simple task to me but when i start coding it, it stops making sense.
I just want to alternate acending and descending row sort on rows that change value in the first column. For exapmle, I have this array below.
T=
1 1;
1 2;
2 1;
2 2;
2 3;
2 4;
3 1;
3 2
First and second column is already sorted. Off to a good start. But now i want to sort every other set of rows in decending order like this:
T=
1 1;
1 2;
2 4;
2 3;
2 2;
2 1;
3 1;
3 2
The actual array I'm sorting is thousands of rows long so it's not jsut the middle section i need to do this to. Any thoughts?

STEPHEN BARRETT on 10 Dec 2019
Edited: STEPHEN BARRETT on 10 Dec 2019
This was actually fairly straight forward after a good nights sleep...
U = unique(T)
for i = 2 : 2 : length(U)
F = find(T(:,1) == U(i));
T(F(1) : F(end), :) = sortrows(T(F(1) : F(end), :), 'descend');
end

Image Analyst on 11 Dec 2019
It's funny how you got this to work:
T=[...
1 1;
1 2;
2 1;
2 2;
2 3;
2 4;
3 1;
3 2]
U = unique(T)
for i = 2 : 2 : length(U)
F = find(T(:,1) == U(i));
T(F(1) : F(end), :) = sortrows(T(F(1) : F(end), :), 'descend');
end
when everyone else gets this:
T =
1 1
1 2
2 1
2 2
2 3
2 4
3 1
3 2
U =
1
2
3
4
Index exceeds the number of array elements (0).
Error in test5 (line 13)
T(F(1) : F(end), :) = sortrows(T(F(1) : F(end), :), 'descend');
Just copy and paste the code above to verify that.
Big hint on solving it: U should not look at the entire T. It should only examine the first column of T to get the unique groups since the second column could be any arbitrary numbers -- they don't need to be part of the same group as the first column, they could be virtually anything. They just need to be sorted in descending order by group. So the numbers in the second column could be floating point numbers, numbers from minus to plus a million, or whatever - it's totally unrestricted.
STEPHEN BARRETT on 11 Dec 2019
sorry, was a typo converting actual code to message board code
U should be:
U = unique(T(:,1))