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:
- Matlab: Lesson 3 (2/17/2006)
- Raptor chase (10/19/2008)
- CVX in Mathematica via Mathematica <-> Java <-> Matlab? (9/1/2009)
Works for me, except I think you need to use single quotes in the last line:
imwrite(gifim, map, ‘bead.gif’);
Thanks. I’ve corrected that now.