alternate row sorting on changing row value

2 ビュー (過去 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 Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by