user7341333
user7341333

Reputation: 41

while with all zero array in condition

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].

Upvotes: 1

Views: 71

Answers (2)

user6120479
user6120479

Reputation:

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

Upvotes: 0

gnovice
gnovice

Reputation: 125854

You just need to use the any function:

while any(a)
  %...operations...
end

Upvotes: 2

Related Questions