Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a fully typed Diagonal constructor from AbstractMatrixes #52487

Merged
merged 6 commits into from
Dec 27, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion stdlib/LinearAlgebra/src/diagonal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ struct Diagonal{T,V<:AbstractVector{T}} <: AbstractMatrix{T}
new{T,V}(diag)
end
end
Diagonal{T,V}(d::Diagonal) where {T,V<:AbstractVector{T}} = Diagonal{T,V}(d.diag)
Diagonal{T,V}(M::AbstractMatrix) where {T,V<:AbstractVector{T}} = Diagonal{T,V}(diag(M))
jishnub marked this conversation as resolved.
Show resolved Hide resolved
Diagonal(v::AbstractVector{T}) where {T} = Diagonal{T,typeof(v)}(v)
Diagonal{T}(v::AbstractVector) where {T} = Diagonal(convert(AbstractVector{T}, v)::AbstractVector{T})

Expand Down
7 changes: 7 additions & 0 deletions stdlib/LinearAlgebra/test/diagonal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ Random.seed!(1)
DI = Diagonal([1,2,3,4])
@test Diagonal(DI) === DI
@test isa(Diagonal{elty}(DI), Diagonal{elty})

# diagonal matrices may be converted to Diagonal
local A = [1 0; 0 2]
local DA = convert(Diagonal{Float32,Vector{Float32}}, A)
@test DA isa Diagonal{Float32,Vector{Float32}}
@test DA == A

# issue #26178
@test_throws MethodError convert(Diagonal, [1,2,3,4])
@test_throws DimensionMismatch convert(Diagonal, [1 2 3 4])
Expand Down