alternate row sorting on changing row value

4 vues (au cours des 30 derniers jours)
STEPHEN BARRETT
STEPHEN BARRETT le 10 Déc 2019
Commenté : STEPHEN BARRETT le 11 Déc 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?

Réponse acceptée

STEPHEN BARRETT
STEPHEN BARRETT le 10 Déc 2019
Modifié(e) : STEPHEN BARRETT le 10 Déc 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
  2 commentaires
Image Analyst
Image Analyst le 11 Déc 2019
Modifié(e) : Image Analyst le 11 Déc 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
STEPHEN BARRETT le 11 Déc 2019
sorry, was a typo converting actual code to message board code
U should be:
U = unique(T(:,1))

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 10 Déc 2019
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.

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by