Reorder Matrix Rows from the row with the most nonzero elements to the row with the least nonzero elements

7 vues (au cours des 30 derniers jours)
Vance Blake le 5 Jan 2021
Commenté : Stephen23 le 5 Jan 2021
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 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Stephen23 le 5 Jan 2021

Connectez-vous pour commenter.

Réponses (2)

Cris LaPierre le 5 Jan 2021
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 commentairesAfficher 1 commentaire plus ancienMasquer 1 commentaire plus ancien
Cris LaPierre le 5 Jan 2021
Sorry, I meant logical arrays, not logical indexing.
Vance Blake le 5 Jan 2021
Modifié(e) : Vance Blake le 5 Jan 2021
This isnt a hw assignment, I'm working on independnet research. I know not to ask hw questions on here. But I was trying to do something like this, but I don't know how to reorder the matrix based on the variable test. Also, I'm not trying to change the order of the nonzero elements in each row; wouldn't sorting them do that ?
test = size(A,2) - sum(A==0, 2);

Connectez-vous pour commenter.

Stephen23 le 5 Jan 2021
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,:)
B = 9×11
1 2 4 7 12 17 22 27 33 40 49 0 1 2 4 7 12 17 22 27 33 42 0 1 2 4 7 12 17 22 28 35 44 0 1 2 5 10 15 20 25 31 38 47 0 1 3 6 11 16 21 26 32 39 48 0 1 2 5 10 15 20 25 31 41 50 0 0 1 3 6 11 16 21 26 34 43 0 0 1 2 8 13 18 23 29 36 45 0 0 1 3 9 14 19 24 30 37 46
0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by