I need to get out of a nested loop when a particular condition is satisfied. I tried to insert the "break", "return" and "continue" commands but it does not seem to make the necessary effect.

15 views (last 30 days)
for i = 1 : n % iterating over all the 'n' particles
for z=1:2000
if (p(i,2)<A && wave(z,2)==20)
sticking_coeff=0.7
rdm_nbr1=rand(1)
if rdm_nbr1>sticking_coeff
v(i,2)=-v(i,2);
v(i,1)=-v(i,1);
else
v(i,1)=0;
v(i,2)=0;
end
elseif (p(i,2)<A && wave(z,2)==0)
p(i,1)
v(i,1)=v(i,1);
v(i,2)=v(i,2);
if (p(i,1)<wave(z,1))
sticking_coeff=0.7 ;
rdm_nbr=rand(1);
if rdm_nbr>sticking_coeff
v(i,2)=-v(i,2);
v(i,1)=-v(i,1);
else
v(i,1)=0;
v(i,2)=0;
end
end
else
v(i,2)=v(i,2);
v(i,1)=v(i,1);
end
end
end
Now, what I would want to happen, is that whenever the condition for i='n' is satisfied, then the inner loops should stop and the control should come back to the first 'for' loop, but is currently happening is that the second 'for' loop is executing for 2000 times before it comes out of the loop. Kindly help.

Accepted Answer

Image Analyst
Image Analyst on 22 Dec 2013
Why not just have your outer for loop go from 1 to (n-1) then, instead of to n? If you went all the way to n, you can't start that loop all over again with i = 1 - you'd have to use a while loop for that kind of logic but then you'd need some logic to prevent it from being an infinite loop. When would it ever stop if it just keeps restarting whenever i hit n?
  2 Comments
Hari
Hari on 23 Dec 2013
Edited: Hari on 23 Dec 2013
Hi
Thanks for the answer. But the issue is not in 'i' because the code would just check the values of p(i,1),v(i,1),p(i,2),v(i,2) with the conditions and do what is required. if there are 5 particles, then the iteration would go from 1st particle to the 5th. I forgot to include a parent 'for' loop which controls the number of iterations. So basically, it would look like:
For n=1:N % N is the number of iterations ( suppose 1500)
For i=1:n % number of particles (suppose 5)
For z=1:1000
{
if
elseif
else
end
}
end
end
end
So the question is how to come out of the 'for z=1:1000' loop whenever any one condition of the if.elseif.else conditions is satisfied into the 'for i=1:n' loop.
Thanks in advance for the answer.
Image Analyst
Image Analyst on 23 Dec 2013
Use break to leave the z loop and continue with the i loop. Use continue to skip the rest of the z loop and start with the next z value.
if (some condition)
break; % out of z loop and continue with the i loop.
end
If you need to break out of two loops , then you will need to set a flag or else check if the inner loop is not greater than or equal to the last value. For example, after the z loop
if z < 1000
break; % break out of "i" loop also.
end

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!