# Saving plot as a GIF

15 views (last 30 days)
Mahdi Noman on 13 Jan 2022
Edited: Walter Roberson on 13 Jan 2022
Hello,
So I have written a script that takes data points and plots them over a certain x and then pauses and plots the next in a for loop. When I run it it looks great but now I want to save it as a gif and I have no idea how. It's basically lines that are plotted then erased and the next line is plotted. I tried using fanimate but I dont have a function I have data points. I will include my code for reference.
Thank you
%Opens the figure
figure(1)
%Finds the min and max vectors of the two matricies
miny = min(W1);
maxy = max(W1);
%Used to "animate" the matricies over the columns
for i = 1:501
plot(x,W1(:,i), '-b', x,W2(:,i), '-r', 'LineWidth',3)
axis off
%Sets the axis mins and maxes
axis([min(x) max(x) min(miny) max(maxy)])
%Pauses after every i value to give the perception of animation
pause(.001)
end

Walter Roberson on 13 Jan 2022
Edited: Walter Roberson on 13 Jan 2022
%This code assumes that you might be changing x inside your loop. If x is
%constant then it can be done a little better.
filename = 'MyAnimation.gif';
%Opens the figure
figure(1)
%Finds the min and max vectors of the two matricies
miny = min(W1); minminy = min(miny);
maxy = max(W1); maxmaxy = max(maxy);
H = plot(nan, nan, '-b', nan, nan, '-r', 'LineWidth', 3);
axis off
%Used to "animate" the matricies over the columns
for i = 1:501
H(1).XData = x; H(1).YData = W1(:,i);
H(2).XData = x; H(2).YData = W2(:,i);
%Sets the axis mins and maxes
axis([min(x) max(x) minminy maxmaxy])
%Pauses after every i value to give the perception of animation
pause(.001)
F = getframe();
if i == 1
imwrite(F.cdata, F.colormap, filename, 'writemode', 'overwrite', 'DelayTime', 1/30);
FrameSize = [size(F.cdata,1), size(F.cdata,2)];
else
imwrite( imresize(F.cdata, FrameSize), F.colormap, filename, 'writemode', 'append');
end
end
Caution: when your x is not constant and you do not know ahead of time what the maximum and minimum possible x are, then you can run into situations where a captured frame might not be exactly the same size as previous frames. The imresize() of frames after the first frame ensures that particular problem cannot occur. But when it would have occurred, the frame might shift slightly visually -- the right border (especially) might flicker moving back and forth a few pixels.
This problem can be avoided if the x values are constant for all iterations, or at least if the minimum and maximum x and y are known ahead of time.

R2021b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!