Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/diagonal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -970,6 +970,10 @@ function inv(D::Diagonal{T}) where T
Diagonal(Di)
end

# Ensure doubly wrapped matrices use efficient diagonal methods and return a Symmetric/Hermitian type
inv(A::Symmetric{<:Number,<:Diagonal}) = Symmetric(inv(A.data), sym_uplo(A.uplo))
inv(A::Hermitian{<:Number,<:Diagonal}) = Hermitian(inv(real(A.data)), sym_uplo(A.uplo))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To avoid the issue of returning a real-eltype matrix for a complex-eltype argument, this should perhaps be

Suggested change
inv(A::Hermitian{<:Number,<:Diagonal}) = Hermitian(inv(real(A.data)), sym_uplo(A.uplo))
inv(A::Hermitian{T,S}) where {T<:Number, S<:Diagonal} = Hermitian{T,S}(inv(real(A.data)), A.uplo)

?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose that's possible, but a Hermitian Diagonal matrix is actually always a real Diagonal matrix, so we can deduce from the type alone that the inverse is always a real diagonal matrix. This also holds for quaternion and octonion valued matrices. If there is a number type where becomes a problem, then using real might also be a problem.


function pinv(D::Diagonal{T}) where T
Di = similar(D.diag, typeof(inv(oneunit(T))))
for i = 1:length(D.diag)
Expand Down
15 changes: 15 additions & 0 deletions test/symmetric.jl
Original file line number Diff line number Diff line change
Expand Up @@ -874,6 +874,21 @@ end
@test det(Hermitian(A))::Float64 == det(A) == 0.0
end

@testset "issue #1437: inverse of Symmetric|Hermitian{<:Any,<:Diagonal} returns of Symmetric|Hermitian{<:Any,<:Diagonal}" begin
Dreal = Diagonal(randn(3))
Dcomplex = Diagonal(randn(ComplexF64, 3))
# without wrapper
invDreal = inv(Dreal)
invDcomplex = inv(real(Dcomplex)) # because Hermitian implies a real diagonal
# with wrapper
SDreal = Symmetric(Dreal)
HDcomplex = Hermitian(Dcomplex)
@test inv(SDreal)::Symmetric{Float64,typeof(Dreal)} ≈ invDreal
@test inv(HDcomplex)::Hermitian{Float64,typeof(Dreal)} ≈ invDcomplex
Dcomplex[2,2] = 0
@test_throws SingularException inv(HDcomplex)
end

@testset "symmetric()/hermitian() for Numbers" begin
@test LinearAlgebra.symmetric(1) == LinearAlgebra.symmetric(1, :U) == 1
@test LinearAlgebra.symmetric_type(Int) == Int
Expand Down