Skip to content

Commit

Permalink
Merge pull request #255 from wsshin/diagm-with-Val
Browse files Browse the repository at this point in the history
Support Val{k} as second argument in diagm
  • Loading branch information
c42f authored Jul 27, 2017
2 parents 588c0a8 + 43b8bfa commit da1a371
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/linalg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -172,11 +172,18 @@ end
end
end

@inline diagm(v::StaticVector) = _diagm(Size(v), v)
@generated function _diagm(::Size{S}, v::StaticVector) where {S}
Snew = (S[1], S[1])
@inline diagm(v::StaticVector, k::Type{Val{D}}=Val{0}) where {D} = _diagm(Size(v), v, k)
@generated function _diagm(::Size{S}, v::StaticVector, ::Type{Val{D}}) where {S,D}
S1 = S[1]
Snew1 = S1+abs(D)
Snew = (Snew1, Snew1)
Lnew = Snew1 * Snew1
T = eltype(v)
exprs = [i == j ? :(v[$i]) : zero(T) for i = 1:S[1], j = 1:S[1]]
ind = diagind(Snew1, Snew1, D)
exprs = fill(:(zero($T)), Lnew)
for n = 1:S[1]
exprs[ind[n]] = :(v[$n])
end
return quote
$(Expr(:meta, :inline))
@inbounds return similar_type($v, Size($Snew))(tuple($(exprs...)))
Expand Down Expand Up @@ -323,4 +330,3 @@ end

@inline Base.LinAlg.Symmetric(A::StaticMatrix, uplo::Char='U') = (Base.LinAlg.checksquare(A);Symmetric{eltype(A),typeof(A)}(A, uplo))
@inline Base.LinAlg.Hermitian(A::StaticMatrix, uplo::Char='U') = (Base.LinAlg.checksquare(A);Hermitian{eltype(A),typeof(A)}(A, uplo))

2 changes: 2 additions & 0 deletions test/linalg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ using StaticArrays, Base.Test

@testset "diagm()" begin
@test @inferred(diagm(SVector(1,2))) === @SMatrix [1 0; 0 2]
@test @inferred(diagm(SVector(1,2,3), Val{2}))::SMatrix == diagm([1,2,3], 2)
@test @inferred(diagm(SVector(1,2,3), Val{-2}))::SMatrix == diagm([1,2,3], -2)
end

@testset "diag()" begin
Expand Down

0 comments on commit da1a371

Please sign in to comment.