Skip to content

Commit 66e9410

Browse files
jishnubdkarrasch
andauthored
Add a fully typed Diagonal constructor from AbstractMatrixes (#52487)
The following works after this PR: ```julia julia> oftype(Diagonal(Float32[1,2]), [1 0; 0 2]) 2×2 Diagonal{Float32, Vector{Float32}}: 1.0 ⋅ ⋅ 2.0 ``` This changes the behavior of the constructor to copy the diagonal, so now ```julia julia> D = Diagonal([1,2]); julia> typeof(D)(D).diag === D.diag false ``` whereas this used to be `true` previously. This probably doesn't matter much, as in most non-trivial cases it'd be copied anyway, and this conversion is unusual in the trivial case. --------- Co-authored-by: Daniel Karrasch <daniel.karrasch@posteo.de>
1 parent b4eefd0 commit 66e9410

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

stdlib/LinearAlgebra/src/diagonal.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ struct Diagonal{T,V<:AbstractVector{T}} <: AbstractMatrix{T}
1010
new{T,V}(diag)
1111
end
1212
end
13-
Diagonal{T,V}(d::Diagonal) where {T,V<:AbstractVector{T}} = Diagonal{T,V}(d.diag)
1413
Diagonal(v::AbstractVector{T}) where {T} = Diagonal{T,typeof(v)}(v)
1514
Diagonal{T}(v::AbstractVector) where {T} = Diagonal(convert(AbstractVector{T}, v)::AbstractVector{T})
1615

@@ -102,6 +101,7 @@ julia> Diagonal(A)
102101
"""
103102
Diagonal(A::AbstractMatrix) = Diagonal(diag(A))
104103
Diagonal{T}(A::AbstractMatrix) where T = Diagonal{T}(diag(A))
104+
Diagonal{T,V}(A::AbstractMatrix) where {T,V<:AbstractVector{T}} = Diagonal{T,V}(diag(A))
105105
function convert(::Type{T}, A::AbstractMatrix) where T<:Diagonal
106106
checksquare(A)
107107
isdiag(A) ? T(A) : throw(InexactError(:convert, T, A))

stdlib/LinearAlgebra/test/diagonal.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,13 @@ Random.seed!(1)
5050
DI = Diagonal([1,2,3,4])
5151
@test Diagonal(DI) === DI
5252
@test isa(Diagonal{elty}(DI), Diagonal{elty})
53+
54+
# diagonal matrices may be converted to Diagonal
55+
local A = [1 0; 0 2]
56+
local DA = convert(Diagonal{Float32,Vector{Float32}}, A)
57+
@test DA isa Diagonal{Float32,Vector{Float32}}
58+
@test DA == A
59+
5360
# issue #26178
5461
@test_throws MethodError convert(Diagonal, [1,2,3,4])
5562
@test_throws DimensionMismatch convert(Diagonal, [1 2 3 4])

0 commit comments

Comments
 (0)