recipes : movies : How do I make an animated gif?

Problem

How do I make an animated gif with MATLAB?

Solution

We will make a 3-D matrix of uniformly distributed noise and turn this into a an animated gif.

data=rand(100,100,20); %100 by 100 and 20 frames

%data go from 0 to 1, so lets convert to 8 bit unsigned integers for saving
data=data*2^8;
data=uint8(data);

%Write the first frame to a file named animGif.gif
imwrite(data(:,:,1),'animGif.gif','gif','writemode','overwrite',...
        'LoopCount',inf,'DelayTime',0);

%Loop through and write the rest of the frames
for ii=2:size(data,3)
     imwrite(data(:,:,ii),'animGif.gif','gif','writemode','append','DelayTime',0)
end

That's it! This is what the result looks like:

Discussion

Note that you can also write the animated gif in one line as in this example.