How can I create animated GIF images in MATLAB ?

3,473 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 1 Aug 2022
Edited: MathWorks Support Team on 28 Mar 2022
In MATLAB 2022a, export to GIF format is supported by the exportgraphics function using the ‘Append’ option.  For example:
x = 0:0.01:1;
p = plot(nan,nan);
p.XData = x;
for n = 1:0.5:5
      p.YData = x.^n;
For releases prior to R2022a, follow the example "Write Animated GIF" on the imwrite reference page.
huanyu on 2 Jul 2022
Thanks for your comment, I have used imwrite to generate gif successfully.

Sign in to comment.

More Answers (3)

Chad Greene
Chad Greene on 4 Jun 2017
Edited: MathWorks Support Team on 25 Sep 2022
Or, for a much simpler option, use the gif function on File Exchange.
  1 Comment
Will Reeves
Will Reeves on 25 Jul 2022
... if you're operating on figure window rather than image data?

Sign in to comment.

Shashank Rai
Shashank Rai on 1 May 2017
Edited: Chad Greene on 17 Oct 2018
x = 0:0.01:1;
filename = 'testnew51.gif';
for n = 1:0.5:5
y = x.^n;
frame = getframe(1);
im = frame2im(frame);
[imind,cm] = rgb2ind(im,256);
if n == 1;
imwrite(imind,cm,filename,'gif', 'Loopcount',inf);
Fei Jia
Fei Jia on 11 Nov 2021
Thank you! This helped me in creating a gif for my student.

Sign in to comment.

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?
DGM on 25 Jul 2022
Edited: DGM on 25 Jul 2022
MIMT gifwrite() works to write I/IA/RGB/RGBA and indexed color images from 4D arrays. MIMT gifread() can read the image with minimal hassle.
Pay attention to the synopsis if you intend to read GIF files in versions newer than R2018a -- regardless of what tools you're using. If you're using a newer version, you will not be able to correctly read most multiframe color GIF files unless you make that effort.
Stitching the frames together to generate a colormap is a bad idea, since it means that no frame can have a unique optimized local color table. The more dynamic the color content is over the sequence, the worse the entire image will look.

Sign in to comment.


Find more on Animation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!