Terminate a loop when conditions met and then display other conditions

1 view (last 30 days)
What I am trying to do here is have x displayed when y=0.
I am using a while loop for trajectory of a projectile.
I want to know what x is at the point when y~0. or close enough to zero since the formula will not give exactly zero.
I know all the information is currently in matlab because i can scroll through the y values, find the loop number n, and then find x for that loop number.
What I want to know is how to do this quickly, without having to look through 2000 loops for the point when y is roughly zero
code is as follows:
%PULL LENGTH
L=0.2;
%LAUNCH ANGLE
theta(1)=45;
%INITIAL POSITION OF LAUNCH
x(1)=0;
y(1)=0.6;
%INITIAL VELOCITY
g=9.81;
%MASS OF BALL
mb=0.0116;
%MASS TOTAL
mt=0.08193;
%SPRING CONSTANT
k=42; %N*m IN EACH OF 4 SPRINGS
%PRE-LOAD
p=0.0125;
%INITIAL VELOCITY AND COMPONENTS
v(1)=sqrt((4*k*(L^2-p^2)-2*mt*g*L*sin(theta(1)))/mt);
vx(1)=v(1)*cos(theta(1));
vy(1)=v(1)*sin(theta(1));
%DRAG
d=(0.01588*2);
A=pi()*d^2/4;
rho=1.2;
cd=0.5;
D=1/2*cd*rho*A;
%TRAJECTORY LOOP
del_t=0.002;
while y(n)>0
n=1:2000;
t(n)=n*del_t;
v(n)=sqrt(vx(n)^2+vy(n)^2);
theta(n)=atan(vy(n)/(vx(n)));
Fd(n)=D*v(n)^2;
ax(n)=-Fd(n)*cos(theta(n))/mb;
ay(n)=-Fd(n)*sin(theta(n))/mb-g;
x(n+1)=x(n)+vx(n)*del_t;
y(n+1)=y(n)+vy(n)*del_t;
vx(n+1)=vx(n)+ax(n)*del_t;
vy(n+1)=vy(n)+ay(n)*del_t;
end
plot(x,y);
axis([0,10,-1,10])
Right now the code ignores the while part and just loops 2000 times regardless. I either want it to stop when y=0 or display x when y=0.

Answers (1)

Walter Roberson
Walter Roberson on 28 Nov 2016
while y(n)>0
means the same as
while all(y(n)>0)
You might think you are dealing with a scalar quantity but you have
n=1:2000;
so you are dealing with a vector.
  2 Comments
Nathan Stone
Nathan Stone on 28 Nov 2016
Thank you for your answer. It does not help me, but that is because I have only the most basic understanding of matlab, I suspect if I knew more about matlab your answer would get me where I need to go.
Im learning that Im way out of my depth with matlab, it was really only a side component of a course I am doing and at this time I lack the skills to do what I am trying to do.
thank you!
Walter Roberson
Walter Roberson on 28 Nov 2016
Change the lines
while y(n)>0
n=1:2000;
to
n = 1;
while y(n)>0
and then just after the line
vy(n+1)=vy(n)+ay(n)*del_t;
add the line
n = n + 1;

Sign in to comment.

Categories

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

Products

Community Treasure Hunt

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

Start Hunting!