在Matlab中分離初始化和顯示圖的正確方法是什么?(我的意思是廣義上的繪圖plot;可以是、plot3等scatter。)舉個具體的例子,我有一個非常復雜的 3D 可視化,它使用sphere和mesh繪制靜態球體網格,然后scatter3在球體上繪制移動軌跡。為了能夠實時執行此操作,我實施了一些簡單的優化,例如僅在scatter3每幀更新物件。但是代碼有點亂,很難添加我想要的附加功能,所以我想改進代碼分離。

我也覺得有時從函式回傳某種繪圖物件而不顯示它可能很有用,例如以一種很好的模塊化方式將它與其他繪圖結合起來。
我想到的一個例子是這樣的:
function frames = spherePlot(solution, options)
% Initialize sphere mesh and scatter objects, configure properties.
...
% Configure axes, maybe figure as well.
...
% Draw sphere.
...
if options.display
% Display figure.
end
for step = 1:solution.length
% Update scatter object, redraw, save frame.
% The frames are saved for use with 'movie' or 'VideoWriter'.
end
end
每個步驟也可以作為一個函式分離出來。
那么,做這樣的事情的一種簡潔而正確的方法是什么?所有檔案似乎都假設人們想要立即顯示所有內容。
uj5u.com熱心網友回復:
例如
% some sample data
N = 100;
phi = linspace(-pi, pi, N);
theta = linspace(-pi, pi, N);
f = @(phi, theta) [sin(phi).*cos(theta); sin(phi).*sin(theta); cos(phi)];
data = f(phi, theta);
% init plot
figure(1); clf
plot3(data(1,:), data(2,:), data(3,:)); % plot path, not updated
hold on
p = plot3([0 data(1,1)], [0 data(2,1)], [0 data(3,1)]); % save handle to graphics objects to update
s = scatter3(data(1,1), data(2,1), data(3,1), 'filled');
axis equal
xlabel('x'); ylabel('y'); zlabel('z');
t = title('first frame'); % also store handle for title or labels to update during animation
% now animate the figure
for k = 1:N
p.XData = [0 data(1,k)]; % update line data
p.YData = [0 data(2,k)];
p.ZData = [0 data(3,k)];
s.XData = data(1,k); % update scatter data
s.YData = data(2,k);
s.ZData = data(3,k);
t.String = sprintf('frame %i', k); % update title
drawnow % update figure
end
基本上,您可以更新圖形句柄的所有值,在本例中為“p”和“s”。如果您打開 matlab 檔案,plot您plot3將找到指向該原語所有屬性的鏈接:例如Line Properties。scatter/imagesc等存在類似的檔案頁面。
所以一般的想法是首先創建一個帶有第一幀的圖形,將句柄保存到您要更新的物件(p = plot(...),然后進入一個回圈,在其中更新該圖形物件的所需屬性(例如p.Color = 'r',或p.XData = ...) .
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/475417.html
上一篇:復制游標當前行的快捷方式是什么?
