参考自:MATLAB CENTRAL - How can I create animated GIF images in MATLAB ?
将那个循环的代码改成:
outfile = 'x.gif';
for t = 0:.1:2*pi
theta=theta0*cos(sqrt(g/l)*t);
x=l*sin(theta);
y=(-1)*l*cos(theta);
set(head,'xdata',x,'ydata',y);
set(body,'xdata',[0;x],'ydata',[0;y]);
% drawnow
frame = getframe(1);
im = frame2im(frame);
[imind,cm] = rgb2ind(im, 256);
if t == 0
imwrite(imind,cm,outfile,'gif','DelayTime',0,'loopcount',inf);
else
imwrite(imind,cm,outfile,'gif','DelayTime',0,'writemode','append');
end
end