Create an animated GIF: My code plots only the first image
4 views (last 30 days)
Show older comments
Hi All, I have written some code to create an animated GIF image, but I don't get any update in the image sequence, it only picks up the first image. I don't get any error messages or warnings either and the drawnow sequence works ok.
I have copied below the part of the code that is relevant for this question. I would really appreciate any ideas on this.
Many thanks.
set(fig1,'Units','normalized','Position',[0 0 1 1]);
set(fig1,'Units','pixels');
% Get figure size
pos = get(gcf, 'Position');
left=pos(1);
bottom=pos(2);
width = pos(3);
height = pos(4);
% Preallocate data (for storage frame data)
mov = zeros(height, width, 1, Imax, 'uint8');
for k=1:Imax
(...)
set(fig1,'Units','pixels');
set(fig1,'Position',[left bottom width height]);
drawnow
% Get frame as an image
f = getframe(fig1);
% Create a colormap for the first frame. For the rest of the frames,
% use the same colormap
if k==1
[mov(:,:,1,k), map] = rgb2ind(f.cdata, 256, 'nodither');
else
mov(:,:,1,k) = rgb2ind(f.cdata, map, 'nodither');
end
end
imwrite(mov, map, 'animation.gif', 'DelayTime',0, 'LoopCount', inf)
0 Comments
Answers (2)
Sean de Wolski
on 12 Dec 2014
It doesn't look like you're actually changing anything in the figure on each iteration. Don't you want to re-plot?
0 Comments
Saleta
on 12 Dec 2014
1 Comment
Sean de Wolski
on 12 Dec 2014
I don't know. I typically don't take the movie approach and instead use the 'writemode append' option (streaming rather than storing).
% Setup
[T, x, y, ang, ~, hh1, hh2, ht, fig] = pendulum_setup();
% Animate and add animation frame to the movie structure
for id = 1:length(T)
% Update XData and YData
set(hh1(1), 'XData', T(id) , 'YData', ang(id, 1))
set(hh1(2), 'XData', T(id) , 'YData', ang(id, 2))
set(hh2(1), 'XData', [0, x(id, 1)] , 'YData', [0, y(id, 1)])
set(hh2(2), 'XData', x(id, :) , 'YData', y(id, :))
set(ht, 'String', sprintf('Time: %0.2f sec', T(id)))
% Get frame as an indexed image with a map
I = frame2im(getframe(fig));
[Ind, map] = rgb2ind(I,256,'nodither');
% Decide what to do
if id == 1
% First iteration, set up GIF properties: loop count and delay time
imwrite(Ind,map,'animation.gif','gif','LoopCount',Inf,'DelayTime',0);
else
% All other iterations, append new frame
imwrite(Ind,map,'animation.gif','gif','WriteMode','append','DelayTime',0);
end
end
pendulum_setup is attached.
If it does work, then just go in and modify the pieces you need.
See Also
Categories
Find more on Animation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!