Animation using plot inside for loop

98 views (last 30 days)
Garrett Herbst
Garrett Herbst on 8 Oct 2018
Commented: Rahul Wadhwani on 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 Comments
Image Analyst
Image Analyst on 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 on 1 Dec 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

Sign in to comment.

Answers (1)

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

Sign in to comment.

Categories

Find more on Animation in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!