Animation using plot inside for loop

111 Ansichten (letzte 30 Tage)
Garrett Herbst
Garrett Herbst am 8 Okt. 2018
Kommentiert: Rahul Wadhwani am 30 Aug. 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 Kommentare
Image Analyst
Image Analyst am 9 Okt. 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 am 1 Dez. 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

Melden Sie sich an, um zu kommentieren.

Antworten (1)

ANKUR KUMAR
ANKUR KUMAR am 9 Okt. 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 Kommentare
Carlos Eduardo Gonzalez Pabon
How can I speed up the animation?
Rahul Wadhwani
Rahul Wadhwani am 30 Aug. 2022
@Carlos Eduardo Gonzalez Pabon you can change the value in pause() to speed up or slow down your animation.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Animation finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by