Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add diagm for vectors #31125

Merged
merged 8 commits into from
Mar 1, 2019
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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` can now construct a diagonal matrix from a vector (#[31125]).
eulerkochy marked this conversation as resolved.
Show resolved Hide resolved

#### 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
9 changes: 9 additions & 0 deletions stdlib/LinearAlgebra/test/dense.jl
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,15 @@ 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))
for i = 1:50
eulerkochy marked this conversation as resolved.
Show resolved Hide resolved
v = randn(500)
@test diagm(v) == diagm(0 => v)
end
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