#Example multivariate  Metropolis-Hastings  random 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
for(i in 2:N)
{
  j = sample(1:p,1)                  # j is random sample of component to update 
  y = x[i-1,]                        # initialize proposal  as previous time  
  y[j] = rnorm(1,x[i-1,j],2)         # 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[1:(1000*p),1],main='X[,1] first 1000 scans')
plot.ts(x[1:(1000*p),2],main='X[,2] first 1000 scans')
hist(x[,1],100,prob=T)
cat("Acceptance rate=",acc/(N-1),"\n")

par(mfrow=c(3,1))
plot(x[(0:1000)*p+1,1],x[(1:1001)*p+1,1],main='X[,1] lag 1(scan) plot')
plot(x[(0:1000)*p+1,2],x[(1:1001)*p+1,2],main='X[,2] lag 1(scan) plot')
plot(x[(0:1000)*p+1,1],x[(1:1001)*p+1,2],main='X[,1] lag 1(scan) X[,2] plot')