I have the following vector in R :
p = c(1/4,1/8,1/6,1/16,3/16,1/12,1/8);p
which has length 7.
I want to c.reate a matrix that will be N times N, where here N=7 but th. e the entries to be with metropolis Hastings algorithm.
As the picture suggests:
So r(x,y)=1/7
and p(x,y) =r(x,y) \min(\frac{\pi(y)}{\pi(x)},1)
For example the p(1,2) = 1/7 \cdot \min(\frac{1/8}{1/4},1) =1/14
p(1,3) = 1/7 \cdot \min(\frac{1/6}{1/4},1) =2/21 apart from the entry p(1,1) = 1-\sum_{i=2}^{j=7}p(i,j).
This sum will be in all the diagonal entries.
r = 1/7
r*min(p[2]/p[1],1)
Any help ?
For diagonal items, your indexes are i and j, but inside you have p(x,y). See your p(1,1). What would be p(2,2) and p(3,3) and so on. Can you please clarify?
p(i,j).I corrected it.The diagonal entries must have 1-sum(the values of the same row) .For example if row 4 is:
1,2,3,x,5,6,7 then x=1-sum(1,2,3,5,6,7)
Please check its correctness. I assume there is a better, compact way to do that. But, i just follow the algorithm.
p = c(1/4,1/8,1/6,1/16,3/16,1/12,1/8)
mh<-matrix(nrow = 7,ncol = 7)
r<-1/7
for (i in 1:7) {
for (j in 1:7) {
if(i!=j){
mh[i,j]<-r*min(p[j]/p[i],1)
}
}
mh[i,i]<-1-sum(mh[i,],na.rm = TRUE)
}
mh
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#> [1,] 0.5714286 0.07142857 0.0952381 0.03571429 0.1071429 0.04761905 0.07142857
#> [2,] 0.1428571 0.26190476 0.1428571 0.07142857 0.1428571 0.09523810 0.14285714
#> [3,] 0.1428571 0.10714286 0.3750000 0.05357143 0.1428571 0.07142857 0.10714286
#> [4,] 0.1428571 0.14285714 0.1428571 0.14285714 0.1428571 0.14285714 0.14285714
#> [5,] 0.1428571 0.09523810 0.1269841 0.04761905 0.4285714 0.06349206 0.09523810
#> [6,] 0.1428571 0.14285714 0.1428571 0.10714286 0.1428571 0.17857143 0.14285714
#> [7,] 0.1428571 0.14285714 0.1428571 0.07142857 0.1428571 0.09523810 0.26190476
Yes, they are 1s.
rowSums(mh)
#> [1] 1 1 1 1 1 1 1
We can also see in this way.
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#> [1,] 4/7 1/14 2/21 1/28 3/28 1/21 1/14
#> [2,] 1/7 11/42 1/7 1/14 1/7 2/21 1/7
#> [3,] 1/7 3/28 3/8 3/56 1/7 1/14 3/28
#> [4,] 1/7 1/7 1/7 1/7 1/7 1/7 1/7
#> [5,] 1/7 2/21 8/63 1/21 3/7 4/63 2/21
#> [6,] 1/7 1/7 1/7 3/28 1/7 5/28 1/7
#> [7,] 1/7 1/7 1/7 1/14 1/7 2/21 11/42
With the MASS::fractions() ?
It just shows number in fraction. Both is same matrix with different presentation. In later fraction matrix, we can easily see row sum is 1.
thanks a lot @mhakanda I appreciate your help mate
A huge thanks for this discussion. As a newbie I was very interesting to read