MATLAB: (Same trajectory problem now with different plot results and problems). I’m trying to write a script that will plot a balls trajectory.

for loopspiecewisepreallocationtrajectory

Intial position and velocity are known (Vi, xi, yi), and air resistance is neglected. Originally I used t=zeros(1,3600); and with the help of someone else t(k2)=(k2-1)*dt; where dt is defined as 1. In this iteration tried to get Y and YX to run 10 iterations from 0 seconds to 'tend', the time when the ball lands. I'm lost in the wind here so any help would be appreciated.
% %%%%code below is what I'm trying to run (still haven't figured out formatting for these message boards, code stops at 'plot(YX,Y)'%%%
%initial values
xi=0;
yi=0;
Vi= 20; % meters per second
g=-9.81; %meters per second squared
THy=[5:10:85];
THx=[0:1:90];
t=zeros(1,10);
for k1 = 1:length(THy)
for k2=1:10
vyi=Vi.*sind(THy(k1));%initail vel. in y
vyx=Vi.*cosd(THy(k1));%initial vel. in x
%t(k2)=(k2-1)*dt;
%vyi=Vi.*sind(THy(k1));
tvzero=vyi./g;%time when ball is at max height
tend=2.*tvzero;%time when ball hits the ground
dt=tend./10;
t(k2)=(k2-1)*dt;
%position of the ball
Y(k1,k2)=yi+vyi.*t(k2)+.5.*g.*(t(k2).^2);%height of the ball
YX(k1,k2)=xi+vyx.*t(k2);%horizonatal distance traveled, no air resitance
end
end
plot(YX,Y)

Best Answer

Two changes:
1. Make ‘g’ positive here:
g = 9.81; %meters per second squared
2. Switch the indices and subtract the gravitational acceleration term here:
Y(k2,k1)=yi+vyi.*t(k2)-0.5.*g.*(t(k2).^2);%height of the ball
YX(k2,k1)=xi+vyx.*t(k2);%horizonatal distance traveled, no air resitance
and you get the plot you want (or at least one that looks good to me).