随着for的继续,有没有办法更新图例



我一直在思考如何在Matlab中更新我的绘图图例,因为for正在进行,基本上,我有一个for,它创建了一个在每次迭代中添加到plot(使用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。我有一种感觉,有一种更好、更具表现力的方法可以做到这一点,但我不知道该如何解决这个问题。

plot函数中使用DisplayName,并在legend中切换AutoUpdate。这是我对你的for循环的尝试:

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

一个改进是更新图例的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

顺便说一句,说到性能,您可能希望用clear替换clear all;请参阅相关链接:1、2、3。

相关内容

最新更新