Using variable legend in a for loop

2 次查看(过去 30 天)
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));

请先登录,再进行评论。

更多回答(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