Vectorized or Optimized Finite Low Pass Filter

6 views (last 30 days)
Alan on 8 Jul 2014
Commented: Alan on 9 Jul 2014
Let me start out with I do not have the signal processing toolbox. A simple low pass filter function should be easy. Indeed, "brute force" it is, I have the following code for filtering a timeseries:
function tsy = dlpf( tsx, lpff )
%dlpf - discrete low pass filter
% Outputs a low pass filtered timeseries when a timeseries and frequency
% are entered
tslen = length(tsx.time);
tau = 1/(2*pi*lpff);
%Line by line version
%This is more accurate, but much slower
disp = '';
tsy = tsx;
for n = 2:tslen
dt = tsx.time(n) - tsx.time(n-1);
alpha = dt/(tau+dt);,:) = alpha*,:) + (1-alpha)*,:);
But, I feel like I've given up whenever I use a for loop in MATLAB. I have timeseries data with over 400000 entries and as with any for loop in MATLAB, this is VERY slow. I want to make a "fast" version that's vectorized, or at least optimized in some way. The problem is, I don't think the equation:
y[i] = a*x[i] + (1-a) * y[i-1]
can be vectorized since the series y appears on both sides of the equation. If I did vectorize, it would look something like this:
%Vectorized version
%For speed, this takes an average dt, which will work if the timeseries
%is more or less uniform.
%For a very nonuniform timeseries, a line by line version would be
dt = mean(tsx.time(2:tslen)-tsx.time(1:tslen-1));
alpha = dt/(tau+dt);
tsy = tsx = (1-alpha)*,:) + alpha*
I fear that the series on the right will not contain the correct values, as they would be updated with each iteration through the series. I don't know how MATLAB would handle this in the background. Would this do what I want, or does anyone know of a better way to do this?
  1 Comment
Alan on 8 Jul 2014
I just ran both sets of code. The vectorized version ran much faster (seconds), of course, but I believe my suspicions that it won't work were true. The result is not the same and does not appear to be an effective filter. It has much more noise than the for loop version. I suspect it's essentially the same as if I used (1-alpha)*,:) which is not the same as the equation I'm trying to achieve.

Sign in to comment.

Accepted Answer

Honglei Chen
Honglei Chen on 8 Jul 2014
Edited: Honglei Chen on 9 Jul 2014
If your signal is uniformly spaced, and if I understand correctly, your alpha can be pre-determined, then this can be done via
y = filter([1 alpha-1],alpha,x)
Alan on 9 Jul 2014
It works. Sorry, I was not comparing the right graphs. Thank You very much! I marked it as accepted.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!