Animating a pendulum: error in code
1 view (last 30 days)
Show older comments
Hi guys,
i'm trying to plot the oscillatory motion of a simple pendulum in the form of a GIF or AVI file and i'm trying the following code, but there seems to be an error:
The pendulum generated is not oscillating.
I got a warning when i ran this: Warning: The EraseMode property is no longer supported and will error in a future release.
Also, how do i save the animation as a GIF file?
% A script to animate the motion of the simple pendulum
clc
clear
disp('Specify the initial angle of the pendulum in degrees, e.g., 50')
disp('or press ENTER for the default value.')
theta=input('Initial angular displacement of the pendulum= ');
if isempty(theta)
theta=50
else
theta;
end
theta=theta*pi/180; % convert from degrees to radians
disp('Specify the final time, e.g. tfinal = 25')
disp('or press ENTER for default value.')
tfinal=input('Final time tfinal = ');
if isempty(tfinal)
tfinal=10
else
tfinal;
end
data_init=[0 0; -4 0]; %pendulum length
% rotation matrix
R=[cos(theta) -sin(theta);sin(theta) cos(theta)];
data=R*data_init; % initial pendulum position
bar=line('xdata',[0 data(1)],'ydata',...
[0 data(2)]','linewidth',3,'erase','xor');
mass=line('xdata',data(1),'ydata',data(2),'marker','o',...
'markersize',15,'MarkerFaceColor','b','erase','xor');
hinge=line('xdata',0,'ydata',0,'marker','o',...
'markersize',7,'erase','xor');
axis([-5 5 -5 5])
grid % comment this out if you do like the grid
set(gca,'Fontsize',14)
set(gca,'dataaspectratio',[1 1 1])
box on
dt=0.03; % step−size for solving differential
% equations can be arbitrarily selected
t=0; % initial time
thetadot=0; % initial angular speed
disp('Can maximize the display so you can see the action better,')
disp('then press ENTER.')
disp('If you are happy with the display size, press ENTER.')
pause
% solve the diff eqns using the Euler's method
while(t<tfinal)
t=t+dt;
theta = theta + thetadot*dt;
thetadot=thetadot - 5*sin(theta)*dt; %−0.01*thetadot;
% you can add some friction
R=[cos(theta) -sin(theta);sin(theta) cos(theta)];
datanew=R*data_init;
% change the property values of the bar and hinge objects
set(bar,'xdata',[0 datanew(1)],'ydata',[0 datanew(2)]);
set(mass,'xdata',datanew(1),'ydata',datanew(2));
set(hinge,'xdata',0,'ydata',0)
set(gca,'dataaspectratio',[1 1 1])
drawnow;
end
5 Comments
Answers (1)
Geoff Hayes
on 16 Nov 2020
In order to convert to a series of frames and save as an AVI, just do
% open the video writer
v = VideoWriter('pendulum.avi');
open(v);
% solve the diff eqns using the Euler's method
while(t<tfinal)
% your existing code
drawnow;
% get the frame and write to the file
frame = getframe(gcf);
writeVideo(v,frame);
end
% close the video writer
close(v);
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!