Animation using plot inside for loop

조회 수: 110 (최근 30일)
Garrett Herbst
Garrett Herbst 2018년 10월 8일
댓글: Rahul Wadhwani 2022년 8월 30일
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
Image Analyst
Image Analyst 2018년 10월 9일
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 2018년 12월 1일
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

댓글을 달려면 로그인하십시오.

답변 (1개)

ANKUR KUMAR
ANKUR KUMAR 2018년 10월 9일
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
Carlos Eduardo Gonzalez Pabon
Carlos Eduardo Gonzalez Pabon 2022년 4월 7일
How can I speed up the animation?
Rahul Wadhwani
Rahul Wadhwani 2022년 8월 30일
@Carlos Eduardo Gonzalez Pabon you can change the value in pause() to speed up or slow down your animation.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Animation에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by