From 5da8d5f17ad9505fdb425c302f3dbac36eef7a55 Mon Sep 17 00:00:00 2001 From: Michael Abbott <32575566+mcabbott@users.noreply.github.com> Date: Wed, 30 Nov 2022 06:11:07 -0500 Subject: [PATCH] Add a warning about inadvertent Diagonal(::Matrix) (#46864) --- stdlib/LinearAlgebra/src/diagonal.jl | 31 +++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/stdlib/LinearAlgebra/src/diagonal.jl b/stdlib/LinearAlgebra/src/diagonal.jl index 291233ebe2e6a..1cb4240722ce2 100644 --- a/stdlib/LinearAlgebra/src/diagonal.jl +++ b/stdlib/LinearAlgebra/src/diagonal.jl @@ -24,13 +24,14 @@ end """ Diagonal(V::AbstractVector) -Construct a matrix with `V` as its diagonal. +Construct a lazy matrix with `V` as its diagonal. -See also [`diag`](@ref), [`diagm`](@ref). +See also [`UniformScaling`](@ref) for the lazy identity matrix `I`, +[`diagm`](@ref) to make a dense matrix, and [`diag`](@ref) to extract diagonal elements. # Examples ```jldoctest -julia> Diagonal([1, 10, 100]) +julia> d = Diagonal([1, 10, 100]) 3×3 Diagonal{$Int, Vector{$Int}}: 1 ⋅ ⋅ ⋅ 10 ⋅ @@ -40,6 +41,30 @@ julia> diagm([7, 13]) 2×2 Matrix{$Int}: 7 0 0 13 + +julia> ans + I +2×2 Matrix{Int64}: + 8 0 + 0 14 + +julia> I(2) +2×2 Diagonal{Bool, Vector{Bool}}: + 1 ⋅ + ⋅ 1 +``` + +Note that a one-column matrix is not treated like a vector, but instead calls the +method `Diagonal(A::AbstractMatrix)` which extracts 1-element `diag(A)`: + +```jldoctest +julia> A = transpose([7.0 13.0]) +2×1 transpose(::Matrix{Float64}) with eltype Float64: + 7.0 + 13.0 + +julia> Diagonal(A) +1×1 Diagonal{Float64, Vector{Float64}}: + 7.0 ``` """ Diagonal(V::AbstractVector)