# for loop output is wrong

2 views (last 30 days)
Athira T Das on 6 Jul 2022
I am trying to find the value of But the answer of my loop is not same as numerically evaluated value. And the code is
clc; clear all; close all;
syms z m1 m2 s1 s2 j1 j2
X =0;
lambda = 1060*10^-9;
wo = 0.02;
C = 10^(-7);
k=2*pi/lambda
k = 5.9275e+06
b=0.1;
z=1
z = 1
T1=0;
T2=0;
T3=0;
T4=0;
T5=0;
T6=0;
M=1;
po=(0.545*C^2*k^2*z)^(-(3/5));
delta= ((1i*k)/(2*z));
for m1 =0:M
for m2=0:M
for s1=0:m1/2
for j1=0:m1-2*s1
for s2=0:(M-m1)/2
for j2=0:(M-m1-2*s2)
T6=T6+(1/(po^2))^j2;
end
T5=T5+T6*((2*1i)/(delta^(0.5)))^(M-m1-2*s2);
end
T4=T4+T5*(1/(po^2))^j1;
end
T3=T3+T4*((2*1i)/(delta^(0.5)))^(m1-2*s1);
end
T2=T2+T3*(factorial(M)/(factorial(m2)*factorial(M-m2)));
end
T1=T1+T2*(factorial(M)/(factorial(m1)*factorial(M-m1)));
end
X=T1
X = 0.0439 + 0.0439i

Abolfazl Chaman Motlagh on 6 Jul 2022
you are adding previous calculated numbers in nested loops. you should set T2,T3,... and T6 to zero before counting them for next step if you don't want to double count them. like this :
for m1 =0:M
T2=0;
for m2=0:M
T3=0;
for s1=0:m1/2
T4=0
for j1=0:m1-2*s1
T5=0
for s2=0:(M-m1)/2
T6=0;
for j2=0:(M-m1-2*s2)
T6=T6+(1/(po^2))^j2;
end
T5=T5+T6*((2*1i)/(delta^(0.5)))^(M-m1-2*s2);
end
T4=T4+T5*(1/(po^2))^j1;
end
T3=T3+T4*((2*1i)/(delta^(0.5)))^(m1-2*s1);
end
T2=T2+T3*(factorial(M)/(factorial(m2)*factorial(M-m2)));
end
T1=T1+T2*(factorial(M)/(factorial(m1)*factorial(M-m1)));
end
if you have problem undestanding why, just look at T6 and think why you should set it to zero in every new T5 loop. the rest is similar.