#Example multivariate Metropolis-Hastings fixed scan
#Target distribution 
f= function(x)
  {
    exp(-sum(x^2)^(3/2)/3)
}
#Proposal distribution: Gaussian distribution centered at previous value
p = 50
N = 1000000    # Number of iterations
x = matrix(nrow=N,ncol=p)

#Initial value
x[1,] = rnorm(p)
acc = 0
j = 0
for(i in 2:N)
{
  j = i%%p + 1                  # fixed scan j is cycling through 1 to p
  y = x[i-1,]                   # initialize proposal  as previous time  
  y[j] = rnorm(1,x[i-1,j],1)    # update coordinate j in proposal
  R = f(y)*dnorm(x[i-1,j],y[j],1)/(f(x[i-1,])*dnorm(y[j],x[i-1,j],1)) # compute M_H Ratio for proposal
  if(runif(1)<R)   #  accept proposal if ok
  {
    x[i,] = y
    acc = acc+1
  }
  else             #  or keep old 
   x[i,] = x[i-1,]
}


par(mfrow=c(3,1))
plot.ts(x[(0:1000)*50+1,1],main='X[,1] first 1000 scans')
plot.ts(x[(0:1000)*50+1,2],main='X[,2] first 1000 scans')
hist(x[,1],100,prob=T)
cat("Acceptance rate=",acc/(N-1),"\n")
