Matlab动画及Gif图片生成
今天在Matlab论坛上碰到有坛友求助动画和Gif图片生成的问题。大概知道怎么弄,实际做做查查发现还是有不少地方,新版本跟旧版本的Matlab存在差异。鉴于我是一个比较懒的人,暂且把代码和图片记录于下,以备后记。 主要是animatedline 和 imwrite的使用,其中有一个坑点是gif一定得是索引图像。
clear;clc;
close all;
t=
0:pi/
10:
10*pi;
x=
sin(t);
y=
cos(t);
figure;
subplot(
2,
1,
1);
axis([
0 10*pi -
1.1 1.1]);
L11 = line([
0 10*pi],[
0 0]);
set(L11,
'linestyle',
'--',
'color',
'g');
L12 = line([
0 10*pi],[-
1 -
1]);
set(L12,
'linestyle',
'--',
'color',
'r');
L13 = line([
0 10*pi],[
1 1]);
set(L13,
'linestyle',
'--',
'color',
'r');
xticks =
0:pi:
10*pi;
set(gca,
'xtick',xticks);
xtickslabel = [{
'0'},{
'\pi'}, {
'2\pi'}, {
'3\pi'}, {
'4\pi'}, ...
{
'5\pi'}, {
'6\pi'}, {
'7\pi'}, {
'8\pi'}, {
'9\pi'}, {
'10\pi'}];
set(gca,
'xticklabel', xtickslabel);
title(
'x = sin(t)');
xlabel(
'x');
subplot(
2,
1,
2);
axis([
0 10*pi -
1.1 1.1]);
L21 = line([
0 10*pi],[
0 0]);
set(L21,
'linestyle',
'--',
'color',
'g');
L22 = line([
0 10*pi],[-
1 -
1]);
set(L22,
'linestyle',
'--',
'color',
'r');
L23 = line([
0 10*pi],[
1 1]);
set(L23,
'linestyle',
'--',
'color',
'r');
xticks =
0:pi:
10*pi;
set(gca,
'xtick',xticks);
xtickslabel = [{
'0'},{
'\pi'}, {
'2\pi'}, {
'3\pi'}, {
'4\pi'}, ...
{
'5\pi'}, {
'6\pi'}, {
'7\pi'}, {
'8\pi'}, {
'9\pi'}, {
'10\pi'}];
set(gca,
'xticklabel', xtickslabel);
xlabel(
'y');
title(
'y = cos(t)');
subplot(
2,
1,
1);
h1 = animatedline(
'color',
'b');
for k =
1:
length(t)
addpoints(h1,t(k),
x(k));hold on;
drawnow update
pause(
0.
01);
im = frame2im(getframe(gcf));
[I,
map] = rgb2ind(im,
20);
if (k==
1)
imwrite(I,
map,
'MyGif.gif1',
'gif',
'Loopcount',inf,
'DelayTime',
0.
01);
else
imwrite(I,
map,
'MyGif.gif1',
'gif',
'WriteMode',
'append',
'DelayTime',
0.
01);
end
end
subplot(
2,
1,
2);
h2 = animatedline(
'color',
'r');
for k =
1:
length(t)
addpoints(h2,t(k),
y(k));hold on;
drawnow update
pause(
0.
01);
im = frame2im(getframe(gcf));
[I,
map] = rgb2ind(im,
20);
imwrite(I,
map,
'MyGif.gif1',
'gif',
'WriteMode',
'append',
'DelayTime',
0.
01);
end
clear;clc;
close all;
z=
0:pi/10:10*pi;
x=sin(z);
y=cos(z);
figure;
for k =
1:length(z)
clf;
xlabel(
'x');ylabel(
'y');zlabel(
'z');
axis([-
1 1 -
1 1 0 40]);hold on;
plot3(x(
1:k),y(
1:k),z(
1:k),
'color',
'b');
plot3(x(k),y(k),z(k),
'r.',
'markersize',
20);
hold off;
im = frame2im(getframe(gcf));
[
I, map] = rgb2ind(im,
20);
if (k==
1)
imwrite(
I,map,
'MyGif2.gif',
'gif',
'Loopcount',inf,
'DelayTime',
0.
01);
else
imwrite(
I,map,
'MyGif2.gif',
'gif',
'WriteMode',
'append',
'DelayTime',
0.
01);
end
end
转载请注明原文地址: https://ju.6miu.com/read-962960.html