有没有办法随着福音的开启而更新传奇?
我一直在思考如何在MATLAB中更新我的图的传奇,因为for继续进行,基本上,我有一个 的,它创建了一个图形,该图被添加到
plot (使用
保留
)在每次迭代中,我都想更新上述图的传说。
这就是我这样做的方式:
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
IE使用那种变化的字符串 str 。我觉得有一种更好,更具性能的方法来做到这一点,但我不知道该如何解决问题。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
plot
函数中使用DisplayName
,并在legend
中切换AutoUpdate
。这是我对你的 for 循环的尝试:Use
DisplayName
in theplot
function, and toggleAutoUpdate
inlegend
. This is my attempt of your for-loop:一个改进将是 update
字符串
传说的属性,而不是创建每个迭代中的新传说。对于随着时间变化而导致执行更快的图形对象,这种“更新而不是重新创建”的想法是常见的实践。在您的示例代码中,这几乎不会产生任何影响,但是它看起来仍然是一种更清洁的方法:或者,您可以避免存储
str
,并直接将新部分附加到图例上。同样,这样做的主要原因是代码可以说是更干净的,因为您避免在两个位置保留相同的信息(变量和图形对象):作为旁注,说到性能,您可能需要替换
通过
清除所有 clear ;请参阅相关链接: 2 , 3 。An improvement would be to update the
String
property of the legend, instead of creating a new legend in each iteration. This "update instead of re-create" idea is common practice for graphical objects that change with time, and results in faster execution. In your example code this will hardly have any impact, but it still looks like a cleaner approach:Alternatively, you can avoid storing
str
, and directly append the new part to the legend. Again, the main reason for this is that the code arguably looks cleaner, as you avoid keeping the same information in two places (the variable and the graphical object):As a side note, speaking of performance, you may want to replace
clear all
byclear
; see relevant links: 1, 2, 3.