MATLAB Answers

How can I create animated GIF images in MATLAB ?

4,220 views (last 30 days)
I would like to know if there is MATLAB functionality to create an animated GIF in MATLAB.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 12 Jun 2017
Use the 'imwrite' function to create an animated GIF. An animated GIF contains a series of images all combined into one file. For this example,
1. Draw a series of plots for the function y = x^n for different values of n
2. Capture them as images
3. Write them into a GIF file
h = figure;
axis tight manual % this ensures that getframe() returns a consistent size
filename = 'testAnimated.gif';
for n = 1:0.5:5
% Draw plot for y = x.^n
x = 0:0.01:1;
y = x.^n;
plot(x,y)
drawnow
% Capture the plot as an image
frame = getframe(h);
im = frame2im(frame);
[imind,cm] = rgb2ind(im,256);
% Write to the GIF File
if n == 1
imwrite(imind,cm,filename,'gif', 'Loopcount',inf);
else
imwrite(imind,cm,filename,'gif','WriteMode','append');
end
end
For a more detailed description on creating an animated GIF File, see the example “Write Animated GIF” on the 'imwrite' function reference page:

  5 Comments

Show 2 older comments
Michael Abboud
Michael Abboud on 1 Aug 2017
That's a good suggestion, thanks for commenting! I have submitted an enhancement request for this functionality, so it may be considered for a future release of MATLAB.
Michael Chan
Michael Chan on 15 Oct 2018
Very useful and easy to modify. Thanks a lot.
Coleman Barrie
Coleman Barrie on 15 Jun 2019
Thank you for writing this very helpful as a framework to modify

Sign in to comment.

More Answers (3)

Chad Greene
Chad Greene on 4 Jun 2017
Or, for a much simpler option, use the gif function on File Exchange.

  0 Comments

Sign in to comment.


Alec
Alec on 19 Dec 2013
So it appears that `imwrite` now supports writing animated grayscale GIFs "When writing multiframe GIF images, X should be an 4-dimensional M-by-N-by-1-by-P array, where P is the number of frames to write."
But if I try to pass it an M-by-N-by-3-by-P it seems to treat each RGB color channel as a separate grayscale frame. Is there now way to write an animated color GIF without a for loop over the frames?

  0 Comments

Sign in to comment.


Shashank Rai
Shashank Rai on 1 May 2017
Edited: Chad Greene on 17 Oct 2018
x = 0:0.01:1;
figure(1)
filename = 'testnew51.gif';
for n = 1:0.5:5
y = x.^n;
plot(x,y)
drawnow
frame = getframe(1);
im = frame2im(frame);
[imind,cm] = rgb2ind(im,256);
if n == 1;
imwrite(imind,cm,filename,'gif', 'Loopcount',inf);
else
imwrite(imind,cm,filename,'gif','WriteMode','append');
end
end

  1 Comment

Coleman Barrie
Coleman Barrie on 15 Jun 2019
Thank you for writing this very helpful as a framework to modify

Sign in to comment.

Sign in to answer this question.