正確和有效的這樣做,這是與handle graphics。你也應該向量化你的plot
命令。
% Example data to make runnable
L = 1;
n = 10; % Number of points
P = 2*rand(1e2,n+1)-1;
% Initialize plot, first iteration
h = plot(P(1,1:n),P(1,2:n+1),'.'); % Plot first set of points and return handle
axis equal;
axis([-L L -L L]);
hold on; % Ensure axis properties are fixed
drawnow;
% Animate
for k = 2:size(P,1) % size is safer in this case
% Use handle to update the positions of the previously plotted points
set(h,{'XData','YData'},{P(k,1:n),P(k,2:n+1)});
drawnow;
pause(0.1); % Slow down animation a bit to make visible
end
上的動畫的每個迭代調用clf
和/或plot
導致許多次已經在內存中被不必要地刪除和重新分配,導致代碼慢得多。在某些情況下,它也可能導致閃爍。請參閱this very similar question and answer。
您可以在繪製之前刷新。試試'clf' –
謝謝!我嘗試了它,它只動畫了一個粒子:/ – DoubleOseven
它動畫了你畫的粒子數量!取決於你放在哪裏,當然。你需要把它放在'for i = 1:n'行之前。之後,寫一個「保持」。 –