Use sorted variable to reorder rows of a matrix
조회 수: 3 (최근 30일)
이전 댓글 표시
I am attempting to reorder the rows of a matrix from greatest number of nonzero elements to least. I calculate the number of zeros per row and then sort that variable to get the correct order, but I am having tourble using my sorted variable to reorder the original matrix. I have posted what I have so far below
Index_matrix = [42 33 27 22 17 12 7 4 2 1 0
43 34 26 21 16 11 6 3 1 0 0
44 35 28 22 17 12 7 4 2 1 0
45 36 29 23 18 13 8 2 1 0 0
46 37 30 24 19 14 9 3 1 0 0
47 38 31 25 20 15 10 5 2 1 0
48 39 32 26 21 16 11 6 3 1 0
49 40 33 27 22 17 12 7 4 2 1
50 41 31 25 20 15 10 5 2 1 0];
test = sum(Index_matrix==0, 2);
test2 = sort(test,1);
index_matrix = sort(Index_matrix, test2);
댓글 수: 3
채택된 답변
Akira Agata
2021년 1월 5일
How about the following solution?
test = sum(Index_matrix==0, 2);
[~, order] = sort(test);
Index_matrix = Index_matrix(order,:);
The result is like:
>> Index_matrix
Index_matrix =
49 40 33 27 22 17 12 7 4 2 1
42 33 27 22 17 12 7 4 2 1 0
44 35 28 22 17 12 7 4 2 1 0
47 38 31 25 20 15 10 5 2 1 0
48 39 32 26 21 16 11 6 3 1 0
50 41 31 25 20 15 10 5 2 1 0
43 34 26 21 16 11 6 3 1 0 0
45 36 29 23 18 13 8 2 1 0 0
46 37 30 24 19 14 9 3 1 0 0
댓글 수: 0
추가 답변 (1개)
KSSV
2021년 1월 5일
idx = [42 33 27 22 17 12 7 4 2 1 0
43 34 26 21 16 11 6 3 1 0 0
44 35 28 22 17 12 7 4 2 1 0
45 36 29 23 18 13 8 2 1 0 0
46 37 30 24 19 14 9 3 1 0 0
47 38 31 25 20 15 10 5 2 1 0
48 39 32 26 21 16 11 6 3 1 0
49 40 33 27 22 17 12 7 4 2 1
50 41 31 25 20 15 10 5 2 1 0];
id =sum(idx==0,2) ; % get the sum of zeros
[val,id1] = sort(id,'descend') ;
iwant = idx(id1,:)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Distribution Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!