How to sort the rows of an array by the total number of zeros in the row
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
David Gillcrist
il 18 Mar 2023
Commentato: David Gillcrist
il 18 Mar 2023
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.
0 Commenti
Risposta accettata
Stephen23
il 18 Mar 2023
Modificato: Stephen23
il 18 Mar 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]
[~,X] = sortrows([-sum(A==0,2),A(:,end:-1:1)]);
B = A(X,:)
or equivalently:
[~,X] = sortrows([sum(A==0,2),A],[-1,1+size(A,2):-1:1]);
B = A(X,:)
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!