模拟最大特征值的采样分布

时间:2016-10-28 18:41:55

标签: r function simulation eigenvalue

我想找到X的最大特征值(遵循Wishart分布)。我用模拟来看这些特征值的经验分布。但是当我以这种方式编码时

library(MASS)

 function(X){
    maxeigen.XtX <- NULL
    num_samples <- 1000
    for(i in 1:num_samples){
      X <- mvrnorm(n=10,mu=rep(0,3),Sigma = matrix(c(1,0.2,0.1,0.2,1,0.2,0.1,0.2,1),nrow=3))
      XtX <- t(X)%*%X
      maxeigen.XtX[i] <- max(eigen(XtX)$values)
      }
      return(maxeigen.XtX)
      summary <- summary(maxeigen.XtX)
      histgram <- hist(maxeigen.XtX,breaks=100)
    }

它没有给我任何东西。不确定问题出在哪里?

1 个答案:

答案 0 :(得分:1)

A成为您的目标协方差矩阵:

A <- matrix(c(1,0.2,0.1,0.2,1,0.2,0.1,0.2,1), nrow = 3)

#     [,1] [,2] [,3]
#[1,]  1.0  0.2  0.1
#[2,]  0.2  1.0  0.2
#[3,]  0.1  0.2  1.0

这是获取最大特征值的N个样本的工作函数。它比使用MASS::mvrnorm更有效,因为A的矩阵分解只执行一次而不是N次。

g <- function (N, n, A) {
  ## get upper triangular Choleksy factor of covariance `A`
  R <- chol.default(A)
  ## a function to generate `n` samples from `N(0, A)`
  ## and get largest eigen value
  f <- function (n, R) {
    Xstd <- matrix(rnorm(n * dim(R)[1L]), n)  ## `n` standard normal samples
    X <- Xstd %*% R  ## transform to have covariance `A`
    S <- crossprod(X)  ## `X'X`
    max(eigen(S, symmetric = TRUE)$values)  ## symmetric eigen decomposition
    }
  ## replicate `N` times for `N` samples of largest eigen values
  replicate(N, f(n, R))
  }

## try `N = 1000`, `n = 10`, as in your original code
set.seed(0); x <- g(1000, 10, A)

注意,我不要求g做摘要和情节。因为只要我们有样品,我们就可以随时进行。

d <- density.default(x)  ## density estimation
h <- hist.default(x, plot = FALSE)  ## histogram
graphics:::plot.histogram(h, freq = FALSE, ylim = c(0, max(h$density, d$y)),
                          main = "histogram of largest Eigen value")
lines(d$x, d$y, col = 2)

enter image description here