bf <- butter(3, 0.1) # 10 Hz low-pass filter
t <- seq(0, 1, len = 100) # 1 second sample
x <- sin(2* pi * t * 2.3) + 0.25 * rnorm(length(t)) # 2.3 Hz sinusoid+noise
z <- filter(bf, x) # apply filter
plot(t, x, type = "l")
lines(t, z, col = "red")
## specify initial conditions
## from Python scipy.signal.lfilter() documentation
t <- seq(-1, 1, length.out = 201)
x <- (sin(2 * pi * 0.75 * t * (1 - t) + 2.1)
+ 0.1 * sin(2 * pi * 1.25 * t + 1)
+ 0.18 * cos(2 * pi * 3.85 * t))
h <- butter(3, 0.05)
lab <- max(length(h$b), length(h$a)) - 1
zi <- filtic(h$b, h$a, rep(1, lab), rep(1, lab))
z1 <- filter(h, x)
z2 <- filter(h, x, zi * x[1])
plot(t, x, type = "l")
lines(t, z1, col = "red")
lines(t, z2$y, col = "green")
legend("bottomright", legend = c("Original signal",
"Filtered without initial conditions",
"Filtered with initial conditions"),
lty = 1, col = c("black", "red", "green"))
Run the code above in your browser using DataLab