Using variable legend in a for loop

3 ビュー (過去 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 Center および File ExchangeLegend についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by