Animation using plot inside for loop

133 vues (au cours des 30 derniers jours)
Garrett Herbst
Garrett Herbst le 8 Oct 2018
Commenté : Rahul Wadhwani le 30 Août 2022
I am trying to create an animation by using the plot function inside of a for loop. No matter what I do, I just get back the same still figure that opens. This figure opens over and over again when I close it.
figure(5)
for n = 1:1000
pos = xout(n,1)
x_origin = 0;
y_origin = 0;
x_bob = 0.75*sin(pos);
y_bob = -0.75*cos(pos);
plot([x_origin,x_bob],[y_origin,y_bob])
axis equal
xlim([-2 2])
ylim([-2 2])
drawnow
end
'xout' is a matrix with the angle values of a pendulum in the first column.
  3 commentaires
Image Analyst
Image Analyst le 9 Oct 2018
I get a line swinging around like hands on a clock. Maybe put a pause(0.1) at the bottom of the loop to slow it down if you can't see it move.
Stephen Wilkerson
Stephen Wilkerson le 1 Déc 2018
Yes this: works fine as a .m file, but if put in a live script does not work, is there a way to animate a live script?
figure(5)
for n = 1:100
x_origin = 0;
y_origin = 0;
x_bob = 0.75*sin(n);
y_bob = -0.75*cos(n);
plot([x_origin,x_bob],[y_origin,y_bob])
axis equal
xlim([-2 2])
ylim([-2 2])
drawnow
end

Connectez-vous pour commenter.

Réponses (1)

ANKUR KUMAR
ANKUR KUMAR le 9 Oct 2018
clc
clear
h=figure
for n = 1:10
x_origin = 0;
y_origin = 0;
x_bob = 0.75*sin(n);
y_bob = -0.75*cos(n);
plot([x_origin,x_bob],[y_origin,y_bob])
axis equal
xlim([-2 2])
ylim([-2 2])
make_animation( h,n,'sample_animation.gif' )
pause(0.2) %you can enter the time in pause to change the loop
end
function make_animation( h,index,filename )
drawnow
frame = getframe(h);
im = frame2im(frame);
[imind,cm] = rgb2ind(im,256);
if index == 1
imwrite(imind,cm,filename,'gif', 'Loopcount',inf);
else
imwrite(imind,cm,filename,'gif','WriteMode','append');
end
end
If you are using older version than 2016a, then write make_animation in separate function and then run the program, as older version of MATLAB doesn't support writing functions inside in the script.
  2 commentaires
Carlos Eduardo Gonzalez Pabon
How can I speed up the animation?
Rahul Wadhwani
Rahul Wadhwani le 30 Août 2022
@Carlos Eduardo Gonzalez Pabon you can change the value in pause() to speed up or slow down your animation.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Animation dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by