how do i get the difference between two successive values in while loop?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi all,
How do I find the difference between a previous value and a current value (‘u_dif’ in code) in a while loop? I get zero values in trying to get this and that affects my expected results.
Thanks
……
for i1 = r:numel(t)
t2 = ts*i1;
…….
err = 1;
i2 = 1
while err > 0.03;
i2 = i2 + 1;
fz = z0 - Znonlin(i1-1);
Fa(i1) = ts*fz.*sin(pp1*(t2)).*exp(n1*(t2));
FFa(i1) = FFa(i1-1)+Fa(i1);
Fb(i1) = ts*fz.*cos(pp1*(t2)).*exp(n1*(t2));
FFb(i1) = FFb(i1-1)+Fb(i1);
d1 = exp(-n1*t2).*sin(pp1*t2);
d2 = exp(-n1*t2).*cos(pp1*t2);
u(i2) = pp2*(FFb(i1).*(Bo.*d1) - FFa(i1).*(Bo.*d2));
Znonlin(i1)= zlin_a(1,i1) + u(i2);
u_new(i2) = u(i2);
u_old(i2)= u(i2-1);
u_dif(i2) = u_new(i2)- u_old(i2);%%why zeroes here?
err = u_dif(i2)/ u_new(i2);
end
Znonlin(i1)
end
0 comentarios
Respuestas (1)
Manikanta Aditya
el 20 de Jun. de 2022
Hi Deen,
The updated code:
……
for i1 = r:numel(t)
t2 = ts*i1;
…….
err = 1;
i2 = 0;
while err > 0.03
i2 = i2 + 1;
fz = z0 - Znonlin(i1-1);
Fa(i1) = ts*fz.sin(pp1(t2)).exp(n1(t2));
FFa(i1) = FFa(i1-1)+Fa(i1);
Fb(i1) = ts*fz.cos(pp1(t2)).exp(n1(t2));
FFb(i1) = FFb(i1-1)+Fb(i1);
d1 = exp(-n1*t2).*sin(pp1*t2);
d2 = exp(-n1*t2).*cos(pp1*t2);
u(i2) = pp2*(FFb(i1).(Bo.*d1) - FFa(i1).(Bo.*d2));
Znonlin(i1)= zlin_a(1,i1) + u(i2);
if i2 != 1
u_new = u(i2);
u_old = u(i2-1);
u_dif = u_new- u_old;
err = u_dif/ u_new;
end
Znonlin(i1)
End
As you are incrementing i2 at the beginning of the while loop, you have to initialize the value of i2 to 0. And since there is no error for the first element, we consider that condition and not calculate the error for u(1).
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!