Using variable legend in a for loop

조회 수: 1 (최근 30일)
Ashi Khajotia
Ashi Khajotia 2023년 5월 19일
댓글: Ashi Khajotia 2023년 5월 22일
Hii,
So while using variable legend code, the color of curves and that of legend are mismatching. And when y = 0, there is a colored line which is coming out of nowhhere. Can anybody be kind enough to help?
n0 = 1;
lam = 3:0.01:7;
a1 = 3.263;
b1 = 0.1644;
n1 = sqrt(1 + (a1.*(lam.^2))./((lam.^2) - (b1^2)));
ns = 1.5;
th = 0;
ii = 1;
for k = 3:1:7
d1 = k./(4*(2.06));
for j = 1:numel(lam)
phi1 =2*pi.*(d1./lam).*sqrt((n1).^2 - sind(th).^2);
D0 = [1 1; n0 -n0];
D_0 = inv(D0);
D1 = [1 1;n1(j) -n1(j)];
D_1 = inv(D1);
Ds = [1 1;ns -ns];
P1 = [exp(1i.*phi1(j)) 0; 0 exp(-1i.*phi1(j))];
M = D_0*D1*P1*D_1*Ds;
r(j,k) = M(2,1)./M(1,1);
R(j,k) = abs(r(j,k).^(2));
end
leg_str{ii} = ['k = ' num2str(k)];
ii = ii + 1;
plot(lam,R,LineWidth=2);
hold on;
end
legend(leg_str);

채택된 답변

VBBV
VBBV 2023년 5월 19일
편집: VBBV 2023년 5월 19일
n0 = 1;
lam = 3:0.01:7;
a1 = 3.263;
b1 = 0.1644;
n1 = sqrt(1 + (a1.*(lam.^2))./((lam.^2) - (b1^2)));
ns = 1.5;
th = 0;
ii = 1;
for k = 3:1:7
d1 = k./(4*(2.06));
for j = 1:numel(lam)
phi1 =2*pi.*(d1./lam).*sqrt((n1).^2 - sind(th).^2);
D0 = [1 1; n0 -n0];
D_0 = inv(D0);
D1 = [1 1;n1(j) -n1(j)];
D_1 = inv(D1);
Ds = [1 1;ns -ns];
P1 = [exp(1i.*phi1(j)) 0; 0 exp(-1i.*phi1(j))];
M = D_0*D1*P1*D_1*Ds;
r(j,k-2) = M(2,1)./M(1,1);
R(j,k-2) = abs(r(j,k-2).^(2));
end
leg_str{k-2} = ['k = ' num2str(k)];
plot(lam,R(:,k-2),LineWidth=2);
hold on;
end
legend(leg_str);
  댓글 수: 2
VBBV
VBBV 2023년 5월 19일
편집: VBBV 2023년 5월 19일
The below lines in your code needs a change, since for loop for the r(j,k) and R(j,k) matrices with index k begins at 3 and ends at 7. Matlab considers (computes) preceding elements i.e. 1 to 2 as zeros for those matrices.
So, when plotting the graph, it is treated as zeros, and corresponding legend is displayed for zeros.
r(j,k-2) = M(2,1)./M(1,1);
R(j,k-2) = abs(r(j,k-2).^(2));
Ashi Khajotia
Ashi Khajotia 2023년 5월 22일
thanks a lot for your help!!

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

추가 답변 (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