This function recursively updates a covariance matrix without entirely recomputing it when new observations arrive.
Usage
updateCovariance(C, x, n, xbar, f, byrow = TRUE)
Arguments
C
covariance matrix.
x
vector/matrix of new data.
n
sample size before observing x.
xbar
mean vector before observing x.
f
forgetting factor: a number beween 0 and 1.
byrow
Are the observation vectors in x stored in rows?
Details
The forgetting factor f determines the balance between past and present observations in the PCA update: the closer it is to 1 (resp. to 0), the more weight is placed on current (resp. past) observations. At least one of the arguments n and f must be specified. If f is specified, its value overrides the argument n. The default f=1/n corresponds to a stationnary observation process.
The argument byrow should be set to TRUE (default value) if the data vectors in x are stored in rows and to FALSE if they are stored in columns. The function automatically handles the case where x is a single vector.
Value
The updated covariance matrix.
See Also
updateMean
Examples
n <- 1e4
n0 <- 5e3
d <- 10
x <- matrix(runif(n*d), n, d)
## Direct computation of the covariance
C <- cov(x)
## Recursive computation of the covariance
xbar0 <- colMeans(x[1:n0,])
C0 <- cov(x[1:n0,])
Crec <- updateCovariance(C0, x[(n0+1):n,], n0, xbar0)
## Check equality
all.equal(C, Crec)