Rotation Matrix to a Unit Quaternion

~14 mincode completion

Implement matrix_to_quaternion(R) returning the 4-element array [w, x, y, z].

Examples

The identity is the quaternion [1, 0, 0, 0]

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

A 90-degree turn about z: the half angle is 45 degrees

Input
matrix_to_quaternion([[0, -1, 0], [1, 0, 0], [0, 0, 1]])
Output
[0.70711, 0, 0, 0.70711]

A 90-degree turn about x

Input
matrix_to_quaternion([[1, 0, 0], [0, 0, -1], [0, 1, 0]])
Output
[0.70711, 0.70711, 0, 0]

Hints

Hint 1

Take the square root at the end, not inside the sum.

Hint 2

Do not forget to the factor of 4w and divided by 2w. That step is easy to skip.

Requirements

  • R: (3, 3) rotation matrix

  • Return (4,) array [w, x, y, z] with w >= 0

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_quaternion(R):
    """
    Unit quaternion from a rotation matrix, trace(R) > -1.

    Args:
        R: (3, 3) rotation matrix

    Returns:
        (4,) array [w, x, y, z] with w >= 0
    """
    # 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.