When using for loops to generate multiple graphs on the same plot, how do I update the legend also using the for loop?

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!

 Réponse acceptée

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 commentaires

That is fantastic, thank you very much!
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

Connectez-vous pour commenter.

Plus de réponses (0)

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by