Search code examples
matlabanimationplotgifmp4

How can I save a 3D animated line as a video or gif in MATLAB


I want to simulate the trajectory of a particle in 3d so I have created this small simulation using this code:

nP=100;
N=100;

z=rand(nP,N);
y=rand(nP,N);        % Compute coordinates of particles for each iteration NS
z=rand(nP,N);  
f = figure

view(3);
for i=N
    
    h = animatedline('MaximumNumPoints', 1.e4,'color',rand(1,3));
    for k = 1:length(x)
   
    addpoints(h,x(i,k),y(i,k),z(i,k));
    
    drawnow
   
   end
     
end
hold on
hold off


 numpoints = 500; 

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:N 
  addpoints(h,x(k),y(k),z(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

I am trying to save it either as a gif or mp4. It all works fine but in the end what is saved is tha trajectory of the particle in 2d. Any ideas of how I could make this work?


Solution

  • You have a mistake in a code:

    z=rand(nP,N);
    y=rand(nP,N); 
    z=rand(nP,N);
    

    Should be (see first line):

    x=rand(nP,N);
    y=rand(nP,N);        % Compute coordinates of particles for each iteration NS
    z=rand(nP,N);
    

    In the second part put view(3) before drawnow

    ...
    for k = 1:N 
      addpoints(h,x(k),y(k),z(k)) 
      %addpoints(h2,x(k),y2(k)) 
      view(3);
      drawnow  
    ...
    

    The full code, which works for me:

    nP=100;
    N=100;
    
    x=rand(nP,N);
    y=rand(nP,N);        % Compute coordinates of particles for each iteration NS
    z=rand(nP,N);  
    f = figure
    
    view(3);
    for i=N
        
        h = animatedline('MaximumNumPoints', 1.e4,'color',rand(1,3));
        for k = 1:length(x)
       
        addpoints(h,x(i,k),y(i,k),z(i,k));
        
        drawnow
       
       end
         
    end
    hold on
    hold off
    
    
     numpoints = 500; 
    
    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:N 
      addpoints(h,x(k),y(k),z(k)) 
      %addpoints(h2,x(k),y2(k)) 
      view(3);
      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
    

    UPDATE: Sorry, I have not noticed Luis Mendo comment.