Reorder Matrix Rows from the row with the most nonzero elements to the row with the least nonzero elements
이전 댓글 표시
I have a matrix with rows of values. I want to order the rows of the matrix so that the matrix with the most nonzero elements is the first row and the next most nonzero elements is the second row, and so on until the end. If two or rows are the same length it doesnt matter which one comes first. Here is the matrix, thanks in advance.
A = [0 1 2 4 7 12 17 22 27 33 42
0 0 1 3 6 11 16 21 26 34 43
0 1 2 4 7 12 17 22 28 35 44
0 0 1 2 8 13 18 23 29 36 45
0 0 1 3 9 14 19 24 30 37 46
0 1 2 5 10 15 20 25 31 38 47
0 1 3 6 11 16 21 26 32 39 48
1 2 4 7 12 17 22 27 33 40 49
0 1 2 5 10 15 20 25 31 41 50];
댓글 수: 1
Stephen23
2021년 1월 5일
Curious. Apparently not homework, but the same question was asked by multiple OPs at the same time:
Backup just in case:
답변 (2개)
Cris LaPierre
2021년 1월 5일
0 개 추천
I'm not aware of anyway to do this without having to write some code, which is probably the exact reason you were given the assignment. Look into logical indexing and sortrows.
댓글 수: 3
Walter Roberson
2021년 1월 5일
sortrows and logical indexing are not needed. There is a one-line solution based upon totaling the number of zeros in each row and sorting. Ascending number of zeros is descending number of non-zeros.
Cris LaPierre
2021년 1월 5일
Sorry, I meant logical arrays, not logical indexing.
Vance Blake
2021년 1월 5일
편집: Vance Blake
2021년 1월 5일
A = [...
0 1 2 4 7 12 17 22 27 33 42
0 0 1 3 6 11 16 21 26 34 43
0 1 2 4 7 12 17 22 28 35 44
0 0 1 2 8 13 18 23 29 36 45
0 0 1 3 9 14 19 24 30 37 46
0 1 2 5 10 15 20 25 31 38 47
0 1 3 6 11 16 21 26 32 39 48
1 2 4 7 12 17 22 27 33 40 49
0 1 2 5 10 15 20 25 31 41 50];
[~,X] = sort(sum(A==0,2));
B = A(X,:)
카테고리
도움말 센터 및 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!