Skip to content

Instantly share code, notes, and snippets.

@RichPollock
Created October 13, 2015 08:32
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save RichPollock/04091c29789dc6e5c55c to your computer and use it in GitHub Desktop.
Save RichPollock/04091c29789dc6e5c55c to your computer and use it in GitHub Desktop.
VBA function for Cholesky decomposition
Function CholeskyDecompose(matrix As Range)
Dim A, LTM() As Double, S As Double
Dim j As Long, K As Long, i As Long, N As Long, M As Long
A = matrix
N = matrix.Rows.Count
M = matrix.Columns.Count
If N <> M Then
CholeskyDecompose = "Non-invertible matrix"
Exit Function
End If
ReDim LTM(1 To N, 1 To N)
For j = 1 To N
S = 0
For K = 1 To j - 1
S = S + LTM(j, K) ^ 2
Next K
LTM(j, j) = A(j, j) - S
If LTM(j, j) <= 0 Then Exit For
LTM(j, j) = Sqr(LTM(j, j))
For i = j + 1 To N
S = 0
For K = 1 To j - 1
S = S + LTM(i, K) * LTM(j, K)
Next K
LTM(i, j) = (A(i, j) - S) / LTM(j, j)
Next i
Next j
CholeskyDecompose = LTM
End Function
@philjoubert
Copy link

Thanks for the implementation.
In line 24 where you have an I think it would be better to quit the function and report that the matrix is not Positive Semi Definite.
I also added in a check at the start to make sure the input matrix is symmetric.
Happy to contribute my code

@spantegu
Copy link

spantegu commented Jan 8, 2021

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment