Rotation Matrix to Axis and Angle

~14 mincode completion

Implement matrix_to_axis_angle(R) returning the 4-element array [kx, ky, kz, angle]. Return [0, 0, 1, 0] when the rotation is (numerically) the identity.

Examples

The identity: zero angle, the default axis, no division by zero

Input
matrix_to_axis_angle([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
Output
[0, 0, 1, 0]

A 90-degree turn about z

Input
matrix_to_axis_angle([[0, -1, 0], [1, 0, 0], [0, 0, 1]])
Output
[0, 0, 1, 1.5708]

A 60-degree turn about x

Input
matrix_to_axis_angle([[1, 0, 0], [0, 0.5, -0.8660254037844386], [0, 0.8660254037844386, 0.5]])
Output
[1, 0, 0, 1.0472]

Hints

Hint 1

bounds an array in one call.

Hint 2

A common slip here: divided the skew part by 2 instead of 2 sin theta.

Requirements

  • R: (3, 3) rotation matrix with rotation angle in [0, pi)

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~14 min

6 employers weight this skill

4 autonomy companies, 2 defense companies. Top match scores 92.

Python
import numpy as np


def matrix_to_axis_angle(R):
    """
    Recover the rotation axis and angle from a rotation matrix.

    Args:
        R: (3, 3) rotation matrix with rotation angle in [0, pi)

    Returns:
        (4,) array [kx, ky, kz, angle], unit axis, angle in radians.
        [0, 0, 1, 0] when R is the identity.
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.