作业帮 > 综合 > 作业

MATLAB中单摆怎么保存成gif格式的

来源:学生作业帮 编辑:拍题作业网作业帮 分类:综合作业 时间:2024/04/28 02:41:17
MATLAB中单摆怎么保存成gif格式的
%制作动画
%挂摆横梁
plot([-0.3;0.3],[0;0],'color','y','linestyle','-',...
'linewidth',10);
g=0.98;
%重力加速度,可以调节摆的摆速
l=1;theta0=pi/4;x0=l*sin(theta0);y0=(-1)*l*cos(theta0);
axis([-0.75,0.75,-1.25,0]);
axis('on');
%不显示坐标轴
%创建摆锤
head=line(x0,y0,'color','r','linestyle','.',...
'erasemode','xor','markersize',40);
%创建摆杆
body=line([0;x0],[0;y0],'color','b','linestyle','-',...
'erasemode','xor');
%摆的运动
t=0;
dt=0.01;
while 1
t=t+dt;
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
end
参考自: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