Advertisement
NaroxEG

plotProjectile MatLab Function

Nov 4th, 2024
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.98 KB | None | 0 0
  1. function [y_values] = plotProjectile(vi, p_angle, t_values)
  2.     syms t
  3.     g = 9.81;
  4.     % y = vi * sin(alpha)t - 0.5*g(t^2)
  5.     y(t) = vi * sind(p_angle) * t - 0.5 * g * (t^2);
  6.     y_values = double(subs(y, t, t_values));
  7.     plot(t_values, y_values, "Color", [1,0,0], "Marker","square");
  8.     ylim([0 max(y_values)]);
  9.     xlim([0 max(t_values)]);
  10.     title("Projectile Motion with Tangent Vectors");
  11.     xlabel("Time (seconds)");
  12.     ylabel("Height (meters)");
  13.     hold on
  14.     % Getting derivative of y with respect to time to draw tanjent lines
  15.     dy_dt = diff(y, t);
  16.     dy_dt_values = double(subs(dy_dt, t, t_values));
  17.     line_length = (t_values(2) - t_values(1));
  18.     % Offset variable to make the text a little bit away from the
  19.     % main graph to avoid overlapping
  20.     vertical_offset = 0.2;
  21.     for i = 1:length(t_values)
  22.         %{
  23.             Both the vectors y, t have the same size, so we can get y(t)
  24.             values at each drawn point by using index of that element in
  25.             vector, which I called ( i ) in my example.
  26.         %}
  27.         t0 = t_values(i);
  28.         y0 = y_values(i);
  29.         slope = dy_dt_values(i);
  30.         %{
  31.             line length should be equal square root of (dx)^2 + (dy)^2
  32.             and dy = slope * dx where slope = dy/dx
  33.             therefore line length = dx * square root of (1 + slope^2)
  34.             and multiplied by 5 for scaling on the plot
  35.         %}
  36.         dx = (line_length * 5 / sqrt(1 + slope^2));
  37.         quiver(t0, y0 , dx, slope * dx, 'b', 'LineWidth', 1, 'MaxHeadSize', 0.5);
  38.         text(t0, y0 + vertical_offset, sprintf('v = %.2f', slope), ...
  39.             'FontSize', 8, 'Color', 'blue');
  40.         % Drawing vertical and horizontal at each point
  41.         quiver(t0, y0, 0, dx * slope, 'k', 'LineWidth', 1, 'MaxHeadSize', 0.5);
  42.         quiver(t0, y0, dx, 0, 'k', 'LineWidth', 1, 'MaxHeadSize', 0.5);
  43.     end
  44.     legend("Projectile Path", "Tangent Vectors (V)", "Vertical and Horizontal Components");
  45.     hold off
  46. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement