alternate row sorting on changing row value
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
STEPHEN BARRETT
el 10 de Dic. de 2019
Comentada: STEPHEN BARRETT
el 11 de Dic. de 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?
0 comentarios
Respuesta aceptada
STEPHEN BARRETT
el 10 de Dic. de 2019
Editada: STEPHEN BARRETT
el 10 de Dic. de 2019
2 comentarios
Image Analyst
el 11 de Dic. de 2019
Editada: Image Analyst
el 11 de Dic. de 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.
Más respuestas (1)
Image Analyst
el 10 de Dic. de 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.
0 comentarios
Ver también
Categorías
Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!