pendulum_damped_driven.m 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. clc; clear all; close all;
  2. c = 0.5; m = 1; g = 9.81; L = 1; initial_angle = deg2rad(30);
  3. omega = 0.6*sqrt(g/L); f0 = 10;
  4. ode_system = @(t, theta) [
  5. theta(2);
  6. ((-m*g*L*sin(theta(1))) - (c*theta(2)) + (f0*cos(omega*t))) / (m*L^2)
  7. ];
  8. t_span = [0, 150]
  9. initial_conditions1 = [initial_angle, 0];
  10. [t1, theta1] = ode45(ode_system, t_span, initial_conditions1);
  11. theta_sol1 = theta1(:, 1);
  12. dthetadt_sol1 = theta1(:, 2);
  13. initial_conditions2 = [initial_angle+0.4, 0];
  14. [t2, theta2] = ode45(ode_system, t_span, initial_conditions2);
  15. theta_sol2 = theta2(:, 1);
  16. dthetadt_sol2 = theta2(:, 2);
  17. figure;
  18. hold on;
  19. xlim(t_span);
  20. plot(t1, theta_sol1, "Color", "red");
  21. plot(t2, theta_sol2, "Color", "blue");
  22. legend show;
  23. %-------------------------------------------------
  24. % Pendulum's base position
  25. x0 = 0; y0 = 0;
  26. % Animation loop
  27. figure;
  28. axis equal;
  29. xlim([-L, L]); % Set x-axis limits
  30. ylim([-L, L]); % Set y-axis limits
  31. xlabel('x (m)');
  32. ylabel('y (m)');
  33. title(sprintf('Pendulum Animation (Angle = %.0f deg)', rad2deg(initial_angle)),'FontSize',14);
  34. for i = 1:length(t1)
  35. % Update pendulum position
  36. x1 = x0 + L*sin(theta_sol1(i));
  37. y1 = y0 - L*cos(theta_sol1(i));
  38. x2 = x0 + L*sin(theta_sol2(i));
  39. y2 = y0 - L*cos(theta_sol2(i));
  40. hold on;
  41. % string
  42. plot([x0,x1], [y0,y1], 'k-', 'LineWidth', 2);
  43. plot([x0,x2], [y0,y2], 'k-', 'LineWidth', 2);
  44. % ball
  45. plot(x1, y1, 'ro', 'MarkerSize', 20);
  46. plot(x2, y2, 'bo', 'MarkerSize', 20);
  47. drawnow;
  48. pause(0.01);
  49. hold off;
  50. cla;
  51. end