Skip to content

Commit 0efdeca

Browse files
committed
Implement matrix logarithm
1 parent e1cbee2 commit 0efdeca

File tree

5 files changed

+45
-1
lines changed

5 files changed

+45
-1
lines changed

src/StaticArrays.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ include("inv.jl")
134134
include("solve.jl")
135135
include("eigen.jl")
136136
include("expm.jl")
137+
include("logm.jl")
137138
include("sqrtm.jl")
138139
include("lyap.jl")
139140
include("triangular.jl")

src/logm.jl

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
@inline log(A::StaticMatrix) = _log(Size(A), A)
2+
3+
@inline function _log(::Size{(0,0)}, A::StaticMatrix)
4+
T = typeof(log(one(eltype(A))))
5+
SMT = similar_type(A,T)
6+
return SMT()
7+
end
8+
9+
@inline function _log(::Size{(1,1)}, A::StaticMatrix)
10+
T = typeof(log(one(eltype(A))))
11+
SMT = similar_type(A,T)
12+
return SMT((log(A[1]), ))
13+
end
14+
15+
function _log(::Size, A::StaticMatrix)
16+
eigA = eigen(A)
17+
T = typeof(log(one(eltype(A)) * one(eltype(eigA.values))))
18+
VT = similar_type(typeof(eigA.values),T)
19+
log_values = log.(VT(eigA.values))
20+
log_eigA = Eigen(log_values, eigA.vectors)
21+
logA = AbstractMatrix(log_eigA)
22+
return logA
23+
end

src/sqrtm.jl

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
@inline sqrt(A::StaticMatrix) = _sqrt(Size(A),A)
32

43
@inline function _sqrt(::Size{(1,1)}, A::SA) where {SA<:StaticArray}

test/logm.jl

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
using StaticArrays, Test, LinearAlgebra
2+
3+
@testset "Matrix logarithm" begin
4+
@test log(SMatrix{0,0,Int}())::SMatrix == SMatrix{0,0,Bool}()
5+
@test log(@SMatrix [2])::SMatrix SMatrix{1,1}(log(2))
6+
@test log(@SMatrix [5 2; -2 1])::SMatrix log([5 2; -2 1])
7+
@test log(@SMatrix [4 2; -2 1])::SMatrix log([4 2; -2 1])
8+
@test log(@SMatrix [4 2; 2 1])::SMatrix log([4 2; 2 1])
9+
@test log(@SMatrix [ -3+1im -1+2im;-4-5im 5-2im])::SMatrix log(Complex{Float64}[ -3+1im -1+2im;-4-5im 5-2im])
10+
# test for identity matrix
11+
@test log(SMatrix{2,2}(I))::SMatrix zeros(2,2)
12+
@test log(@SMatrix Complex{Float64}[1 2 0; 2 1 0; 0 0 1]) log([1 2 0; 2 1 0; 0 0 1])
13+
14+
for sz in 0:4, typ in (Float64, Complex{Float64})
15+
A = rand(SMatrix{sz,sz,typ})
16+
expA = exp(A)
17+
logexpA = log(expA)
18+
@test logexpA A
19+
end
20+
end

test/runtests.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ addtests("inv.jl")
5656
addtests("solve.jl")
5757
addtests("eigen.jl")
5858
addtests("expm.jl")
59+
addtests("logm.jl")
5960
addtests("sqrtm.jl")
6061
addtests("lyap.jl")
6162
addtests("lu.jl")

0 commit comments

Comments
 (0)