我一直在考慮如何在 Matlab 中更新我的圖例,因為 for 繼續進行,基本上,我有一個for創建一個在每次迭代中添加到plot(using hold on) 的圖形,我想更新上述情節的傳說。這就是我的做法:
clear all; close all; clc;
x0 = 10;
t = linspace(0, 2, 100);
v0 = 0;
g = [10:10:100];
str = [];
hold on
for i = 1:length(g)
x = x0 v0*t - 1/2*g(i)*t.^2;
v = v0 - g(i)*t;
plot(t, x)
axis([0, 2, -200, 10]);
str = [str, sprintf("g = %d", g(i))];
legend(str, 'Location','southwest');
pause(0.3);
end
hold off
即使用那個改變大小的字串str。我有一種感覺,有一種更好、更高效的方法可以做到這一點,但我不知道如何解決這個問題。
uj5u.com熱心網友回復:
DisplayName在函式中使用,并在 中plot切換。這是我對你的 for 回圈的嘗試:AutoUpdatelegend
for i = 1:length(g)
x = x0 v0*t - 1/2*g(i)*t.^2;
v = v0 - g(i)*t;
plot(t, x,'DisplayName',sprintf("g = %d", g(i)));
axis([0, 2, -200, 10]);
% str = [str, sprintf("g = %d", g(i))];
% legend(str, 'Location','southwest');
legend('Location','southwest','AutoUpdate',1);
pause(0.3);
end
uj5u.com熱心網友回復:
一個改進是更新圖例的String屬性,而不是在每次迭代中創建一個新的圖例。這種“更新而不是重新創建”的想法是隨時間變化的圖形物件的常見做法,并導致更快的執行。在您的示例代碼中,這幾乎不會產生任何影響,但它看起來仍然是一種更清潔的方法:
clear all; close all; clc;
x0 = 10;
t = linspace(0, 2, 100);
v0 = 0;
g = [10:10:100];
str = [];
le = legend(str, 'Location','southwest'); %%% new: create empty legend
hold on
for i = 1:length(g)
x = x0 v0*t - 1/2*g(i)*t.^2;
v = v0 - g(i)*t;
plot(t, x)
axis([0, 2, -200, 10]);
str = [str, sprintf("g = %d", g(i))];
le.String = str; %%% changed: update String property of the legend
pause(0.3);
end
hold off
或者,您可以避免存盤str,并直接將新部分附加到圖例中。同樣,這樣做的主要原因是代碼看起來更干凈,因為您避免在兩個地方(變數和圖形物件)保留相同的資訊:
clear all; close all; clc;
x0 = 10;
t = linspace(0, 2, 100);
v0 = 0;
g = [10:10:100];
% str = []; %%% removed
le = legend(str, 'Location','southwest'); %%% new: create empty legend
hold on
for i = 1:length(g)
x = x0 v0*t - 1/2*g(i)*t.^2;
v = v0 - g(i)*t;
plot(t, x)
axis([0, 2, -200, 10]);
% str = [str, sprintf("g = %d", g(i))]; %%% removed
le.String = [le.String sprintf("g = %d", g(i))]; %%% changed: append new string
pause(0.5);
end
hold off
As a side note, speaking of performance, you may want to replace clear all by clear; see relevant links: 1, 2, 3.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/456637.html
上一篇:MatLab三角線性方程組
下一篇:如何將空陣列附加到元胞陣列
