Info

This question is closed. Reopen it to edit or answer.

Legend command in a for loop

1 view (last 30 days)
Giano Rugge
Giano Rugge on 31 Jan 2016
Closed: MATLAB Answer Bot on 20 Aug 2021
Hi everyone, I was trying to add a legend to series of plots in a for loop but I didn't manage to do this. That's my code:
i=-4:0.5:4
Param.beta=i;
...
if i<0
figure(1)
fplot(@(ST) p_cev(0.9,ST,Param),[0, 2]);
title(['CEV density, \beta<0'])
hold on
else
figure(2)
fplot(@(ST) p_cev(0.9,ST,Param),[0,2]);
title(['CEV density, \beta>=0'])
hold on
end
end
If I use the command
legend=['\beta=',num2str(i)]);
Matlab gives me back a legend in which only the last itemof the loop is represented. Do you have any suggestion to fix it? Thanks.
  1 Comment
Geoff Hayes
Geoff Hayes on 31 Jan 2016
Giano - please clarify where in the above code you are creating the legend. You initialized i as an array of beta values (?) but then create the legend as
legend(['beta=','num2str(i)]);
(which is slightly different from your call). Is i still an array or an scalar? (Note that MATLAB uses i and j to represent the imaginary number so you may want to rename this local variable to something else.)
Do you add a legend for both figures or just one?
When you call legend, you are adding a new legend to the figure so any previously created one (on a previous iteration if that is what is happening) won't be updated...the new one will just "take its place".
Please show more of your code so that we can see how you are invoking legend. You may just want to wait until all iterations have been completed and then create the legend and pass in a cell of strings (one string per plot).

Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!