How to remove zeros from an array without using nonzeros command

조회 수: 1 (최근 30일)
Dimitrios Adam
Dimitrios Adam 2019년 9월 2일
댓글: Dimitrios Adam 2019년 9월 2일
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
  댓글 수: 2
Rik
Rik 2019년 9월 2일
The code you show is not formatted correctly and it doesn't show an array, x is only a scalar. Are you sure this is what you mean?
Dimitrios Adam
Dimitrios Adam 2019년 9월 2일
편집: Dimitrios Adam 2019년 9월 2일
sorry i forgot the space.For some reason it only deletes 1 zero if the are two one next to each other

댓글을 달려면 로그인하십시오.

채택된 답변

Rik
Rik 2019년 9월 2일
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)=[];

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by