Home > Net >  Detailed Balance equations in R
Detailed Balance equations in R

Time:12-03

I have a matrix and a vector in R.

The matrix is :

P = matrix(c(0,2/5,3/5,
             1/2,1/4,1/4,
             1/2,1/6,1/3),3,3,byrow = TRUE) 
P

and the vector is :

p = c(1/3,4/15,2/5)

I want to create a function have will have two arguments:

i)the matrix and ii) the vector

Inside the function I want to check all the detailed balance equations p_iP_ij = p_jP_ji if all these are equal then to return a message "balanced" otherwise "not_balanced"

For example :

p_1P_12 = 1/3*2/5 = 2/15

p_2P_21 = 4/15*1/2 =2/15

So p_1P_12 = p_2P_21

p_1P_13 = 1/3*3/5=3/15=1/5

p_3P_31 = 2/5*1/2=2/10=1/5

p_1P_13 = p_3P_31

p_2P_23 = 4/15*1/4=4/60=1/15

p_3P_32 = 2/5*1/6=2/30=1/15

p_2P_23=p_3P_32

No this is an example from Robert Dobrow's book Introduction to stochastic processes in R and is about a 3x3 matrix and a vector of length 3.

In general it might be a A \in R^{m \times m} matrix and a vector of length m.

How can I do it in R ?

CodePudding user response:

You could write a function to accomplish this:

is_balanced <- function(Mat, vec){
  Matrix::isSymmetric(Mat * vec)
}

is_balanced(P,p)
[1] TRUE

using for-loop:

is_balanced2 <- function(Mat, vec){
  l <- length(vec)
  for(i in seq(1, l-1)){
    for(j in seq(i 1, l))
      res <- abs(vec[i] * Mat[i, j]- vec[j] * Mat[j,i])
      if( res > .Machine$double.eps)return(FALSE)
  }
  return(TRUE)
}
  • Related