How to sort the rows of an array by the total number of zeros in the row
5 ビュー (過去 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.
0 件のコメント
採用された回答
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]
[~,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,:)
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Shifting and Sorting Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!