フィルターのクリア

Animation using plot inside for loop

74 ビュー (過去 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 Center および File ExchangeAnimation についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by