| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- clc; clear all; close all;
- % Constants
- g = 9.81;
- L = 2;
- initial_angle = deg2rad(60);
- initial_v = 0;
- initial_conditions = [initial_angle; initial_v];
- t_span = [0 3];
- ode_system = @(t, theta) [
- theta(2);
- -(g/L)*sin(theta(1))
- ];
- [t, theta] = ode45(ode_system, t_span, initial_conditions);
- theta_sol = theta(:, 1);
- dthetadt_sol = theta(:, 2);
- figure;
- plot(t, theta_sol);
- %-------------------------------------------------
- % Pendulum's base position
- x0 = 0; y0 = 0;
- % Animation loop
- figure;
- axis equal;
- xlim([-L, L]); % Set x-axis limits
- ylim([-L, 0.5]); % Set y-axis limits
- xlabel('x (m)');
- ylabel('y (m)');
- title(sprintf('Pendulum Animation (Angle = %.0f deg)', rad2deg(initial_angle)),'FontSize',14);
- for i = 1:length(t)
- % Update pendulum position
- x = x0 + L*sin(theta_sol(i));
- y = y0 - L*cos(theta_sol(i));
- hold on;
- % string
- plot([x0,x], [y0,y], 'k-', 'LineWidth', 2)
- % ball
- plot(x, y, 'ro', 'MarkerSize', 20);
- drawnow;
- pause(0.1);
- hold off;
- cla;
- end
|