Is there a way to update the legend as the for goes on?

51 views (last 30 days)
I've been thinking how I could update in Matlab the legend of my plots as the for goes on, basically, I have a for which creates a graph that is added to the plot (using hold on) in every iteration, I'd like to update the legend of the aforementioned plot. This is how I've done it:
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
i.e. using that size-changing string str. I have a feeling that there is a better and more performant way of doing this but I don't know how else to approach the problem.

Answers (2)

Star Strider
Star Strider on 2 Apr 2022
See the legend documentation section on Specify Legend Labels During Plotting Commands for one possible approach
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, 'DisplayName',sprintf("g = %d", g(i)))
axis([0, 2, -200, 10]);
legend(str, 'Location','southwest');
pause(0.3);
end
hold off
.

Voss
Voss on 2 Apr 2022
You can create the entire string array str before the loop, and use the first i elements of str in the legend each time through the loop.
Also (not related to the legend) you can avoid setting the axes limits every time and just do it once before the loop.
x0 = 10;
t = linspace(0, 2, 100);
v0 = 0;
g = [10:10:100];
str = "g = " + string(g);
hold on
axis([0, 2, -200, 10]);
for i = 1:length(g)
x = x0 + v0*t - 1/2*g(i)*t.^2;
v = v0 - g(i)*t;
plot(t, x)
legend(str(1:i), 'Location','southwest');
pause(0.3);
end
hold off

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!