DR15
DR15

Reputation: 693

How to looping until I get a positive definite matrix

I think I have a simple issue, where, in my real problem is that sometimes my loop got a not 'positive definite' matrix, and then I can't generate random values from a normal distribution using this matrix as Scale parameter. So, I'm struggling on how can I calculate that again until I get a a 'positive definite' one. I made a simple example that can help:

test = function(a){
  b = rnorm(1) + a
  c = b - .5
  return(c)
}
replicate(20,test(.5))

[1]  0.93297282  1.17247501 -0.06919809  0.71069048 -0.12760964  1.46818526 -1.34637900  0.85637634 -0.03191685
[10]  0.24198938  0.26555849 -0.47910932  0.11841441  1.92971628 -1.23540504 -0.07653842 -0.08895779  1.32780821
[19] -0.03604193  0.13845360

Suppose I want 'c' to be positive, and whenever 'c' is negative I would like 'b' to be generated again. I know we could truncate, but in my real case I need to go back and generate the variable 'b' again, until I have the 20 positive values for 'c'.

Any hint on how can I do that?

Upvotes: 0

Views: 57

Answers (1)

jay.sf
jay.sf

Reputation: 73212

You could use a repeat loop and break it if c >= 0.

test <- function(a) {
  repeat({
    b <- rnorm(1) + a
    c <- b - .5
    if (c >= 0) break
  })
  return(c)
}

set.seed(42)
replicate(20, test(.5))
# [1] 1.37095845 0.36312841 0.63286260 0.40426832 1.51152200 2.01842371
# [7] 1.30486965 2.28664539 0.63595040 1.32011335 1.21467470 1.89519346
# [13] 0.46009735 0.45545012 0.70483734 1.03510352 0.50495512 0.03612261
# [19] 0.20599860 0.75816324

Upvotes: 1

Related Questions