動圖有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);