bring zeros on top of a matrix

2 visualizzazioni (ultimi 30 giorni)
ALESSIO
ALESSIO il 8 Feb 2023
Commentato: Dyuman Joshi il 9 Feb 2023
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

Risposta accettata

Dyuman Joshi
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))'
C = 3×4
0 0 0 4 5 6 3 5 7 3 4 6
%Initial vectorized approach
%B=A';
%C=reshape([B(B==0);B(B~=0)],size(B))';

Più risposte (0)

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!

Translated by