I need to generate a sparse 100x100 precision matrix to sample multivariate Gaussian random vectors using the inverse of it as the covariance matrix. To be a valid precision matrix, the matrix I create should be a positive definite matrix, so I regenerate the matrix until it is positive definite (all its eigenvalues are positive). Here is my R code for this job:
library(pracma)
k = 100
sparsity = .2
while (TRUE) {
# generate the symmetric sparsity mask
mask = rand(k)
mask = mask * (mask < sparsity)
mask[lower.tri(mask, diag = TRUE)] = 0
mask = mask + t(mask) + eye(k)
mask[mask > 0] = 1
# generate the symmetric precision matrix
theta = matrix(rnorm(k^2), k)
theta[lower.tri(theta, diag = TRUE)] = 0
theta = theta + t(theta) + eye(k)
# apply the reqired sparsity
theta = theta * mask
if(sum(eigen(theta)$values > 0) == k) {
break
} else {
print('Theta is not positive definite!')
}
}
The problem is that this code never ends, which means that that kind of valid precision matrix can never be created. What is the way to achieve this job?