How to use previously calculated value in next iteration

7 ビュー (過去 30 日間)
James
James 2012 年 7 月 20 日
コメント済み: shiv gaur 2022 年 3 月 6 日
I haven't used Matlab in some time - I'm slowly getting back in the groove.
I'm trying to run some raw data through a smoothing filter as shown below. I need each calculation in the for loop to use the previously calculated value (Tf) during the next iteration.
Tf(n)=5 %Initial value for Tf
for n=1:700000
Tf(n)=(1/32)*L(n)+(1-(1/32))*Tf(n); %filter
end
I also tried this:
Tfn(n)=5
for n=1:700000
Tf(n)=(1/32)*L(n)+(1-(1/32))*Tfn(n); %filter
Tfn(n)=Tf(n)
end
What am I doing wrong?
Thanks
EDIT:
I believe I figured it out. This seems to work.
Tfn(n)=5
for n=1:700000
Tf(n)=(1/32)*L(n)+(1-(1/32))*Tfn(n); %filter
Tfn(n+1)=Tf(n)
end
-James
  1 件のコメント
per isakson
per isakson 2012 年 7 月 21 日
Try:
Tf = filter( 1/32, [1,-31/32] , L, 5 );

サインインしてコメントする。

回答 (2 件)

Jan
Jan 2012 年 7 月 20 日
編集済み: Jan 2012 年 7 月 20 日
Tf(1)=5 %Initial value for Tf
for n=1:700000
Tf(n)=(1/32)*L(n)+(1-(1/32))*Tf(n-1); %filter
end
Note: This is more efficient due to less operations:
Tf(n) = (L(n) + 31 * Tf(n-1)) / 32; %filter
  1 件のコメント
Elizabeth
Elizabeth 2012 年 7 月 21 日
By using for n=1:700000 Tf(n)=(L(n)+31*Tf(n-1))/32; end At the first loop, Tf(n-1)=T(0) which will cause an error. Therefore, you have to initialize T(1) outside of the loop and use for n=2:700000

サインインしてコメントする。


Elizabeth
Elizabeth 2012 年 7 月 20 日
Something that may be more efficient for your code is:
Tfn(1)= 5 % initial value of Tfn
for 2:700000
Tfn(n)=(1/32)*L(n-1)+(1-(1/32))*Tfn(n-1); %filter
end
Tfn=Tfn(n)
  2 件のコメント
shiv gaur
shiv gaur 2022 年 3 月 6 日
this is your last problem you answer but value is not right
shiv gaur
shiv gaur 2022 年 3 月 6 日
sorry for answer this was not for this

サインインしてコメントする。

カテゴリ

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