Running like a forever loop

4 views (last 30 days)
Karlie Brillant
Karlie Brillant on 27 Mar 2019
Commented: Steven Lord on 27 Mar 2019
I am working on the following function
function [x,y]=projectile(V_int,theta,dt)
time=dt; %(seconds)
k=0.32; %drag coefficient (given)
g=-9.81; %(m/s^2)
%First time step in x direction
x(1)=0; %initial x position
v_int_x=V_int*cos(theta); %initial velocity in x direction
a_x=v_int_x*k; %initial acceleration in x direction
x(2)=x(1)+v_int_x*time+0.5*a_x*(time^2); %second position in x direction
v_fin_x=v_int_x+a_x*time;
%First time step in y direction
y(1)=0;
v_int_y=V_int*sin(theta);
a_y=g-v_int_y*k;
y(2)=y(1)+v_int_y*time+0.5*a_x*(time^2);
v_fin_y=v_int_y+a_y*time;
time=time+dt;
i=3; %counter
while y(i-1)>=0
%calculates x values
a_x=-v_fin_x*k;
x(i)=x(i-1)+v_fin_x*time+0.5*a_x*(time^2);
v_fin_x=v_fin_x+a_x*time;
%calculates y values
a_y=v_fin_y*k;
y(i)=y(i-1)+v_fin_y*time+0.5*a_y*(time^2);
v_fin_y=v_fin_y+a_y*time;
%change counter and timestep to continue loop
i=i+1;
time=time+dt;
end
plot(x,y)
title('Path of Projectile');
xlabel('Distance of Projectile (meters)');
ylabel('Height of Projectile (meters)');
axis([0 max(x)+50 0 max(y)+50]); %axes for plot
x_distance=max(x);
end
I am trying to run it using this script
for theta=0:pi %degrees
V_int=sum('karlie');
dt=0.5; %second(s)
[x,y]=projectile(V_int,theta,dt);
end
index=(find(x==max(x_)));
max_theta=theta(index);
fprintf('The projectile will travel furthest at an angle of %2.2f degrees\n', max_theta);
However, when I run my script it gets stuck running like a forever loop and I have to terminate it. Not sure why this is happening.
  2 Comments
Star Strider
Star Strider on 27 Mar 2019
your ‘y’ vector increases without bound. After 25 iterations, your projectile has traveled 23.3961e+012 metres, so it is apparently in interstellar space.
Change the first statement of your while loop to something like this:
while y(i-1)>=0 & (i <= 25)
until you figure out what the problem is with your code. That limits the number of iterations, making effective troubleshooting easier.
Steven Lord
Steven Lord on 27 Mar 2019
I suspect it's the introduction of anti-gravity.
%calculates y values
a_y=v_fin_y*k;
y(i)=y(i-1)+v_fin_y*time+0.5*a_y*(time^2);
v_fin_y=v_fin_y+a_y*time;
Shouldn't these lines of code make use of g somewhere? It might be useful to write the mathematical expression each line or each section of your code implements as a comment before that line or section, so you can easily check if your equation and your code are doing the same thing.

Sign in to comment.

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!