\Header{convolve}{Fast Convolution}
\keyword{math}{convolve}
\keyword{dplot}{convolve}
\begin{Usage}
\begin{verbatim}
convolve(x, y, conj = TRUE, type = c("circular", "open", "filter"))
\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\texttt{x,y}] numeric sequences \emph{of the same length} to be convolved.
\item[\texttt{conj}] logical; if \texttt{TRUE}, take the complex \emph{conjugate}
before back-transforming (default, and used for usual convolution).
\item[\texttt{type}] character; one of \texttt{"circular"}, \texttt{"open"},
\texttt{"filter"} (beginning of word is ok).
For \texttt{circular}, the two sequences are treated as
\emph{circular}, i.e., periodic.

For \texttt{open} and \texttt{filter}, the sequences are padded with
\texttt{0}s (from left and right) first;
\texttt{"filter"} returns a the middle sub-vector of \texttt{"open"},
namely, the result of running a weighted mean of \texttt{x} with
weights \texttt{y}.
\end{ldescription}
\end{Arguments}
\begin{Description}
Use the Fast Fourier Transform to compute the
several kinds of convolutions of two sequences.\end{Description}
\begin{Details}
The Fast Fourier Transform, \texttt{\Link{fft}}, is used for efficiency.

The input sequences \texttt{x} and  \texttt{y} must have the same length if
\texttt{circular = TRUE}).\end{Details}
\begin{Value}
If \texttt{r <- convolve(x,y, conj=TRUE, type)}
and \texttt{n <- length(x)}, then
\deqn{r_k = \sum_{i=1}^n x_i y_{k-i}}{r[k] = sum(i=1,..,n;  x[i] * y[k-i])}
for \eqn{k = 1,\dots,n}{}.

If \texttt{type == "circular"}, then
\eqn{y_{j} = y_{n+j}}{y[j] == y[n+j]} for \eqn{j < 0}{}.\end{Value}
\begin{References}
Brillinger, D. R. (1981).
\emph{Time Series: Data Analysis and Theory}, Second Edition.
San Francisco: Holden-Day.\end{References}
\begin{SeeAlso}
\texttt{\Link{fft}}, \texttt{\Link{nextn}}.\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
x <- c(0,0,0,100,0,0,0)
y <- c(0,0,1, 2 ,1,0,0)/4
zapsmall(convolve(x,y))		#  *NOT* what you first thought..
zapsmall(convolve(x, y[3:5], type="f")) # rather
x <- rnorm(50);y <- rnorm(50)
all(convolve(x,y), convolve(y,x))
all(convolve(x,y, conj = FALSE), rev(convolve(y,x)))

n <- length(x <- -20:24)
y <- (x-10)^2/1000 + rnorm(x)/8

Han <- function(y) # Hanning
       convolve(y, c(1,2,1)/4, type = "filter")

plot(x,y, main="Using  convolve(.) for Hanning filters")
lines(x[-c(1  , n)      ], Han(y), col="red")
lines(x[-c(1:2, (n-1):n)], Han(Han(y)), lwd=2, col="dark blue")
\end{ExampleCode}
\end{Examples}

