pendulum_variablelength.m 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. clc; clear all; close all;
  2. % Constants
  3. g = 9.81;
  4. L = 2;
  5. omega = 1.5;
  6. A = 0.4;
  7. initial_angle = deg2rad(20);
  8. initial_v = 0;
  9. initial_conditions = [initial_angle; initial_v];
  10. t_span = [0 10];
  11. length_time = @(l0, t, A, omega) l0 + A*cos(omega*t);
  12. dlength_dtime = @(t, A, omega) -A*omega*sin(omega*t);
  13. length_span = length_time(L, t_span, A, omega);
  14. ode_system = @(t, theta) [
  15. theta(2);
  16. -(g/length_time(L, t, A, omega))*sin(theta(1)) - (2*dlength_dtime(t, A, omega)/length_time(L, t, A, omega))*theta(2)
  17. ];
  18. [t, theta] = ode45(ode_system, t_span, initial_conditions);
  19. theta_sol = theta(:, 1);
  20. dthetadt_sol = theta(:, 2);
  21. figure;
  22. plot(t, theta_sol);
  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, 0.5]); % 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(t)
  35. % Update pendulum position
  36. x = x0 + length_span(i)*sin(theta_sol(i));
  37. y = y0 - length_span(i)*cos(theta_sol(i));
  38. hold on;
  39. % string
  40. plot([x0,x], [y0,y], 'k-', 'LineWidth', 2)
  41. % ball
  42. plot(x, y, 'ro', 'MarkerSize', 20);
  43. drawnow;
  44. pause(0.1);
  45. hold off;
  46. cla;
  47. end