Rumpl
Rumpl

Reputation: 343

apply butterworth filter to signal with varying frequencies

I am filtering a signal with a 240 Hz frequency using a 4th order low pass butterworth filter. Here's the filter setup code:

library(signal) 
fo <- 4                   # filter order
fs <- 240                 # signal frequency
fc10 <- 10                # cut-off frequency
w <- 2 * (fc10 / fs)      # critical frequency (Nyquist)
ft <- "low"               # type = low
 
bf <- butter(fo, w, type = ft)

I apply the filter to padded data (with reflection of the first and last elements) using this function:

pad_filt_unpad <- function(x, bf) {
  # pad data
  padded_data <- c(rep(first(x), fs), x, rep(last(x), fs))
  # filter data
  filtered_data <- filtfilt(bf, padded_data)
  # un-pad data
  filtered_data <- filtered_data[(fs + 1):(length(filtered_data) - fs)]
  return(filtered_data)
}

This works as expected.

Now, I have a new signal that varies between data coming in with a frequency of 60 Hz and 240 Hz (nothing in between, just switching between 60 or 240 Hz). My first idea was to quadruplicate all 60 Hz data and leave the filter as is, but that will probably lead to funny effects. So, what can I do? Any ideas would be much appreciated.

Upvotes: 2

Views: 171

Answers (1)

Pascal Getreuer
Pascal Getreuer

Reputation: 3256

You receive some data at 240 Hz sample rate and some data at 60 Hz sample rate, and in both cases you want to apply a lowpass filter with 10 Hz cutoff.

What you suggest of 4x replicating the 60 Hz sample rate data to 240 Hz, and then lowpass filtering, would work just fine. Sure, 4x replicating is crude, but whether using that or a more sophisticated interpolation would make little difference after the 10 Hz cutoff lowpass filter. The "funny effects" are smoothed away.

Or, instead of upsampling to 240 Hz, consider this other route: decimate to 60 Hz. That 10 Hz cutoff is so low that the final lowpassed result would be more than adequately represented with a 60 Hz sample rate. This may be simpler and cheaper to compute:

  1. Design the 10 Hz cutoff lowpass filter for 60 Hz sample rate.
  2. When given 240 Hz sample rate data, apply an anti-aliasing filter and then subsample by 4x to 60 Hz. The anti-aliasing can be as simple computing the average of each group of 4 consecutive samples.
  3. With all data at 60 Hz, apply the 10 Hz cutoff lowpass filter.

Upvotes: 1

Related Questions