MATLAB: Last Part of Baseball Trajectory Problem

for loopsiteration problemsmax valuepreallocation

My issues concerns the for loop containing k3 and k4 at the bottom of the code (top half is just for reference I guess, although Im sure you've seen it a couple times already). Anyway what I'm trying to get is the maximum value of XX as well as the THx that created it. Right now the program repeats 3 or 4 iterations with the break command.
if true
%trajectory of a baseball, no air resistance
%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:11
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(k2,k1)=yi+vyi.*t(k2)-.5.*g.*(t(k2).^2);%height of the ball
YX(k2,k1)=xi+vyx.*t(k2);%horizonatal distance traveled, no air resitance
end
end
plot(YX,Y)
grid on
title('Trajectory of a Baseball')
xlabel('Horizontal Distance')
ylabel('Height')
axis([0,45,0,25])
for k3=1:length(THx)
for k4=1:11
vyi=Vi.*sind(THx(k3));%initail vel. in y
tvzerob=vyi./g;%time when ball is at max height
tendb=2.*tvzerob;%time when ball hits the ground
vyx=Vi.*cosd(THx(k3));%initial vel. in x
dt=tendb./10;
t(k4)=(k4-1).*dt;
XX(k4,k3)=xi+vyx.*t(k4);%horizontal distance travelled
%I need to find the maximum valule of XX and the THx that created
%it, without the break it runs a couple more iterations.
%[M,I]=max(XX);
[M,I]=max(XX);
fprintf('The maximum distance thrown is %f at an angle of %f degrees\n',M,I)
break
end
end
end

Best Answer

You already calculated the time the ball hits the ground (in ‘tendb’, so the maximum value for ‘XX’ for each iteration would seem to me to be:
MaxXX(k4,k3)=xi+vyx.*tendb;%horizontal distance travelled
then get the maximum of ‘MaxXX’ and find the value of your independent variable that created it (by subscript reference from the maximum value of ‘MaxXX’).
I found your code a bit confusing, so I didn’t run it this time.