Struggling with hold on and hold off placements

8 次查看(过去 30 天)
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
Simon Chan 2022-4-10
How about this?
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 个评论
Isabelle Davies
Isabelle Davies 2022-4-10
Holy sh*t it worked! Thank you so much! This has literally made me cry so many times
Simon Chan
Simon Chan 2022-4-10
Great, please accept the answer if you find it useful. Thank you.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by