필터 지우기
필터 지우기

break out of for loop help

조회 수: 3 (최근 30일)
Sean Smith
Sean Smith 2011년 10월 20일
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
Jan
Jan 2011년 10월 20일
Please post your initial values such that we can run your code.
Sean Smith
Sean Smith 2011년 10월 20일
h=1;
C=0.5;
R=0.0366;
p=1.2;
m=0.145;
g=9.81;
D=C*p*pi*R^2/(2*m);
vo=90*0.44704;
th0=30*(pi/180);
Tmax=vo*sin(th0)/g+sqrt(2*h/g+vo^2*sin(th0)^2/g^2);
T=1/100;
t=0:T:Tmax;
N=floor(Tmax/T);
v(1)=vo;
x(1)=0;
vx(1)=vo*cos(th0);
y(1)=h;
vy(1)=vo*sin(th0);
ax(1)=-D*vx(1)*v(1);
ay(1)=-D*vy(1)*v(1)-g;

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

채택된 답변

Jan
Jan 2011년 10월 21일
The loop does stop. You can check this by a disp statement before the break.
I assume you have written the code into a script and y is defiend from an earlier run. Then a "clear" statement on top would be helpful - not "clear all". Or you could convert it to a function by inserting this as first line:
function myIntegrator
or what ever your file is called.
Note: Using several commands in one line impedes debugging. You cannot set a breakpoint on the break command in:
if y(n+1)==0, break; end
But this would have revealed the problem.
  댓글 수: 1
Sean Smith
Sean Smith 2011년 10월 21일
i didn't mean to hit answer accepted, oops.
how does it fill it with only 1 iteration? shouldn't it do it from 1 to N? what would you suggest to get it to stop when y=0?

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

추가 답변 (1개)

Image Analyst
Image Analyst 2011년 10월 20일
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
Sean Smith
Sean Smith 2011년 10월 20일
still not stopping it for some reason

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

카테고리

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