Search code examples
matlabmatlab-figure

MATLAB- How o save an animated function as a gif


I'm using function called "animated line" to create some animated function. I would like to understand how can I save my function as a GIF to use it elsewhere, e.g. PowerPoint. I'm trying to use a gif function but I cannot. Could anyone suggest me how to achieve it or how to use correctly gif function? Here a simple code:

    numpoints = 100000; 
x = linspace(0,4*pi,numpoints); 
y = square(x); 
y2 = 3 +square(x+1);
figure 
h = animatedline('Color','b','LineWidth',2); 
h2 = animatedline('Color','r','LineWidth',2);
grid on;
axis([0,12,-3,+6]) 
for k = 1:numpoints 
  addpoints(h,x(k),y(k)) 
  addpoints(h2,x(k),y2(k)) 
  drawnow  


end

Solution

  • Use the imwrite function to create gif.

    numpoints = 500; 
    x = linspace(0,4*pi,numpoints); 
    y = square(x); 
    y2 = 3 +square(x+1);
    f = figure 
    h = animatedline('Color','b','LineWidth',2); 
    h2 = animatedline('Color','r','LineWidth',2);
    grid on;
    axis([0,12,-3,+6]) 
    for k = 1:numpoints 
      addpoints(h,x(k),y(k)) 
      addpoints(h2,x(k),y2(k)) 
      drawnow  
    
      % Capture the plot as an image 
      frame = getframe(f); 
      im = frame2im(frame); 
      [imind,cm] = rgb2ind(im,256); 
      % Write to the GIF File 
      if k == 1 
          imwrite(imind,cm,'test.gif','gif', 'Loopcount',inf); 
      else 
          imwrite(imind,cm,'test.gif','gif','WriteMode','append'); 
      end 
    end
    

    The gif is saved to the file called test.gif.