-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPendulum_R.m
80 lines (34 loc) · 1.27 KB
/
Pendulum_R.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
% Parameters
gravity = 9.81; % Acceleration due to gravity (m/s^2)
pendulumLength = 1.0; % Length of the pendulum (m)
initialAngle = pi/4; % Initial angle of the pendulum (rad)
timeStep = 0.01; % Time step for simulation (s)
totalTime = 10; % Total simulation time (s)
% Create video file
outputVideo = VideoWriter('pendulum_video.avi');
open(outputVideo);
% Simulation loop
t = 0:timeStep:totalTime;
theta = initialAngle * cos(sqrt(gravity/pendulumLength) * t); % Pendulum angle as a function of time
for i = 1:length(t)
% Calculate position of the ball
x = pendulumLength * sin(theta(i));
y = -pendulumLength * cos(theta(i));
% Plot the pendulum and ball
plot([0, x], [0, y], 'b', 'LineWidth', 2); % Pendulum rod
hold on;
plot(x, y, 'ro', 'MarkerSize', 10); % Ball
hold off;
axis([-pendulumLength, pendulumLength, -pendulumLength, 0.2]);
axis equal;
xlabel('X');
ylabel('Y');
title('Pendulum Motion');
% Capture frame and write to video
frame = getframe(gcf);
writeVideo(outputVideo, frame);
% Pause for a short time to control the animation speed
pause(0.01);
end
% Close video file
close(outputVideo);