Skip to content
Open
Show file tree
Hide file tree
Changes from 10 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
22 changes: 22 additions & 0 deletions src/Quaternion.jl
Original file line number Diff line number Diff line change
Expand Up @@ -293,3 +293,25 @@ function slerp(qa::Quaternion{T}, qb::Quaternion{T}, t::T) where {T}
qa.v3 * ratio_a + qm.v3 * ratio_b,
)
end

function _complex_representation(A::Matrix{Quaternion{T}}) where {T}
# convert a quatenion matrix to corresponding complex matrix
a = map(t->t.s, A)
b = map(t->t.v1, A)
c = map(t->t.v2, A)
d = map(t->t.v3, A)

return [a+im*b c+im*d;-c+im*d a-im*b]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently this allocates a lot of intermediate arrays. What about something like this to allocate just 1?

Suggested change
a = map(t->t.s, A)
b = map(t->t.v1, A)
c = map(t->t.v2, A)
d = map(t->t.v3, A)
return [a+im*b c+im*d;-c+im*d a-im*b]
n = size(A, 1)
Ac = Matrix{Complex{T}}(undef, 2n, 2n)
Ac[1:n, 1:n] .= complex.(getfield.(A, :s), getfield.(A, :v1))
Ac[1:n, n+1:2n] .= complex.(getfield.(A, :v2), getfield.(A, :v3))
Ac[n+1:2n, 1:n] .= .- conj.(view(Ac, 1:n, n+1:2n))
Ac[n+1:2n, n+1:2n] .= conj.(view(Ac, 1:n, 1:n))
return Ac

end

function _quaternion_representation(A::Matrix{Complex{T}}) where {T}
n = round(Int, size(A, 1)/2)

X = @view A[1:n, 1:n]
Y = @view A[1:n, n+1:2n]

return [Quaternion(X[i,j].re, X[i,j].im, Y[i,j].re, Y[i,j].im) for i in 1:n, j in 1:n]
end

# A quick way of doing the quaternionic matrix exponential
exp(A::Matrix{Quaternion{T}}) where {T} = _quaternion_representation(exp(_complex_representation(A)))
9 changes: 9 additions & 0 deletions test/test_Quaternion.jl
Original file line number Diff line number Diff line change
Expand Up @@ -138,4 +138,13 @@ for _ in 1:100
@test q ⊗ slerp(q1, q2, t) ≈ slerp(q ⊗ q1, q ⊗ q2, t)
@test q ⊗ linpol(q1, q2, t) ≈ linpol(q ⊗ q1, q ⊗ q2, t)
end
let # test matrix exponential
z = zeros(Quaternion{Float64}, 3, 3)
id = Matrix{Quaternion{Float64}}(I, 3, 3)
d = [Quaternion(randn(4)...) for i in 1:3]
expd = exp.(d)
D = exp(Array(Diagonal(d)))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you include a test for a dense matrix also? Perhaps you could check it using evalpoly.

@test exp(z) ≈ id
@test D ≈ Array(Diagonal(expd))
end
end