【问题标题】:How can I save a 3D animated line as a video or gif in MATLAB如何在 MATLAB 中将 3D 动画线保存为视频或 gif
【发布时间】:2021-04-25 09:00:57
【问题描述】:

我想在 3d 中模拟粒子的轨迹,所以我使用以下代码创建了这个小模拟:

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

我正在尝试将其保存为 gif 或 mp4。一切正常,但最终保存的是粒子在 2d 中的轨迹。有什么想法可以让我完成这项工作吗?

【问题讨论】:

  • 第一行z=... 应该是x=...。为什么有两个数字?第二个不应该有view(3)吗?这似乎解决了问题

标签: matlab animation plot gif mp4


【解决方案1】:

你的代码有错误:

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

应该是(见第一行):

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

在第二部分中,将view(3) 放在drawnow 之前

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

适合我的完整代码:

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

更新:抱歉,我没有注意到 Luis Mendo 的评论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-27
    • 2018-11-13
    • 2016-01-07
    • 2019-12-03
    • 2015-12-03
    • 2021-06-24
    • 2014-04-19
    • 1970-01-01
    相关资源
    最近更新 更多