1

I have an array a=[1 2 3 4 5 6 7 8 9];. I want to execute a while loop which performs some actions on the array a until all the elements in the array a are zero. How should I do it?

For example:

a=[1 2 3 4 5 6 7 8 9];

while(a contains all zero elements)
    do some operations on a  
end 

At the end of the while loop the a should be a=[0 0 0 0 0 0 0 0 0].

TroyHaskin
  • 8,361
  • 3
  • 22
  • 22

2 Answers2

2

You just need to use the any function:

while any(a)
  %...operations...
end
gnovice
  • 125,304
  • 15
  • 256
  • 359
  • I have tried using any but it goes into infinite loop – user7341333 Dec 26 '16 at 07:15
  • 2
    @user7341333: Then that means something in `a` is still non-zero. Are you dealing with floating-point values? If so, you may end up with values in `a` that are extremely close to zero, but not *exactly* zero. Take a look at this question: [Why is 24.0000 not equal to 24.0000 in MATLAB?](http://stackoverflow.com/q/686439/52738) – gnovice Dec 26 '16 at 07:22
  • 1
    @user7341333 If you're getting an infinite loop, your operation is not setting all of the elements to zero. I would suggest stepping through this operation with the debugger (keeping in mind gnovice's warning about floating-point). – beaker Dec 26 '16 at 15:22
0

In this case, you can mimic a 'for' loop by 'while':

i = length(a);
j = 1;
while j<=i
   a(1,j) = 0;
   j = j + 1;
end

or simply, you can do this as gnovice suggests:

j= 1;
while any(a)
  a(j)=0;
  j = j+1;
end
Community
  • 1
  • 1