#' backwardAlg
#'
#' \code{backwardAlg} performs the Backward Algorithm on a single trajecture of observed chain X
#'
#' \code{backwardAlg} computes the matrix, beta, where beta[k,t] = P(X[(t+1):T]=x[(t+1):T] | Z[t]=k)
#'
#' @export
#' @param X a vector of observed states
#' @param trans a matrix of transition probability
#' @param u a vector of means of Normal distribution for each state (emission probability)
#' @param sig a vector of standard deviations of Normal distribution for each state (emission probability)
#' @return A matrix, beta.
#'
#' @examples
#' set.seed(1221)
#' df <- generateHMM(num=2,n=10)
#' backwardAlg(df$X[,1], df$trans, df$u, df$sig)
backwardAlg <- function(X, trans, u, sig){
n <- length(X) # length of Markov chain
M <- dim(trans)[1] # number of states of Markov chain
beta <- matrix(0, M, n)
beta[,n] <- 1
# compute beta by time/column
for (t in (n-1):1){
Pxz <- dnorm(X[t+1], u, sig)
beta[,t] <- trans %*% (Pxz * beta[, t+1])
}
return(beta)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.