微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 MATLAB 中将 3D 动画线保存为视频或 gif

如何解决如何在 MATLAB 中将 3D 动画线保存为视频或 gif

我想在 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,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',2);
grid on;
%axis([0,12,-3,+6]) 
for k = 1:N 
  addpoints(h,x(k),y(k),z(k)) 
  %addpoints(h2,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,'WriteMode','append'); 
  end 
end

我正在尝试将其保存为 gif 或 mp4。一切正常,但最终保存的是 2d 中粒子的轨迹。关于我如何使这项工作有任何想法?

解决方法

您的代码有误:

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

应该是(见第一行):

x=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,y2(k)) 
  view(3);
  drawnow  
...

对我有用的完整代码:

nP=100;
N=100;

x=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,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',2);
grid on;
%axis([0,12,-3,+6]) 
for k = 1:N 
  addpoints(h,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,'WriteMode','append'); 
  end 
end

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。