dtmvnorm(x=c(0,0))
dtmvnorm(x=c(0,0), mean=c(1,1), upper=c(0,0))
###########################################
#
# Example 1:
# rejection sampling
#
############################################
sigma <- matrix(c(4,2,2,3), ncol=2)
x <- rtmvnorm(n=500, mean=c(1,2), sigma=sigma, upper=c(1,0))
plot(x, main="samples from truncated bivariate normal distribution",
xlim=c(-6,6), ylim=c(-6,6),
xlab=expression(x[1]), ylab=expression(x[2]))
abline(v=1, lty=3, lwd=2, col="gray")
abline(h=0, lty=3, lwd=2, col="gray")
###########################################
#
# Example 2:
# Gibbs sampler for 4 dimensions
#
############################################
C = matrix(0.8, 4, 4)
diag(C)=rep(1, 4)
lower = rep(-4, 4)
upper = rep(-1, 4)
# acceptance rate alpha
alpha = pmvnorm(lower=lower, upper=upper, mean=rep(0,4), sigma=C)
alpha
# Gibbs sampler
X1=rtmvnorm(n=20000, mean = rep(0,4), sigma=C, lower=lower, upper=upper,
algorithm="gibbs", burn.in.samples=100)
# Rejection sampling
X2=rtmvnorm(n=5000, mean = rep(0,4), sigma=C, lower=lower, upper=upper)
colMeans(X1)
colMeans(X2)
plot(density(X1[,1]), col="red", lwd=2, main="Gibbs vs. Rejection")
lines(density(X2[,1]), col="blue", lwd=2)
legend("topleft",legend=c("Gibbs Sampling","Rejection Sampling"),
col=c("red","blue"), lwd=2)
Run the code above in your browser using DataLab