Skip to content

Commit f7e6eb6

Browse files
authored
Merge pull request #212 from marius311/MM/sqrtm
add sqrtm
2 parents 5079568 + d47dcdf commit f7e6eb6

File tree

4 files changed

+29
-1
lines changed

4 files changed

+29
-1
lines changed

src/StaticArrays.jl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import Base: getindex, setindex!, size, similar, vec, show,
88
length, convert, promote_op, map, map!, reduce, reducedim, mapreducedim,
99
mapreduce, broadcast, broadcast!, conj, transpose, ctranspose,
1010
hcat, vcat, ones, zeros, eye, one, cross, vecdot, reshape, fill,
11-
fill!, det, inv, eig, eigvals, expm, trace, vecnorm, norm, dot, diagm,
11+
fill!, det, inv, eig, eigvals, expm, sqrtm, trace, vecnorm, norm, dot, diagm,
1212
sum, diff, prod, count, any, all, minimum,
1313
maximum, extrema, mean, copy, rand, randn, randexp, rand!, randn!,
1414
randexp!, normalize, normalize!, read, read!, write
@@ -91,6 +91,7 @@ include("inv.jl")
9191
include("solve.jl")
9292
include("eigen.jl")
9393
include("expm.jl")
94+
include("sqrtm.jl")
9495
include("cholesky.jl")
9596
include("deque.jl")
9697
include("io.jl")

src/sqrtm.jl

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
@inline sqrtm(A::StaticMatrix) = _sqrtm(Size(A),A)
2+
3+
@inline function _sqrtm(::Size{(1,1)}, A::SA) where {SA<:StaticArray}
4+
s = sqrtm(A[1,1])
5+
similar_type(SA,typeof(s))(s)
6+
end
7+
8+
@inline function _sqrtm(::Size{(2,2)}, A::SA) where {SA<:StaticArray}
9+
a,b,c,d = A
10+
if a==b==c==d==0
11+
zero(A)
12+
else
13+
s = sqrtm(a*d-b*c)
14+
t = inv(sqrtm(a+d+2s))
15+
similar_type(SA,typeof(t))(t*(a+s), t*b, t*c, t*(d+s))
16+
end
17+
end
18+
19+
@inline _sqrtm(s::Size, A::StaticArray) = s(Base.sqrtm(Array(A)))

test/runtests.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ using Base.Test
2727
include("solve.jl") # Strange inference / world-age error
2828
include("eigen.jl")
2929
include("expm.jl")
30+
include("sqrtm.jl")
3031
include("chol.jl")
3132
include("deque.jl")
3233
include("io.jl")

test/sqrtm.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
@testset "Matrix square root" begin
2+
@test sqrtm(@SMatrix [2])::SMatrix SMatrix{1,1}(sqrtm(2))
3+
@test sqrtm(@SMatrix [5 2; -2 1])::SMatrix sqrtm([5 2; -2 1])
4+
@test sqrtm(@SMatrix [4 2; -2 1])::SMatrix sqrtm([4 2; -2 1])
5+
@test sqrtm(@SMatrix [4 2; 2 1])::SMatrix sqrtm([4 2; 2 1])
6+
@test sqrtm(@SMatrix [1 2 0; 2 1 0; 0 0 1])::SizedArray{Tuple{3,3}} sqrtm([1 2 0; 2 1 0; 0 0 1])
7+
end

0 commit comments

Comments
 (0)