how do i get the difference between two successive values in while loop?

조회 수: 3 (최근 30일)
Deen Halis
Deen Halis 2016년 11월 11일
답변: Manikanta Aditya 2022년 6월 20일
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

답변 (1개)

Manikanta Aditya
Manikanta Aditya 2022년 6월 20일
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).

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by