Skip to content

Instantly share code, notes, and snippets.

@buybackoff
Created December 9, 2016 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buybackoff/bfeb9c8959157dbf86310d383c93f00d to your computer and use it in GitHub Desktop.
Save buybackoff/bfeb9c8959157dbf86310d383c93f00d to your computer and use it in GitHub Desktop.
Recursive Least Squares with Exponential Forgetting
RLSF <- function(y,x,alpha=0.95,ist=30,xpxi=NULL,xpy0=NULL)
{
# http://queue.acm.org/detail.cfm?id=2534976
if(!is.matrix(x))x=as.matrix(x)
nT=dim(x)[1]
k=dim(x)[2]
xpx0 = NULL
#
if(is.null(xpxi)){
if(ist <= k)ist=k+1
xpx0=t(x[1:ist,])%*%x[1:ist,]
xpxi=solve(xpx0)
xpy0=t(x[1:ist,])%*%matrix(y[1:ist],ist,1)
}
ist=ist+1
resi=NULL
beta=matrix(c(xpxi%*%xpy0),1,k)
for (t in ist:nT){
jdx=t-ist+1
x1=matrix(x[t,],1,k)
tx1 = t(x1)
xpx0 = alpha * xpx0 + tx1 %*% x1
xpy0 = alpha * xpy0 + tx1 * y[[t]]
xpxi=solve(xpx0)
tmp = matrix(c(xpxi%*%xpy0),1,k)
beta=rbind(beta,tmp)
res=y[t]-tmp%*%t(x1)
resi=c(resi,res)
}
beta=beta[-1,]
RLSF <- list(beta=beta,resi=resi)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment