alternate row sorting on changing row value

조회 수: 7 (최근 30일)
STEPHEN BARRETT
STEPHEN BARRETT 2019년 12월 10일
댓글: STEPHEN BARRETT 2019년 12월 11일
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
STEPHEN BARRETT 2019년 12월 10일
편집: STEPHEN BARRETT 2019년 12월 10일
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
  댓글 수: 2
Image Analyst
Image Analyst 2019년 12월 11일
편집: Image Analyst 2019년 12월 11일
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
STEPHEN BARRETT 2019년 12월 11일
sorry, was a typo converting actual code to message board code
U should be:
U = unique(T(:,1))

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2019년 12월 10일
Sounds a lot like homework. So look at functions like sort(), flipup(), findgroups(), mod(), rem(), etc. and look at indexing, like 1:2:end, or 2:2:end, or even end:-1:1. Those should be enough hints.

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by