Skip to content

Commit

Permalink
add a Diagonal constructor and a conversion (#48895)
Browse files Browse the repository at this point in the history
* add a Diagonal constructor and a conversion

Co-authored-by: woclass <[email protected]>
  • Loading branch information
putianyi889 and inkydragon authored Mar 9, 2023
1 parent 78ec99b commit 2ed1cfe
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
5 changes: 5 additions & 0 deletions stdlib/LinearAlgebra/src/diagonal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ julia> diag(A, 2)
```
"""
Diagonal(A::AbstractMatrix) = Diagonal(diag(A))
Diagonal{T}(A::AbstractMatrix) where T = Diagonal{T}(diag(A))
function convert(::Type{T}, A::AbstractMatrix) where T<:Diagonal
checksquare(A)
isdiag(A) ? T(A) : throw(InexactError(:convert, T, A))
end

Diagonal(D::Diagonal) = D
Diagonal{T}(D::Diagonal{T}) where {T} = D
Expand Down
5 changes: 4 additions & 1 deletion stdlib/LinearAlgebra/test/diagonal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,14 @@ Random.seed!(1)
end
@test eltype(Diagonal{elty}([1,2,3,4])) == elty
@test isa(Diagonal{elty,Vector{elty}}(GenericArray([1,2,3,4])), Diagonal{elty,Vector{elty}})
@test isa(Diagonal{elty}(rand(Int,n,n)), Diagonal{elty,Vector{elty}})
DI = Diagonal([1,2,3,4])
@test Diagonal(DI) === DI
@test isa(Diagonal{elty}(DI), Diagonal{elty})
# issue #26178
@test_throws MethodError convert(Diagonal, [1, 2, 3, 4])
@test_throws MethodError convert(Diagonal, [1,2,3,4])
@test_throws DimensionMismatch convert(Diagonal, [1 2 3 4])
@test_throws InexactError convert(Diagonal, ones(2,2))
end

@testset "Basic properties" begin
Expand Down

0 comments on commit 2ed1cfe

Please sign in to comment.