Skip to content

Commit b4b0c4e

Browse files
authored
Inverse of Cholesky decomposition (#852)
* inverse of Cholesky decomposition * division by Cholesky decomposition * right division by Cholesky is not available on older Julia versions * comment about a version check
1 parent 8033332 commit b4b0c4e

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/cholesky.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,16 @@ end
5555
similar_type(A)(cholesky(Hermitian(Matrix(A))).U)
5656

5757
LinearAlgebra.hermitian_type(::Type{SA}) where {T, S, SA<:SArray{S,T}} = Hermitian{T,SA}
58+
59+
function inv(A::Cholesky{T,<:StaticMatrix{N,N,T}}) where {N,T}
60+
return A.U \ (A.U' \ SDiagonal{N}(I))
61+
end
62+
63+
function Base.:\(A::Cholesky{T,<:StaticMatrix{N,N,T}}, B::StaticVecOrMatLike) where {N,T}
64+
return A.U \ (A.U' \ B)
65+
end
66+
67+
function Base.:/(B::StaticMatrixLike, A::Cholesky{T,<:StaticMatrix{N,N,T}}) where {N,T}
68+
return (B / A.U) / A.U'
69+
end
70+

test/chol.jl

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,44 @@ using LinearAlgebra: PosDefException
4848
m = SMatrix{25,25}(m_a)
4949
@test cholesky(m).L cholesky(m_a).L
5050
end
51+
52+
@testset "Inverse" begin
53+
m_a = randn(elty, 3, 3)
54+
m_a = m_a*m_a'
55+
m = SMatrix{3,3}(m_a)
56+
c = cholesky(m)
57+
@test (@inferred inv(c)) isa SMatrix{3,3,elty}
58+
@test inv(c) SMatrix{3,3}(inv(m_a))
59+
end
60+
61+
@testset "Division" begin
62+
m_a = randn(elty, 3, 3)
63+
m_a = m_a*m_a'
64+
m = SMatrix{3,3}(m_a)
65+
c = cholesky(m)
66+
c_a = cholesky(m_a)
67+
68+
d_a = randn(elty, 3, 3)
69+
d = SMatrix{3,3}(d_a)
70+
71+
@test (@inferred c \ d) isa SMatrix{3,3,elty}
72+
@test c \ d c_a \ d_a
73+
@test (@inferred c \ Symmetric(d)) isa SMatrix{3,3,elty}
74+
@test c \ Symmetric(d) c_a \ Symmetric(d_a)
75+
76+
if VERSION >= v"1.3"
77+
# on earlier versions of Julia d_a / c_a fails
78+
@test (@inferred d / c) isa SMatrix{3,3,elty}
79+
@test d / c d_a / c_a
80+
@test (@inferred Symmetric(d) / c) isa SMatrix{3,3,elty}
81+
@test Symmetric(d) / c Symmetric(d_a) / c_a
82+
end
83+
84+
v_a = randn(elty, 3)
85+
v = SVector{3}(v_a)
86+
@test (@inferred c \ v) isa SVector{3,elty}
87+
@test c \ v c_a \ v_a
88+
end
5189
end
5290

5391
@testset "static blockmatrix" for i = 1:10

0 commit comments

Comments
 (0)