How to create a legend for a variable used as for loop iteration?
67 views (last 30 days)
Show older comments
Greetings,
I am looking for a simple way to create a legend that defines a key for every loop iteration of a variable that is used as a for loop instrumentation. Is it even possible to call the loop iteration values without assigning them to an array?
For example, I want to display a variable called SNR and have it automatically increment its value corresponding to its iterations. The legend would look something like this:
-- SNR = 0
-+ SNR = 1
== SNR = 2
... and so on
I saw some previous solutions for this, but can it be done simply without an additional for loop and within 10 lines of code like this?
for SNR = 0:10
% body
end
figure
plot(x,y)
legend('SNR =',num2str(SNR),...'location','Best');
0 Comments
Answers (3)
Jayanth Reddy Regatti
on 11 Sep 2016
Edited: Jayanth Reddy Regatti
on 11 Sep 2016
If this question is still not solved, here is one work around. Declare your Snr values in a column vector Pr.
legend(strcat('p=',num2str(Pr')))
This works if you are plotting all the curves at a go.
1 Comment
Marina Ramos Cuevas
on 11 May 2020
Thank you very much! This one actually solved my problem on how not to overwrite the legend fields every time I had to perform a loop operation with a plot inside and I could access the plot 'Display Name' tag itself. Really useful!
Chad Greene
on 6 Aug 2014
Edited: Chad Greene
on 6 Aug 2014
x = 1:.1:3;
y = sin(x);
plot(x,y,'linewidth',2);
hold on;
legend('sin(x)')
colors = jet(10);
for n = 1:10
s = rand;
plot(x,y+s,'color',colors(n,:))
legappend(['sin(x)+',num2str(s)])
end
Azzi Abdelmalek
on 17 Jul 2014
To concatenate a string with a number
number=10
out=sprintf('SNR%d',number)
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!