简体   繁体   中英

How to Generate Random Covariance Matrix from Wishart Distrubtion

I need to generate an nxn, positive-definite covariance matrix for a project. Drawing from the Wishart distribution was recommended. How do I generate a random covariance matrix in R, ideally also using the Wishart Distribution. I've tried rwishart() to get values, but need more help. Thanks

Please see the function documentation by running ?rWishart .

As you can read, you need to supply the number of samples n you want (ie n random matrices), the degrees of freedom df , and the parameter Sigma to the function. In addition, you also need to decide on the dimension of the wanted random matrix.

# Set parameters
n <- 1  # Number of matrices
p <- 5  # Dimension
df <- 10  # Degrees of freedom
Sigma <- toeplitz((p:1)/p)  # the matrix parameter of the distribution

# Draw n Wishart distributed matrices
rwish <- drop(rWishart(n, df, Sigma))
print(rwish)

The function generates a 1 xpxp array (effectively a matrix) but we drop the unneeded dimension.

You can generate a wishart distributed matrix "manually" by

library("mvtnorm")
rgaus <- rmvnorm(n = df, mean = rep(0, p), sigma = Sigma)
rwish2 <- crossprod(rgaus) # crossprod is the same as "t(rgaus) %*% rgaus"

which should help you understand better what the Wishart distribution actually is. It is the distribution of the so-called scatter matrix df samples from a zero-mean multivariate normal distribution with variance Sigma .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM