0

I have done mvn simulation with the MASS package.

Simulations should have the Mean and Variances of X and Y and a chosen correlation. SO far this works:

    K=0.1
    Sim <- data.frame(X,Y)
    CovM <- matrix(data=c(var(X),(-k)*sd(X)*sd(Y),(-k)*sd(X)*sd(Y),var(Y),ncol=2,nrow=2)
    MVSim <- mvrnorm(n, mu=colMeans(Sim), Sigma=CovM, empirical=TRUE)

Now I want to replicate the procedure with a for loop:

    for(i in seq(1,m, by=2)){
      MVSimOB[, i:(i+1)] <- mvrnorm(n, mu=colMeans(Sim), Sigma=CovM, empirical=TRUE)

But I get the following error message:

  Sigma = matrix(c(var(SimYOB),  : 
  Indices out of borders

The solution is probably very simple. But I do not understand why I first do not get an error, but replicating the procedure does not work. Thanks a lot for help!

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
greenfisha
  • 3
  • 1
  • 3
  • Hi, you have forgotten the 'matrix' in the loop – Mamoun Benghezal Feb 18 '15 at 15:37
  • Hey, I have edited my post now - unfortunately it still does not work! – greenfisha Feb 18 '15 at 15:44
  • 1
    hard to say where is the problem without reproductivle example, but obviously you covarance matrix is not the right size. You should check out your matrix before executing **mvnorm** – Mamoun Benghezal Feb 18 '15 at 15:48
  • check your code, there is some miss parenthese : CovM<-matrix(data=c(var(X),(-k)*sd(X)*sd(Y),(-k)*sd(X)*sd(Y),var(Y),ncol=2,nrow=2) – Mamoun Benghezal Feb 18 '15 at 16:04
  • 1
    There must have been some problem with the covariance matrix. I did not find out what exactly. But naming the first run MVSim1 and using Sigma = Cov(MVSim1) in the loop, it worked. - Thanks for the help! – greenfisha Feb 18 '15 at 16:12
  • I was getting this same error using ZCA whiten functions in R. I then saw that the methods implemented in python use a fudge factor (see https://martin-thoma.com/zca-whitening/ & https://stackoverflow.com/questions/6574782/how-to-whiten-matrix-in-pca/11336203#11336203). – thistleknot Dec 07 '21 at 00:26

0 Answers0