MATLAB: How to remove zeros from an array without using nonzeros command

nonzeros

i want to delete the zeros without using nonzeros
x=[1 2 2 0 3 1 3 0 0];
i=1;
j=1;
while i <= length(x)
if x(i)==0
x(i) =[] ;
else
x(i)=x(i);
end
while j <= length(x)
if x(j)==0
x(j) =[] ;
else
x(j)=x(j);
end
j=j+1;
i=i+1;
end
end
x

Best Answer

If you insist on a loop: loop backwards through your array to account for removed elements.
x=[1 2 2 0 3 1 3 0 0];
for n=numel(x):-1:1
if x(n)==0,x(n)=[];end
end
But course it is much better to do an array operation:
x(x==0)=[];