pendulum_ode.m 1021 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. clc; clear all; close all;
  2. % Constants
  3. g = 9.81;
  4. L = 2;
  5. initial_angle = deg2rad(60);
  6. initial_v = 0;
  7. initial_conditions = [initial_angle; initial_v];
  8. t_span = [0 3];
  9. ode_system = @(t, theta) [
  10. theta(2);
  11. -(g/L)*sin(theta(1))
  12. ];
  13. [t, theta] = ode45(ode_system, t_span, initial_conditions);
  14. theta_sol = theta(:, 1);
  15. dthetadt_sol = theta(:, 2);
  16. figure;
  17. plot(t, theta_sol);
  18. %-------------------------------------------------
  19. % Pendulum's base position
  20. x0 = 0; y0 = 0;
  21. % Animation loop
  22. figure;
  23. axis equal;
  24. xlim([-L, L]); % Set x-axis limits
  25. ylim([-L, 0.5]); % Set y-axis limits
  26. xlabel('x (m)');
  27. ylabel('y (m)');
  28. title(sprintf('Pendulum Animation (Angle = %.0f deg)', rad2deg(initial_angle)),'FontSize',14);
  29. for i = 1:length(t)
  30. % Update pendulum position
  31. x = x0 + L*sin(theta_sol(i));
  32. y = y0 - L*cos(theta_sol(i));
  33. hold on;
  34. % string
  35. plot([x0,x], [y0,y], 'k-', 'LineWidth', 2)
  36. % ball
  37. plot(x, y, 'ro', 'MarkerSize', 20);
  38. drawnow;
  39. pause(0.1);
  40. hold off;
  41. cla;
  42. end