How to use previously calculated value in next iteration
7 次查看(过去 30 天)
显示 更早的评论
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
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
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
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!