Struggling with hold on and hold off placements
9 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Isabelle Davies
il 10 Apr 2022
Commentato: Simon Chan
il 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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/959200/image.png)
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)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/959205/image.png)
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 Commenti
Risposta accettata
Simon Chan
il 10 Apr 2022
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 Commenti
Più risposte (0)
Vedere anche
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!