bring zeros on top of a matrix
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
hi, i need to write a function which brings all the zeros that are on a given matrix at the top of it.
for example, if i my matrix is
4 5 0 6
3 0 5 7
0 3 4 6
the output would be:
0 0 0 4
5 6 3 5
7 3 4 6
the answer needs to use loops
1 Commento
Risposta accettata
Dyuman Joshi
il 8 Feb 2023
Modificato: Dyuman Joshi
il 8 Feb 2023
Assuming elements are sorted row-wise
A=[4 5 0 6;3 0 5 7;0 3 4 6];
"the answer needs to use loops"
B=A';
C=B(:)';
for ix = find(C==0)
C(1:ix)=[C(ix) C(1:(ix-1))];
end
C=reshape(C',size(B))'
%Initial vectorized approach
%B=A';
%C=reshape([B(B==0);B(B~=0)],size(B))';
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!