# Simple example to show how data are input to the filter-sampler.
# Assumes a simple bivariate regression model with switching means and
# variances.
TT <- 100
h <- 2
m <- 2
set.seed(123)
x1 <- rnorm(TT)
x2 <- rnorm(TT)
y1 <- 5 + 2*x1 + rnorm(TT)
y2 <- 1 + x2 + 5*rnorm(TT)
Y <- rbind(cbind(y1[1:(0.5*TT)],y2[1:(0.5*TT)]),
cbind(y2[((0.5*TT)+1):TT],y1[((0.5*TT)+1):TT]))
X <- rbind(cbind(x1[1:(0.5*TT)],x2[1:(0.5*TT)]),
cbind(x2[((0.5*TT)+1):TT],x1[((0.5*TT)+1):TT]))
u1 <- Y - tcrossprod(cbind(rep(1,TT), X), matrix(c(5,2,0,1,1,0), 2, 3))
u2 <- Y - tcrossprod(cbind(rep(1,TT), X), matrix(c(1,1,0,5,2,0), 2, 3))
u <- array(0, c(TT, m, h))
u[,,1] <- u1
u[,,2] <- u2
Sik <- array(0, c(m,m,h))
Sik[,,1] <- diag(c(1,25))
Sik[,,2] <- diag(c(25,1))
Q <- matrix(c(0.9,0.2,0.1,0.8), h, h)
# estimate the states 100 times
ss <- replicate(100, SS.ffbs(u, TT, m, p=1, h, Sik, Q), simplify=FALSE)
# Get the state estimates from the 100 simulations
ss.est <- matrix(unlist(ss), nrow=(h*TT + h^2))
ss.prob <- matrix(rowMeans(ss.est[1:(h*TT),]), ncol=h)
ss.transition <- matrix(rowMeans(ss.est[((h*TT)+1):((h*TT) + h^2),]),
h, h)
Run the code above in your browser using DataLab