Skip to content

Commit 76fed85

Browse files
author
Andy Ferris
committed
Add diagm(), fix #62
1 parent 55449ff commit 76fed85

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

src/StaticArrays.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import Base: @pure, @propagate_inbounds, getindex, setindex!, size, similar,
66
length, convert, promote_op, map, map!, reduce, mapreduce,
77
broadcast, broadcast!, conj, transpose, ctranspose, hcat, vcat,
88
ones, zeros, eye, cross, vecdot, reshape, fill, fill!, det, inv,
9-
eig, trace, vecnorm, norm, dot
9+
eig, trace, vecnorm, norm, dot, diagm
1010

1111
export StaticScalar, StaticArray, StaticVector, StaticMatrix
1212
export Scalar, SArray, SVector, SMatrix

src/linalg.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,16 @@ end
242242
end
243243
end
244244

245+
@generated function diagm(v::StaticVector)
246+
T = eltype(v)
247+
exprs = [i == j ? :(v[$i]) : zero(T) for i = 1:length(v), j = 1:length(v)]
248+
newtype = similar_type(v, (length(v), length(v)))
249+
return quote
250+
$(Expr(:meta, :inline))
251+
@inbounds return $(Expr(:call, newtype, Expr(:tuple, exprs...)))
252+
end
253+
end
254+
245255
@generated function cross(a::StaticVector, b::StaticVector)
246256
if length(a) === 3 && length(b) === 3
247257
return quote

test/linalg.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@
1414
@test v1 - v2 === @SVector [-2, 1, 4, 7]
1515
end
1616

17+
@testset "diagm()" begin
18+
@test diagm(SVector(1,2)) === @SMatrix [1 0; 0 2]
19+
end
20+
1721
@testset "eye()" begin
1822
@test eye(SMatrix{2,2,Int}) === @SMatrix [1 0; 0 1]
1923
@test eye(SMatrix{2,2}) === @SMatrix [1.0 0.0; 0.0 1.0]

0 commit comments

Comments
 (0)