% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sgolay.R
\name{sgolay}
\alias{sgolay}
\title{Savitzky-Golay filter design}
\usage{
sgolay(p, n, m = 0, ts = 1)
}
\arguments{
\item{p}{Polynomial filter order; must be smaller than \code{n}.}

\item{n}{Filter length; must a an odd positive integer.}

\item{m}{Return the m-th derivative of the filter coefficients. Default: 0}

\item{ts}{Scaling factor. Default: 1}
}
\value{
An square matrix with dimensions \code{length(n)} that is of class
  \code{"sgolayFilter"}, so it can be used with \code{filter}.
}
\description{
Compute the filter coefficients for all Savitzky-Golay FIR smoothing filters.
}
\details{
The early rows of the resulting filter smooth based on future values and
later rows smooth based on past values, with the middle row using half future
and half past.  In particular, you can use row \code{i} to estimate
\code{x(k)} based on the \code{i-1} preceding values and the \code{n-i}
following values of \code{x} values as \code{y(k) = F[i, ] *
x[(k - i + 1):(k + n -i)]}.

Normally, you would apply the first \code{(n-1)/2} rows to the first \code{k}
points of the vector, the last \code{k} rows to the last \code{k} points of
the vector and middle row to the remainder, but for example if you were
running on a real-time system where you wanted to smooth based on the all the
data collected up to the current time, with a lag of five samples, you could
apply just the filter on row \code{n - 5} to your window of length \code{n}
each time you added a new sample.
}
\examples{
## 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))

}
\seealso{
\code{\link{sgolayfilt}}
}
\author{
Paul Kienzle \email{pkienzle@users.sf.net},\cr
 Pascal Dupuis, \email{Pascal.Dupuis@esat.kuleuven.ac.be}.\cr
 Conversion to R Tom Short,\cr
 adapted by Geert van Boxtel \email{G.J.M.vanBoxtel@gmail.com}.
}
