how to filter without a for loop (first order filter)

조회 수: 7 (최근 30일)
Andrew Tilmouth
Andrew Tilmouth 2017년 12월 10일
편집: Jan 2018년 12월 8일
Hi for a large vector (361156 points or more) I have this for loop to filter engine speed (RPM), it works fine but it is too slow
for i=1:length(RPM)
RPMFilt(i) = RPM(i) + RPMFilt(i-1) - RPM(i) * RPMFiltConstant
end
where RPMFiltConstant = 0.98 (heavily filtered)
Too avoid the for loop, I guess that I could use the filter function y = filter(b,a,x) (only the matlab filter function, I don't have the DSP or signal processing tool boxes)
But the problem is I am not sure what I should set b and a to in order to achieve the same result as the equation above with 0.98 filter constant, can anyway explain and show how to calculate what b and a should be for different values of RPMFiltConstant between 0 and 1.
thanks
  댓글 수: 1
Jan
Jan 2017년 12월 10일
Your code does not run: What is RPMFilt(i-1) for i=1 ? Please post the real code, which runs and produces the wanted result.

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2017년 12월 10일
편집: Jan 2018년 12월 8일
Your code does not run: What is RPMFilt(i-1) for i=1 ? Please post the real code, which runs and produces the wanted result.
Do you pre-allocate the output?
RPM = rand(1, 361156);
RPMFiltConstant = 0.98;
tic;
RPMFilt = zeros(size(RPM));
RPMFilt(1) = RPM(1); % Or what else?
for i = 2:length(RPM)
RPMFilt(i) = RPM(i) + RPMFilt(i-1) - RPM(i) * RPMFiltConstant;
end
toc
This takes 0.026 sec on my R2016b/64/Win7 system. Not so much. This is a little bit faster:
tic;
b = 1 - RPMFiltConstant;
RPMFilt = zeros(size(RPM));
RPMFilt(1) = RPM(1); % Or what else?
for i = 2:length(RPM)
RPMFilt(i) = b * RPM(i) + RPMFilt(i-1);
end
toc
And with filter:
RPMFilt = [RPM(1), filter([0.02, 0], [1, -1], RPM(2:end), RPM(1))];
  댓글 수: 3
Lugi Marcato
Lugi Marcato 2018년 12월 8일
RPMFiltConstant is equal to Tsimpling/(Tsimpling+tau)?
what is [0.02, 0], [1, -1]?
Jan
Jan 2018년 12월 8일
편집: Jan 2018년 12월 8일
@Lugi: I do not knwo what Tsimpling and tau is.
[0.02, 0], [1, -1] are the filter parameters B and A, which perform the same calculations as the for loop, except for rounding errors:
RPM = rand(1, 361156);
RPMFiltConstant = 0.98;
R1 = zeros(size(RPM));
R1(1) = RPM(1); % Or what else?
for i = 2:length(RPM)
R1(i) = RPM(i) + R1(i-1) - RPM(i) * RPMFiltConstant;
end
R2 = [RPM(1), filter([1-RPMFiltConstant, 0], [1, -1], RPM(2:end), RPM(1))];
max(abs(R1 - R2) ./ abs(R2)) % Relative error: about 1.7763e-15

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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