using for loop with syms
2 次查看(过去 30 天)
显示 更早的评论
Hello,
I would like to use for loop with syms,
So there a variable lam with which phi1 and phi2 will change and so do matrix M, now I want to use different M elements of each iteration in z. Can anyone help me in using For loop here?
syms n0 n1 n2 ns phi1 phi2
n0 = 1;
n1 = 2;
n2 = 1;
n3 = 2;
d1 = 0.1;
d2 = 0.2;
lam = 3:1:7;
th = 0;
phi1 =(d1./lam).*sqrt((n1));
phi2 = (d2./lam).*sqrt((n2));
for j = 1:length(lam)
D0 = [2 2; n0 -n0];
D1 = [2 2;n1 -n1];
D2 = [2 2; n2 -n2];
D3 = [2 2;n3 -n3];
P1 = [exp(-1i.*phi1) 1; 1 exp(1i.*phi1)];
P2 = [exp(-1i*phi2) 1; 1 exp(1i*phi2)];
M = D0*([D1*P1*D2*P2]^(2))*D3;
Msubs = subs(M);
Mvalue = double(Msubs);
z = M(2,2)./M(1,1);
end
1 个评论
Askic V
2023-4-19
编辑:Askic V
2023-4-19
Hi Ashi,
first of all this line will produce an error:
% M = D0*([D1*P1*D2*P2]^(2))*D3;
Executing the whole script:
syms n0 n1 n2 ns phi1 phi2
n0 = 1;
n1 = 2;
n2 = 1;
n3 = 2;
d1 = 0.1;
d2 = 0.2;
lam = 3:1:7;
th = 0;
phi1 =(d1./lam).*sqrt((n1));
phi2 = (d2./lam).*sqrt((n2));
for j = 1:length(lam)
D0 = [2 2; n0 -n0];
D1 = [2 2;n1 -n1];
D2 = [2 2; n2 -n2];
D3 = [2 2;n3 -n3];
P1 = [exp(-1i.*phi1) 1; 1 exp(1i.*phi1)];
P2 = [exp(-1i*phi2) 1; 1 exp(1i*phi2)];
M = D0*([D1*P1*D2*P2]^(2))*D3;
Msubs = subs(M);
Mvalue = double(Msubs);
z = M(2,2)./M(1,1);
end
This is because D1*P1 is a matrix with dimensions 2x6, and D2 is a matrix of dimensions 2x2.
How Matrix M shuld look like? What is your intention here?
Just to be able to execute the line properly, you can do something like this:
M = D0*([D1*P1*(D2*P2)']^(2))*D3;
回答(1 个)
Walter Roberson
2023-4-19
syms n0 n1 n2 ns phi1 phi2
n0 = 1;
n1 = 2;
n2 = 1;
n3 = 2;
d1 = 0.1;
d2 = 0.2;
lam = 3:1:7;
th = 0;
phi1 =(d1./lam).*sqrt((n1));
phi2 = (d2./lam).*sqrt((n2));
for j = 1:length(lam)
D0 = [2 2; n0 -n0];
D1 = [2 2;n1 -n1];
D2 = [2 2; n2 -n2];
D3 = [2 2;n3 -n3];
P1 = [exp(-1i.*phi1(j)) 1; 1 exp(1i.*phi1(j))];
P2 = [exp(-1i*phi2(j)) 1; 1 exp(1i*phi2(j))];
M = D0*([D1*P1*D2*P2]^(2))*D3;
Msubs = subs(M);
Mvalue = double(Msubs);
z(j,1) = M(2,2)./M(1,1);
end
plot(lam, real(z), lam, imag(z));
legend({'real', 'imaginary'})
2 个评论
Dyuman Joshi
2023-4-19
I'm not sure why OP needs to use symbolic variables here
%syms n0 n1 n2 ns phi1 phi2
n0 = 1;
n1 = 2;
n2 = 1;
n3 = 2;
d1 = 0.1;
d2 = 0.2;
lam = 3:1:7;
th = 0;
phi1 =(d1./lam).*sqrt((n1));
phi2 = (d2./lam).*sqrt((n2));
z = zeros(size(lam));
for j = 1:numel(lam)
D0 = [2 2; n0 -n0];
D1 = [2 2;n1 -n1];
D2 = [2 2; n2 -n2];
D3 = [2 2;n3 -n3];
P1 = [exp(-1i.*phi1(j)) 1; 1 exp(1i.*phi1(j))];
P2 = [exp(-1i*phi2(j)) 1; 1 exp(1i*phi2(j))];
M = D0*([D1*P1*D2*P2]^(2))*D3;
z(j) = M(2,2)./M(1,1);
end
plot(lam, real(z), lam, imag(z));
legend({'real', 'imaginary'})
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!