When using for loops to generate multiple graphs on the same plot, how do I update the legend also using the for loop?
3 views (last 30 days)
Show older comments
Jonezed1
on 23 May 2019
Commented: Lorenzo Mattera
on 11 Aug 2022
I am trying to display multiple curves on a singular plot, and I understand for loops as the best way to do this... however if I want a legend to represent each of the curves, I am unable to complete this command inside the loop...can someone help me?
figure(1)
hold on;
for kk = 1:17
scatter(stiffnesses(kk,:),Pt_LIRL_vect_wmr(kk,:));
legend(strcat('mr = ', num2str(mass_ratio_vals(kk))));
end
I want to graph 17 different data sets/scatters on the one plot (a 17x1000 probability matrix called 'Pt_LIRL_vect_wmr' against another 7x1000 matrix called 'stiffnesses'), and this is coming up fine.
It is the legend command that is not working. As can be seen, I am using num2str to write the legend, based off a pre-defined vector called 'mass_ratio_vals', where mass_ratio_vals = .4:.1:2.
The compiler however is only displaying the final value in mass_ratio_vals, i.e. 'mr = 2' as the only entry in the legend.
Can a loop be used to create a legend in this way?
Thank you!
0 Comments
Accepted Answer
Alex Mcaulley
on 23 May 2019
You need to call legend function just one time outside the loop
figure(1)
hold on;
names = cell(1,17);
for kk = 1:17
scatter(stiffnesses(kk,:),Pt_LIRL_vect_wmr(kk,:));
names{kk} = strcat('mr = ', num2str(mass_ratio_vals(kk)));
end
legend(names)
2 Comments
Lorenzo Mattera
on 11 Aug 2022
Any way to show and upgrade the legend inside the loop?
I am running a very long loop (50000 iterations with a time stop of the order of 1 sec at each iteration) and I would like to see the legend before the end of all iterations)
Thanks
More Answers (0)
See Also
Categories
Find more on Legend in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!