Advertisement
Guest User

Rotation matrix computation

a guest
Dec 2nd, 2018
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Julia 2.06 KB | None | 0 0
  1. using LinearAlgebra
  2.  
  3. """
  4.    quadraticSolver(A, b, x)
  5.  
  6. Solves an equation system of the form:
  7.  
  8.    forall k in 1..n sum_{i=1}^n sum_{j=1}^n a_{kij} x_i x_j = b_k
  9.  
  10. Uses Newton's method; the optimization starts from `x`.
  11. """
  12. function quadraticSolver(A, b, x)
  13.     tolerance = 1.0e-8
  14.     maxiter = 100
  15.     n = length(A)
  16.     for _ in 1:maxiter
  17.         D = zeros(n, n)
  18.         f = -b
  19.         for k in 1:n, i in 1:n, j in 1:n
  20.             f[k] += A[k][i,j] * x[i] * x[j]
  21.         end
  22.         for k in 1:n, l in 1:n
  23.             D[k,l] = 2 * A[k][l,l] * x[l]
  24.             for i in 1:n
  25.                 D[k,l] += (A[k][i,l] + A[k][l,i]) * x[i]
  26.             end
  27.         end
  28.         delta = inv(D) * f
  29.         norm(delta) < tolerance && break
  30.         x -= delta
  31.     end
  32.     x
  33. end
  34.  
  35. """
  36.    findMatrix(p, n)
  37.  
  38. `e` and `n` are vectors of three 3D vectors.
  39. Returns a rotation matrix s.t. n[i]'*R*e[i] == 0.
  40. """
  41. function findMatrix(e, n)
  42.     # Set up the quaternion equations
  43.     A = [Matrix{Float64}(I, 4, 4)]
  44.     for i in 1:3
  45.         E = [   0    -e[i][1] -e[i][2] -e[i][3]
  46.              e[i][1]     0     e[i][3] -e[i][2]
  47.              e[i][2] -e[i][3]     0     e[i][1]
  48.              e[i][3]  e[i][2] -e[i][1]     0   ]
  49.         N = [   0    -n[i][1] -n[i][2] -n[i][3]
  50.              n[i][1]     0    -n[i][3]  n[i][2]
  51.              n[i][2]  n[i][3]     0    -n[i][1]
  52.              n[i][3] -n[i][2]  n[i][1]     0   ]
  53.         push!(A, E' * N)
  54.    end
  55.    b = [1., 0, 0, 0]
  56.    # Compute q such that q' * A[i] * q = b[i], i = 1..4
  57.     q = quadraticSolver(A, b, [1., 0, 0, 0])
  58.     # Convert q to rotation matrix form
  59.     [q[1]^2+q[2]^2-q[3]^2-q[4]^2 2(q[2]*q[3]-q[1]*q[4])      2(q[2]*q[4]+q[1]*q[3])
  60.      2(q[2]*q[3]+q[1]*q[4])      q[1]^2+q[3]^2-q[2]^2-q[4]^2 2(q[3]*q[4]-q[1]*q[2])
  61.      2(q[2]*q[4]-q[1]*q[3])      2(q[3]*q[4]+q[1]*q[2])      q[1]^2+q[4]^2-q[2]^2-q[3]^2]
  62. end
  63.  
  64. function test()
  65.     e = [normalize(rand(3)) for _ in 1:3]
  66.     n = [normalize(rand(3)) for _ in 1:3]
  67.     R = findMatrix(e, n)
  68.     println("Error: $(sum(i -> abs(dot(n[i], R * e[i])), 1:3))")
  69. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement