How to sort the rows of an array by the total number of zeros in the row

4 visualizaciones (últimos 30 días)
I have any array where each row is a unique vector index, I want to sort the array so that column by column the numbers increase but also I want to make sure that the number of zeros in any given row does not increase from the previous row. For example, I want this:
V =
1 0 0
2 0 0
3 0 0
0 1 0
1 1 0
2 1 0
0 2 0
1 2 0
0 3 0
0 0 1
1 0 1
2 0 1
0 1 1
1 1 1
0 2 1
0 0 2
1 0 2
0 1 2
0 0 3
To be
V =
1 0 0
2 0 0
3 0 0
0 1 0
0 2 0
0 3 0
0 0 1
0 0 2
0 0 3
1 1 0
2 1 0
1 2 0
1 0 1
2 0 1
1 0 2
0 1 1
0 1 2
0 2 1
1 1 1
The actual order of the nonzero numbers in a section with a constain pattern in zeros column-wise doesn't matter so long as the zeros follow the pattern shown is all that matters. How could I do this, particlarly in a succinct and efficient way, but I'd like it work regardless of the size of the 2D matrix. Additionally, what would be the fastest way to break the array into those sections, i.e.
V1 =
1 0 0
2 0 0
3 0 0
V2 =
0 1 0
0 2 0
0 3 0
V3 =
0 0 1
0 0 2
0 0 3
V12 =
1 1 0
2 1 0
1 2 0
V13 =
1 0 1
2 0 1
1 0 2
V23 =
0 1 1
0 1 2
0 2 1
V123 =
1 1 1
Again something that could do this regardless of the size of the matrix.

Respuesta aceptada

Stephen23
Stephen23 el 18 de Mzo. de 2023
Editada: Stephen23 el 18 de Mzo. de 2023
A = [1,0,0;2,0,0;3,0,0;0,1,0;1,1,0;2,1,0;0,2,0;1,2,0;0,3,0;0,0,1;1,0,1;2,0,1;0,1,1;1,1,1;0,2,1;0,0,2;1,0,2;0,1,2;0,0,3]
A = 19×3
1 0 0 2 0 0 3 0 0 0 1 0 1 1 0 2 1 0 0 2 0 1 2 0 0 3 0 0 0 1
[~,X] = sortrows([-sum(A==0,2),A(:,end:-1:1)]);
B = A(X,:)
B = 19×3
1 0 0 2 0 0 3 0 0 0 1 0 0 2 0 0 3 0 0 0 1 0 0 2 0 0 3 1 1 0
or equivalently:
[~,X] = sortrows([sum(A==0,2),A],[-1,1+size(A,2):-1:1]);
B = A(X,:)
B = 19×3
1 0 0 2 0 0 3 0 0 0 1 0 0 2 0 0 3 0 0 0 1 0 0 2 0 0 3 1 1 0
  1 comentario
David Gillcrist
David Gillcrist el 18 de Mzo. de 2023
I ended up coming to this same answer on my own, I'm glad someone else was able to get to it. Awesome, thank you!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by