pendulum_damped.m 1.0 KB

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