Hitting a home run on a computer

The code on the other page is kind of unwieldy for tweaking the speed and angle of the ball. We can revise it to make it easier to try different values of $v$ and $\theta$. Let's wrap all the code in a function of those two variables and include a numerical test to see if the ball clears the outfield fence.

function hitball(v, theta)
% simulate trajectory of a baseball hit with speed v (m/s) and angle (degrees)
% make a plot and determine if it clears the 17 ft outfield fence at 3
 
  x = 0.0;      % horizontal position of home plate, meters
  y = 1.0;      % height of ball over strike zone
 
  % initial position and speed of ball
  u0 = [x, y, v*cosd(theta), v*sind(theta)]; 
 
  % solve for the first ten seconds of flight
  tspan = [0 10];  
 
  % solve the baseball equations numerically
  [t, u] = ode45(@f_withdrag, tspan, u0);
 
  % get the x,y coordinates from the solutions and plot
  figure(1); clf()
  x = u(:,1);
  y = u(:,2);
  plot(x, y, 'r-')
  hold on
 
  plot([120, 120], [0, 5.2], 'k-', 'linewidth',2)
 
  legend('baseball path', 'outfield fence')
 
  grid on
  xlim([-10, 130])
  ylim([0, 110])
  xlabel("x, meters")
  ylabel("y, meters")
  title("baseball trajectory")
 
  % find height of ball at x=120 by interpolation
  y120 = interp1(x, y, 120);
 
  if (y120 > 5.2)
    disp(strcat('hooray! home run! height of ball at outfield fence is ', num2str(y120), ' meters'))
  elseif (y120 >= 0.0)
    disp(strcat('boo! fly ball!  ball hit outfield fence at height y = ', num2str(y120), ' meters'))
  elseif (y120 < 0.0)
    disp('boo! fly ball!  ball didn''t reach fence')
  end
 
end

Now you can try different speeds $v$ and angles $\theta$ by calling the ``hitball`` function at the Matlab prompt. For example, to compute the trajectory for $v=20$ and $\theta = 70^\circ$, type

>> hitball(20, 70)

Questions