Skip to content

Commit

Permalink
linalg: add diagm(v) as shorthand for diagm(0 => v), fixes #31111 (#3…
Browse files Browse the repository at this point in the history
  • Loading branch information
eulerkochy authored and fredrikekre committed Mar 1, 2019
1 parent 9329e0f commit 5a4191d
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
15 changes: 15 additions & 0 deletions stdlib/LinearAlgebra/src/dense.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 7 additions & 0 deletions stdlib/LinearAlgebra/test/dense.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 5a4191d

Please sign in to comment.