break out of for loop help
Afficher commentaires plus anciens
I have this for loop which works perfectly fine except that I want it to stop the for loop when y=0. The loop is calculating trajectory so I want it to stop when the ball hits the ground (or y=0). I have tried everything I can think of but nothing works. It either doesn't stop the loop or it returns the completely wrong y values. I've tried if y==0, y<=0, y(n)==0, y(n)<=0, y(n+1)==0, y(n+1)<=0, and putting it before and after the calculations. nothing worked Please help.
for n=1:N
ax(n+1) = -D*vx(n)*v(n);
ay(n+1) = -D*vy(n)*v(n)-g;
v(n+1) = sqrt(vx(n)^2+vy(n)^2);
x(n+1) = x(n)+T*vx(n)+0.5*T^2*ax(n);
vx(n+1) = vx(n)+T*ax(n);
y(n+1) = y(n)+T*vy(n)+0.5*T^2*ay(n);
vy(n+1) = vy(n)+T*ay(n);
if y(n+1)==0, break; end
end
2 commentaires
Jan
le 20 Oct 2011
Please post your initial values such that we can run your code.
Sean Smith
le 20 Oct 2011
Réponse acceptée
Plus de réponses (1)
Image Analyst
le 20 Oct 2011
It probably won't hit 0.0000000000000000000 exactly. It might get to 0.000000000000002, so check if it's close:
if abs(y(n+1)) < 0.0001 % Some tolerance.
break;
end
1 commentaire
Sean Smith
le 20 Oct 2011
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!