%This code assumes that you might be changing x inside your loop. If x is
%constant then it can be done a little better.
filename = 'MyAnimation.gif';
%Opens the figure
figure(1)
%Finds the min and max vectors of the two matricies
miny = min(W1); minminy = min(miny);
maxy = max(W1); maxmaxy = max(maxy);
H = plot(nan, nan, '-b', nan, nan, '-r', 'LineWidth', 3);
axis off
%Used to "animate" the matricies over the columns
for i = 1:501
H(1).XData = x; H(1).YData = W1(:,i);
H(2).XData = x; H(2).YData = W2(:,i);
%Sets the axis mins and maxes
axis([min(x) max(x) minminy maxmaxy])
%Pauses after every i value to give the perception of animation
pause(.001)
F = getframe();
if i == 1
imwrite(F.cdata, F.colormap, filename, 'writemode', 'overwrite', 'DelayTime', 1/30);
FrameSize = [size(F.cdata,1), size(F.cdata,2)];
else
imwrite( imresize(F.cdata, FrameSize), F.colormap, filename, 'writemode', 'append');
end
end
Caution: when your x is not constant and you do not know ahead of time what the maximum and minimum possible x are, then you can run into situations where a captured frame might not be exactly the same size as previous frames. The imresize() of frames after the first frame ensures that particular problem cannot occur. But when it would have occurred, the frame might shift slightly visually -- the right border (especially) might flicker moving back and forth a few pixels.
This problem can be avoided if the x values are constant for all iterations, or at least if the minimum and maximum x and y are known ahead of time.
