## Generate a signal that consists of a 0.2 Hz sinusoid embedded
## in white Gaussian noise and sampled five times a second for 200 seconds.
dt <- 1 / 5
t <- seq(0, 200 - dt, dt)
x <- 5 * sin(2 * pi * 0.2 * t) + rnorm(length(t))
## Use sgolay to smooth the signal.
## Use 21-sample frames and fourth order polynomials.
p <- 4
n <- 21
sg <- sgolay(p, n)
## Compute the steady-state portion of the signal by convolving it
## with the center row of b.
ycenter <- conv(x, sg[(n + 1)/2, ], 'valid')
## Compute the transients. Use the last rows of b for the startup
## and the first rows of b for the terminal.
ybegin <- sg[seq(nrow(sg), (n + 3) / 2, -1), ] %*% x[seq(n, 1, -1)]
yend <- sg[seq((n - 1)/2, 1, -1), ] %*%
x[seq(length(x), (length(x) - (n - 1)), -1)]
## Concatenate the transients and the steady-state portion to
## generate the complete smoothed signal.
## Plot the original signal and the Savitzky-Golay estimate.
y = c(ybegin, ycenter, yend)
plot(t, x, type = "l", xlab = "", ylab = "", ylim = c(-8, 10))
lines(t, y, col = 2)
legend("topright", c('Noisy Sinusoid','S-G smoothed sinusoid'),
lty = 1, col = c(1,2))
Run the code above in your browser using DataLab