Code covered by the BSD License  

Highlights from
frames2gif

from frames2gif by Paxon Frady
Converts frames captured by getframes to an animated gif.

frames2gif(filename, frames, varargin)
function frames2gif(filename, frames, varargin)
% frames2gif(filename, frames, varargin): This function takes an array of 
% frames (made by getframe) and converts them to an animated gif.
% Each index in the frames array should contain what is returned by
% getframe - i.e. frames(1) = getframe(figure_handle). This takes each of
% those frames and converts them to something that can be saved as a gif.
% The frames is saved as [filename]. Extra parameters can be passed that
% would be passed to imwrite.
%
% @param: filename the name to save the gif.
% @param: frames the frames to animate.
% @param: varargin the extra params to pass to imwrite.
%     I.e. 'DelayTime', 0 will not put any delay between frames.
%          'LoopCount', Inf will repeat the animation continuously.
%
% @file: frames2gif.m
% Contains a function that takes a cell array of frames and creates a gif
% animation.
% @author: Paxon Frady
% @created: 4/13/2010

% To make an animated gif from matlab, we have to convert the movie into an
% indexed movie with a colormap. So we have to make a colormap that has all
% of the colors of the whole movie.
all_frames = [frames.cdata]; % Put all the frames of the movie together.
[~, map] = cmunique(double(all_frames)/255); % Get all of the unique colors out.

im = zeros([size(frames(1).cdata, 1), size(frames(1).cdata, 2), 1, length(frames)]);

% Now we just have to get the indices for each of the colors for each
% frame.
for i = 1:length(frames)   
    % rgb2ind for some reason returns 0-based indices, so have to add 1 at
    % the end.
    im(:,:,1,i) = rgb2ind(double(frames(i).cdata)/255, map, 'nodither') + 1;
end

% imwrite allows us to write gifs in this format.
imwrite(im, map, 'gif', filename, varargin{:});

end

Contact us