Good evening
In the following code, I am having 8 plots at the end, for one distance value I have two plots. One for LoS path, the other for NLoS path.But all in one figure. I tried to put a legend but it gives me an error. What is the correct syntax to do it?
thank you
for k=1:length(R)
[HL,HN] = Channel_LoS(p,R(k),dt(k),dr(k));
plot(p.f,HL)
hold on
plot(p.f,HN)
end
hold off

Réponses (1)

Adam Danz
Adam Danz le 27 Oct 2018

0 votes

What code did you use to produce your legend and what was the error? Do you want a legend for each subplot or 1 legend for the whole figure? There's lots of ways to go about this depending on what you're looking for. Here's a general solution that can be adapted to your needs.
for k=1:length(R)
[HL,HN] = Channel_LoS(p,R(k),dt(k),dr(k));
p1 = plot(p.f,HL);
hold on
p2 = plot(p.f,HN);
end
legend([p1,p2], {'HL', 'HN'})
hold off
Another solution I often prefer is using the 'DisplayName' property.
for k=1:length(R)
[HL,HN] = Channel_LoS(p,R(k),dt(k),dr(k));
p1 = plot(p.f,HL, 'DisplayName', 'HL');
hold on
p2 = plot(p.f,HN, 'DisplayName', 'HN');
end
legend([p1,p2])
hold off

4 commentaires

Alice Faisal
Alice Faisal le 27 Oct 2018
I tried this
for k=1:length(R)
[HL,HN] = Channel_LoS(p,R(k),dt(k),dr(k));
p1=plot(p.f,HL);
hold on
p2=plot(p.f,HN);
legendInfo{k} = ['LoS, d=' R(k) , 'NLoS, d=' R(k)];
end
legend(legendInfo)
hold off
but it is not displaying R(n), the numbers in the legend
Adam Danz
Adam Danz le 27 Oct 2018
If R is a numerical vector, it will not appear in legendInfo unless you convert it to a character vector or string. Try something like this:
legendInfo{k} = sprintf('LoS, d=%d, NLoS, d=%d', R(k), R(k));
That assumes R(k) is an integer. If R(k) contains decimals, instead of %d, use %.2f (or whatever precision you want).
Alice Faisal
Alice Faisal le 28 Oct 2018
I don't think its right. I think this way will just list them as you wrote without connecting them to the actual curve. This is what I understood from debugging the plot.
Adam Danz
Adam Danz le 28 Oct 2018
Your line of code
legendInfo{k} = ['LoS, d=' R(k) , 'NLoS, d=' R(k)];
is incorrect because the numerical values are not converted to strings.
My line of code
legendInfo{k} = sprintf('LoS, d=%d, NLoS, d=%d', R(k), R(k));
correctly converts the numerical values to strings. However, you still need to use the plot handles to correctly pair the plot elements with the legend text. Look at my answer again and you'll see how I use the plot handles in the legend. You can also play around with the sprintf command to suit your needs. Let me know if you have any follow-up questions.

Connectez-vous pour commenter.

Commenté :

le 28 Oct 2018

Community Treasure Hunt

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

Start Hunting!

Translated by