title: R chol and positive semi-definite matrix
body: <p>I have the following matrix:</p>
  
  <pre><code>j &lt;- matrix(c(1,1,.5,1,1,.5,.5,.5,1), nrow=3, ncol=3)
  </code></pre>
  
  <p>Which is positive semi-definite, because all of the eigenvalues are >= 0.</p>
  
  <p>Source: <a href="https://math.stackexchange.com/questions/40849/how-to-check-if-a-symmetric-4-times4-matrix-is-positive-semi-definite">https://math.stackexchange.com/questions/40849/how-to-check-if-a-symmetric-4-times4-matrix-is-positive-semi-definite</a></p>
  
  <pre><code>&gt; eigen(j, symmetric = TRUE)
  $values
  [1] 2.3660254 0.6339746 0.0000000
  
  $vectors
             [,1]       [,2]          [,3]
  [1,] -0.6279630 -0.3250576  7.071068e-01
  [2,] -0.6279630 -0.3250576 -7.071068e-01
  [3,] -0.4597008  0.8880738 -1.942890e-15
  </code></pre>
  
  <p>However, the cholesky decomposition fails...</p>
  
  <pre><code>&gt; chol(j)
  Error in chol.default(j) : 
    the leading minor of order 2 is not positive definite
  </code></pre>
  
  <p>I also adapted some code from the internet...</p>
  
  <pre><code>cholesky_matrix &lt;- function(A){
      # http://rosettacode.org/wiki/Cholesky_decomposition#C
  
      L &lt;- matrix(0,nrow=nrow(A),ncol=ncol(A))
      colnames(L) &lt;- colnames(A)
      rownames(L) &lt;- rownames(A)
  
      m &lt;- ncol(L)
  
  
      for(i in 1:m){
          for(j in 1:i){
              s &lt;- 0
              if(j &gt; 1){
                  for(k in 1:(j-1)){
                      s &lt;- s + L[i,k]*L[j,k]
                  }
              }
              if(i == j){
                  L[i,j] &lt;- sqrt(A[i,i] - s)
              } else {
                  L[i,j] &lt;- (1 / L[j,j])*(A[i,j] - s)
              }
          }
      }
      return(L)    
  }
  </code></pre>
  
  <p>Which also "fails" with NaNs.</p>
  
  <pre><code>&gt; cholesky_matrix(j)
       [,1] [,2] [,3]
  [1,]  1.0    0    0
  [2,]  1.0    0    0
  [3,]  0.5  NaN  NaN
  </code></pre>
  
  <p>Does anyone have any idea what is going on?  Why is my decomposition failing?</p>