MATLAB: When using for loops to generate multiple graphs on the same plot, how to update the legend also using the for loop

for looplegendMATLABplotting

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 17×1000 probability matrix called 'Pt_LIRL_vect_wmr' against another 7×1000 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!

Best Answer

  • 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)