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

1 次查看(过去 30 天)
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.

采纳的回答

Stephen23
Stephen23 2023-3-18
编辑:Stephen23 2023-3-18
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by