Struggling with hold on and hold off placements
조회 수: 9 (최근 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!
댓글 수: 0
채택된 답변
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Graphics Performance에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!