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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by