首页 > 解决方案 > 在 Python 中查找两个向量之间的旋转矩阵

问题描述

我正在尝试编写一个代码,为我提供两个向量之间的旋转矩阵。我已经尝试了作为 这个问题的答案给出的代码。我首先让它计算旋转矩阵,然后测试它是否给出正确的答案。但是,它似乎没有给出正确的答案。任何人都可以帮助我为什么无法得到正确的答案吗?

代码如下:

import numpy as np 

def rotation_matrix_from_vectors(vec1, vec2):

    a, b = (vec1 / np.linalg.norm(vec1)).reshape(3), (vec2 / np.linalg.norm(vec2)).reshape(3)
    v = np.cross(a, b)
    c = np.dot(a, b)
    s = np.linalg.norm(v)
    kmat = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])
    rotation_matrix = np.eye(3) + kmat + kmat.dot(kmat) * ((1 - c) / (s ** 2))
    return rotation_matrix

#from here it is the code I have written to test this function
vector1 = array([0,1,0])
vector2 = array([-1,0,1])

rot = rotation_matrix_from_vectors(vector1,vector2)
rotated = np.dot(rot,vector1)

print(rotated)

这将打印矢量 [-0.707, 0, 0.707] 而不是 [-1, 0, 1]。

标签: pythonlinear-algebra

解决方案


推荐阅读