MATLAB 动图绘制、保存

动图有gif格式和视频的avi格式。

1、sin(x)动图

clear all
h = animatedline;%动画线
axis([0 4*pi -1 1])
box on
x = linspace(0,4*pi,200);

for k = 1:length(x)
    y = sin(x(k));
    addpoints(h,x(k),y);%将数据添加到动画线中
    drawnow%画出动画线
    f=getframe(gcf);  
    imind=frame2im(f);
    [imind,cm] = rgb2ind(imind,256);
    if k == 1;
        imwrite(imind,cm,'test.gif','GIF', 'Loopcount',inf,'DelayTime',1);
    else
        imwrite(imind,cm,'test.gif','GIF','WriteMode','append','DelayTime',1);
    end  
end

  

2、

close all; clear all;
%创建avi文件对象
aviobj = VideoWriter('test.avi','Uncompressed AVI');
open(aviobj) 
%动画部分代码
t = linspace(0,2.5*pi,40);
fact = 10*sin(t);
fig=figure;
[x,y,z] = peaks;
for k=1:length(fact)
    h = surf(x,y,fact(k)*z);
    axis([-3 3 -3 3 -80 80])
    axis off
    caxis([-90 90])
    %获取当前画面
    F = getframe(fig);
    %加入avi对象中
    writeVideo(aviobj,F);
     
    %转成gif图片,只能用256色
    im = frame2im(F);
    [I,map] = rgb2ind(im,256);
    %写入 GIF89a 格式文件    
    if k == 1;
        imwrite(I,map,'test.gif','GIF', 'Loopcount',inf,'DelayTime',0.1);
    else
        imwrite(I,map,'test.gif','GIF','WriteMode','append','DelayTime',0.1);
    end    
end
close(fig);
%关闭avi对象
 close(aviobj);

  

 3、

clear all
close all

mov=VideoWriter('mult_1.avi');
open(mov);
N=50;
om=0.1;
X = linspace(0,12.4,N);
Y = 0*X;
Z2= 0*X;
for it=1:100
    
   Z = cos(X-it*om);
   Y2= cos(X-it*om);

   stem3(X,Y,Z,'r','fill')
   hold on
   stem3(X,Y2,Z2,'k','fill')
   hold on;
   line(X,Y,Z2);

   for ix=1:N
      hold on;
      plot([X(ix) X(ix)],[0 Y2(ix)],'k');
   end;

   hold off
   view(-25,30);

   xlim([X(1) X(end)]);
   ylim([-1 1])
   zlim([-1 1])

   set(gcf,'Color',[1 1 1],'nextplot','replacechildren', 'Visible','off')
   axis off

   FF=getframe(gcf);
   % With "VideoWriter" use "writevideo" to add frames to the video
   writeVideo(mov,FF);
   im = frame2im(FF);
    [I,map] = rgb2ind(im,256);
    %写入 GIF89a 格式文件    
    if it == 1;
        imwrite(I,map,'test.gif','GIF', 'Loopcount',inf,'DelayTime',0.1);
    else
        imwrite(I,map,'test.gif','GIF','WriteMode','append','DelayTime',0.1);
    end    
end;
% Close the video file
close(mov);

  

原文地址:https://www.cnblogs.com/ruo-li-suo-yi/p/8312880.html