LinearAlgebra.jl icon indicating copy to clipboard operation
LinearAlgebra.jl copied to clipboard

Specialize `diag(::Diagonal)`

Open putianyi889 opened this issue 11 months ago • 5 comments

The current implementation diag(::Diagonal, k=0), for the sake of type stability, returns a Vector even when D.diag is lazy.

julia> diag(Diagonal(1:5))
5-element Vector{Int64}:
 1
 2
 3
 4
 5

This can cause bugs when one does want the result to be lazy:

julia> D1 = Diagonal(1:5)
5×5 Diagonal{Int64, UnitRange{Int64}}:
 1  ⋅  ⋅  ⋅  ⋅
 ⋅  2  ⋅  ⋅  ⋅
 ⋅  ⋅  3  ⋅  ⋅
 ⋅  ⋅  ⋅  4  ⋅
 ⋅  ⋅  ⋅  ⋅  5

julia> D2 = Diagonal(1.0:5.0)
5×5 Diagonal{Float64, StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}}:
 1.0   ⋅    ⋅    ⋅    ⋅ 
  ⋅   2.0   ⋅    ⋅    ⋅
  ⋅    ⋅   3.0   ⋅    ⋅
  ⋅    ⋅    ⋅   4.0   ⋅
  ⋅    ⋅    ⋅    ⋅   5.0

julia> oftype(D2,D1)
ERROR: MethodError: Cannot `convert` an object of type Vector{Int64} to an object of type StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}

putianyi889 avatar Dec 22 '24 22:12 putianyi889