# NOT RUN {
fs <- 1000
t <- seq(0, 1, 1/fs)
s <- sin(2* pi * t * 6)
x <- s + rnorm(length(t))
plot(t, x, type = "l", col="light gray")
lines(t, s, col="black")
sosg <- butter(3, 0.02, output = "Sos")
sos <- sosg$sos
sos[1, 1:3] <- sos[1, 1:3] * sosg$g
y <- sosfilt(matrix(sos, ncol=6), x)
lines(t, y, col="red")
## using 'filter' will handle the gain for you
y2 <- filter(sosg, x)
all.equal(y, y2)
## The following example is from Python scipy.signal.sosfilt
## It shows the instability that results from trying to do a
## 13th-order filter in a single stage (the numerical error
## pushes some poles outside of the unit circle)
arma <- ellip(13, 0.009, 80, 0.05, output='Arma')
sos <- ellip(13, 0.009, 80, 0.05, output='Sos')
x <- rep(0, 700); x[1] <- 1
y_arma <- filter(arma, x)
y_sos <- filter(sos, x)
plot(y_arma, type ="l")
lines (y_sos, col = 2)
legend("topleft", legend = c("Arma", "Sos"), lty = 1, col = 1:2)
# }
Run the code above in your browser using DataLab