How to plot loop items on legend

조회 수: 1 (최근 30일)
Joshua Tshuma
Joshua Tshuma 2022년 4월 4일
댓글: Voss 2022년 4월 5일
Hi,
I've got a loop that uses values in a list (fRat) in each iteration. The output of the code is as expected, but I want to make sure the legend shows me which curve corresponed to which iteration value in the list. So far it's only giving me the last list item value i.e., 0.3.
I've attached the code.
Also, if i move the %plotting block from where it is now, it'll again only output one curve - the last one.
I look forward to your advice and/or feedback.
Thanks.
%range
x = 50:1000;
TL = zeros(length(x), 1); % memory pre-allocation
for fRat = [0.1, 0.15, 0.3] %list
for j = 1:length(x)
%code
%TL - desired output function
end
%plotting
y = real(TL);
semilogx(x, y)
hold on
legend(strcat('p=', num2str(fRat)))
xlabel("Frequency (Hz)")
ylabel("Transmission loss (dB)")
end

채택된 답변

Voss
Voss 2022년 4월 4일
%range
x = 50:1000;
TL = zeros(length(x), 1); % memory pre-allocation
fRat_all = [0.1, 0.15, 0.3];
% pre-allocate line handles:
h_line = zeros(1,numel(fRat_all));
for ii = 1:numel(fRat_all) %list
fRat = fRat_all(ii);
for j = 1:length(x)
%code
%TL - desired output function
TL(j) = ii+0.25; % some different TL values, so the lines are different
end
%plotting
y = real(TL);
% store this line as h_line(ii):
h_line(ii) = semilogx(x, y);
hold on
end
legend(h_line,sprintfc('p=%.2f',fRat_all)); % use all lines and all fRat values in legend
xlabel("Frequency (Hz)")
ylabel("Transmission loss (dB)")
  댓글 수: 2
Joshua Tshuma
Joshua Tshuma 2022년 4월 5일
Awesome. Works perfectly. Thank you
Voss
Voss 2022년 4월 5일
You're welcome!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by