Skip to content

Commit

Permalink
add constructors for Symmetric(::Hermitian) and Hermitian(::Symmetric) (
Browse files Browse the repository at this point in the history
  • Loading branch information
fredrikekre authored and KristofferC committed Jun 7, 2017
1 parent 13c1830 commit 4e6ccf6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 14 deletions.
33 changes: 19 additions & 14 deletions base/linalg/symmetric.jl
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,6 @@ julia> Slower = Symmetric(A, :L)
Note that `Supper` will not be equal to `Slower` unless `A` is itself symmetric (e.g. if `A == A.'`).
"""
Symmetric(A::AbstractMatrix, uplo::Symbol=:U) = (checksquare(A); Symmetric{eltype(A),typeof(A)}(A, char_uplo(uplo)))
Symmetric(A::Symmetric) = A
function Symmetric(A::Symmetric, uplo::Symbol)
if A.uplo == char_uplo(uplo)
return A
else
throw(ArgumentError("Cannot construct Symmetric; uplo doesn't match"))
end
end

struct Hermitian{T,S<:AbstractMatrix} <: AbstractMatrix{T}
data::S
Expand Down Expand Up @@ -91,12 +83,25 @@ function Hermitian(A::AbstractMatrix, uplo::Symbol=:U)
end
Hermitian{eltype(A),typeof(A)}(A, char_uplo(uplo))
end
Hermitian(A::Hermitian) = A
function Hermitian(A::Hermitian, uplo::Symbol)
if A.uplo == char_uplo(uplo)
return A
else
throw(ArgumentError("Cannot construct Hermitian; uplo doesn't match"))

for (S, H) in ((:Symmetric, :Hermitian), (:Hermitian, :Symmetric))
@eval begin
$S(A::$S) = A
function $S(A::$S, uplo::Symbol)
if A.uplo == char_uplo(uplo)
return A
else
throw(ArgumentError("Cannot construct $($S); uplo doesn't match"))
end
end
$S(A::$H) = $S(A.data, Symbol(A.uplo))
function $S(A::$H, uplo::Symbol)
if A.uplo == char_uplo(uplo)
return $S(A.data, Symbol(A.uplo))
else
throw(ArgumentError("Cannot construct $($S); uplo doesn't match"))
end
end
end
end

Expand Down
7 changes: 7 additions & 0 deletions test/linalg/symmetric.jl
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ let n=10
@test Hermitian(Hermitian(asym, :U), :U) === Hermitian(asym, :U)
@test_throws ArgumentError Symmetric(Symmetric(asym, :U), :L)
@test_throws ArgumentError Hermitian(Hermitian(asym, :U), :L)
# mixed cases with Hermitian/Symmetric
@test Symmetric(Hermitian(asym, :U)) === Symmetric(asym, :U)
@test Hermitian(Symmetric(asym, :U)) === Hermitian(asym, :U)
@test Symmetric(Hermitian(asym, :U), :U) === Symmetric(asym, :U)
@test Hermitian(Symmetric(asym, :U), :U) === Hermitian(asym, :U)
@test_throws ArgumentError Symmetric(Hermitian(asym, :U), :L)
@test_throws ArgumentError Hermitian(Symmetric(asym, :U), :L)

# similar
@test isa(similar(Symmetric(asym)), Symmetric{eltya})
Expand Down

0 comments on commit 4e6ccf6

Please sign in to comment.