抛砖引玉,给出两种MATLAB画动图的方法,以画爱心为例吧,我怎么这么有爱心(俗)。
1.使用plot
%% 爱心的参数方程
t=0:0.1:2*pi;
x=16*sin(t).^3;
y=13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t);
%% 动图画图并保存为GIF
figure;
h = plot(x(1),y(1),'r');
axis([-20,20,-20,20]);
axis off
[A,map] = rgb2ind(frame2im(getframe),256);%getframe获取当前画面
imwrite(A,map,'1.gif','LoopCount',inf,'DelayTime',0.1);
for idx = 2:length(t)
h.XData(idx) = x(idx);
h.YData(idx) = y(idx);
drawnow
[A,map] = rgb2ind(frame2im(getframe),256);
imwrite(A,map,'1.gif','WriteMode','append','DelayTime',0.1);
end
其中第7行代码h为Line对象。通过改变其XData和YData值的同时加入刷新图形窗口命令drawnow来实现动态画图,然后通过imwrite函数将动图保存为GIF。结果如下:
2.使用animatedline+addpoints
%% 爱心方程
t=0:0.1:2*pi;
x=16*sin(t).^3;
y=13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t);
%% 动图画图并保存为GIF
h = animatedline('Color','r');%创建动画线型
axis([-20,20,-20,20]);
axis off
[A,map] = rgb2ind(frame2im(getframe),256);
imwrite(A,map,'2.gif','LoopCount',inf,'DelayTime',0.1);
for idx = 1:length(t)
addpoints(h,x(idx),y(idx));
drawnow
[A,map] = rgb2ind(frame2im(getframe),256);
imwrite(A,map,'2.gif','WriteMode','append','DelayTime',0.1);
end
结果如下:
微信公众号:三猫Matlab