# Struggling with hold on and hold off placements

6 views (last 30 days)
Isabelle Davies on 10 Apr 2022
Commented: Simon Chan on 10 Apr 2022
I'm trying to animate a moving pendulum for one period, but I'm having trouble using hold on and hold off. I'm trying to make it so that my axes options are retained, but not the plotting of each point. As a result, my 'pendulums' are all stacked on top of each other and I'm not sure how to fix it.
L = 2 ;
g = 9.81 ;
Theta_0 = pi/3 ;
% Equations for pendulum
p = 2*pi*sqrt(L/g)
t = 0:(1/30):2.837 ;
Theta = Theta_0 * cos(sqrt(g/L) * t) ;
x = L * sin(Theta) ;
y = L * (1 - cos(Theta)) ;
figure(1)
hold on
axis equal
axis([-2,2,-2,2]);
for i = 1:length(t)
p1 = plot([0, x(i)], [2, y(i)], '-', 'LineWidth', 6, 'Color', 'k');
p2 = plot(x(i), y(i), 'b.', 'Markersize', 70);
drawnow
end
The result of the for loop is this:
I then thought 'maybe it's just showing every frame on top of each other, and it'll look normal once I put it into a video.
So I did this:
myVideo = VideoWriter('pen2')
open(myVideo)
figure(1)
hold on
axis equal
axis([-2,2,-2,2]);
for i = 1:length(t)
p1 = plot([0, x(i)], [2, y(i)], '-', 'LineWidth', 6, 'Color', 'k');
p2 = plot(x(i), y(i), 'b.', 'Markersize', 70);
frame = getframe ;
writeVideo(myVideo, 1)
end
close(myVideo)
implay pen2.avi
But all that does is open an avi file that's completely blank (see below)
Any help would be greatly appreciated, even though this seems like a simple task I've been working on it for quite some time.
Thanks!

Simon Chan on 10 Apr 2022
L = 2 ;
g = 9.81 ;
Theta_0 = pi/3 ;
% Equations for pendulum
p = 2*pi*sqrt(L/g);
t = 0:(1/30):2.837 ;
Theta = Theta_0 * cos(sqrt(g/L) * t) ;
x = L * sin(Theta) ;
y = L * (1 - cos(Theta)) ;
figure(1)
ax = gca;
p1 = plot(ax,NaN, NaN, '-', 'LineWidth', 6, 'Color', 'k');
hold(ax,'on');
p2 = plot(ax,NaN, NaN, 'b.', 'Markersize', 70);
axis(ax,'equal');
axis(ax,'off'); % Optional
axis(ax,[-2,2,-2,2]);
for i = 1:length(t)
set(p1,'XData',[0, x(i)], 'YData',[2, y(i)]);
set(p2,'XData',x(i),'YData',y(i));
drawnow;
end
hold(ax,'off');
##### 2 CommentsShowHide 1 older comment
Simon Chan on 10 Apr 2022
Great, please accept the answer if you find it useful. Thank you.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by