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

답변 (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 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