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

3 views (last 30 days)
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.

Accepted Answer

Stephen23
Stephen23 on 18 Mar 2023
Edited: Stephen23 on 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]
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 Comment
David Gillcrist
David Gillcrist on 18 Mar 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!

Sign in to comment.

More Answers (0)

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!