diff --git a/NEWS.md b/NEWS.md index 4f643f61b3b6c..7b6beb3a10a6d 100644 --- a/NEWS.md +++ b/NEWS.md @@ -52,6 +52,7 @@ Standard library changes * Eigenvalues λ of general matrices are now sorted lexicographically by (Re λ, Im λ) ([#21598]). * `one` for structured matrices (`Diagonal`, `Bidiagonal`, `Tridiagonal`, `Symtridiagonal`) now preserves structure and type. ([#29777]) +* `diagm(v)` is now a shorthand for `diagm(0 => v)`. ([#31125]). #### SparseArrays diff --git a/stdlib/LinearAlgebra/src/dense.jl b/stdlib/LinearAlgebra/src/dense.jl index 0688d6d39e128..9326ff8a6155b 100644 --- a/stdlib/LinearAlgebra/src/dense.jl +++ b/stdlib/LinearAlgebra/src/dense.jl @@ -291,6 +291,21 @@ function diagm_container(kv::Pair{<:Integer,<:BitVector}...) return falses(n, n) end +""" + diagm(v::AbstractVector) + +Construct a square matrix with elements of the vector as diagonal elements. + +# Examples +```jldoctest +julia> diagm([1,2,3]) +3×3 Array{Int64,2}: + 1 0 0 + 0 2 0 + 0 0 3 +``` +""" +diagm(v::AbstractVector) = diagm(0 => v) function tr(A::Matrix{T}) where T n = checksquare(A) diff --git a/stdlib/LinearAlgebra/test/dense.jl b/stdlib/LinearAlgebra/test/dense.jl index 116a6da1afc12..496c84fccbe49 100644 --- a/stdlib/LinearAlgebra/test/dense.jl +++ b/stdlib/LinearAlgebra/test/dense.jl @@ -84,6 +84,13 @@ bimg = randn(n,2)/2 end end # for eltyb +@testset "Test diagm for vectors" begin + @test diagm(zeros(50)) == diagm(0 => zeros(50)) + @test diagm(ones(50)) == diagm(0 => ones(50)) + v = randn(500) + @test diagm(v) == diagm(0 => v) +end + @testset "Test pinv (rtol, atol)" begin M = [1 0 0; 0 1 0; 0 0 0] @test pinv(M,atol=1)== zeros(3,3)