diff --git a/stdlib/LinearAlgebra/src/diagonal.jl b/stdlib/LinearAlgebra/src/diagonal.jl index 53312a56bd29b..b3d54b5842112 100644 --- a/stdlib/LinearAlgebra/src/diagonal.jl +++ b/stdlib/LinearAlgebra/src/diagonal.jl @@ -704,7 +704,7 @@ function pinv(D::Diagonal{T}, tol::Real) where T end #Eigensystem -eigvals(D::Diagonal{<:Number}; permute::Bool=true, scale::Bool=true) = D.diag +eigvals(D::Diagonal{<:Number}; permute::Bool=true, scale::Bool=true) = copy(D.diag) eigvals(D::Diagonal; permute::Bool=true, scale::Bool=true) = [eigvals(x) for x in D.diag] #For block matrices, etc. eigvecs(D::Diagonal) = Matrix{eltype(D)}(I, size(D)) diff --git a/stdlib/LinearAlgebra/test/diagonal.jl b/stdlib/LinearAlgebra/test/diagonal.jl index 6efed3b7d9cff..8bc84d93c6348 100644 --- a/stdlib/LinearAlgebra/test/diagonal.jl +++ b/stdlib/LinearAlgebra/test/diagonal.jl @@ -465,6 +465,13 @@ end @test sort([eigvals(D)...;], by=LinearAlgebra.eigsortby) ≈ eigvals([D.diag[1] zeros(3,2); zeros(2,3) D.diag[2]]) end +@testset "eigvals should return a copy of the diagonal" begin + D = Diagonal([1, 2, 3]) + lam = eigvals(D) + D[3,3] = 4 # should not affect lam + @test lam == [1, 2, 3] +end + @testset "eigmin (#27847)" begin for _ in 1:100 d = randn(rand(1:10))