example MATLAB animation -> animated gif

I always forget how to make animations in MATLAB, and I never knew how to make animated gifs before. I figured this out for the MATLAB course, but I don’t think I’ll go over it in class, since I don’t want to get into handle graphics nastiness. But for my own reference, and anyone who may be looking for ways to do this, this code gives the gist of it:

clf
theta = linspace(0, 2*pi, 200);
x = cos(theta); y = sin(theta);
hbead = line(x(1), y(1), 'marker', 'o', 'markersize', 8);
htrail = line(x(1), y(1), 'marker', '.', 'color', 'r');
axis([-1 1 -1 1]);
axis('square');
im = {};
for k = 2:length(theta)
    set(hbead, 'xdata', x(k), 'ydata', y(k));
    set(htrail, 'xdata', x(1:k), 'ydata', y(1:k));
    drawnow;
    [im{k}, map] = frame2im(getframe);
end

[temp, map] = rgb2ind(im{2}, 4);
for k = 2:length(theta)
    gifim(:,:,1,k-1) = rgb2ind(im{k}, map);
end
imwrite(gifim, map, 'bead.gif');

Here’s the (ugly) output. The axes need to be expanded, ticks turned off, and most difficult, something needs to be done with the speed. And are there animated GIF compressors out there? This file is huge!

Possibly relevant posts:

Oct 15th, 2009 | Posted in General, Programming, just for kicks
Tags:
  1. Nov 20th, 2009 at 16:15 | #1

    Works for me, except I think you need to use single quotes in the last line:
    imwrite(gifim, map, ‘bead.gif’);

  2. Nov 20th, 2009 at 21:55 | #2

    Thanks. I’ve corrected that now.

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">
CommentLuv Enabled