如何测试矩阵是否为旋转矩阵?

时间:2018-12-17 03:07:19

标签: python numpy rotational-matrices

我有一个检查矩阵是否为旋转矩阵的任务,我编写如下代码:

import numpy as np    

def isRotationMatrix(R):
    # some code here
    # return True or False

R = np.array([
    [0, 0, 1],
    [1, 0, 0],
    [0, 1, 0],
])
print(isRotationMatrix(R))  # Should be True
R = np.array([
    [-1, 0, 0],
    [0, 1, 0],
    [0, 0, 1],
])
print(isRotationMatrix(R))  # Should be False

我不知道如何实现功能isRotationMatrix


我的幼稚工具,仅适用于3x3矩阵:

def isRotationMatrix(R_3x3):
    should_be_norm_one = np.allclose(np.linalg.norm(R_3x3, axis=0), np.ones(shape=3))
    x = R_3x3[:, 0].ravel()
    y = R_3x3[:, 1].ravel()
    z = R_3x3[:, 2].ravel()
    should_be_perpendicular = \
        np.allclose(np.cross(x, y), z) \
        and np.allclose(np.cross(y, z), x) \
        and np.allclose(np.cross(z, x), y)
    return should_be_perpendicular and should_be_norm_one

2 个答案:

答案 0 :(得分:3)

我正在使用this旋转矩阵的定义。旋转矩阵应满足条件M (M^T) = (M^T) M = Idet(M) = I。这里的M^T表示M的转置,I表示单位矩阵,det(M)表示矩阵M的行列式。

您可以使用以下python代码检查矩阵是否为旋转矩阵。

import numpy as np

''' I have chosen `M` as an example. Feel free to put in your own matrix.'''
M = np.array([[0,-1,0],[1,0,0],[0,0,1]]) 

def isRotationMatrix(M):
    tag = False
    I = np.identity(M.shape[0])
    if np.all((np.matmul(M, M.T)) == I) and (np.linalg.det(M)==1): tag = True
    return tag    

if(isRotationMatrix(M)): print 'M is a rotation matrix.'
else: print 'M is not a rotation matrix.'  

答案 1 :(得分:1)

旋转矩阵是orthonormal matrix,其行列式应为1。
我的工具:

import numpy as np


def isRotationMatrix(R):
    # square matrix test
    if R.ndim != 2 or R.shape[0] != R.shape[1]:
        return False
    should_be_identity = np.allclose(R.dot(R.T), np.identity(R.shape[0], np.float))
    should_be_one = np.allclose(np.linalg.det(R), 1)
    return should_be_identity and should_be_one


if __name__ == '__main__':
    R = np.array([
        [0, 0, 1],
        [1, 0, 0],
        [0, 1, 0],
    ])
    print(isRotationMatrix(R))  # True
    R = np.array([
        [-1, 0, 0],
        [0, 1, 0],
        [0, 0, 1],
    ])
    print(isRotationMatrix(R))  # True
    print(isRotationMatrix(np.zeros((3, 2))))  # False