# spacepy.coordinates.quaternionFromMatrix

`spacepy.coordinates.``quaternionFromMatrix`(matrix, scalarPos='last')

  Given an input rotation matrix, return the equivalent quaternion

  The output has one fewer axis than the input (the last axis) and the shape is otherwise unchanged, allowing multi-dimensional matrix input.

  Parameters
    matrix array_like

      input rotation matrix or array of matrices

  Returns
    out array_like

      Quaternions representing the same rotation as the input rotation matrices.

  Other Parameters
    scalarPos str

      Location of the scalar component of the output quaternion, either ‘last’ (default) or ‘first’.

  Raises
    NotImplementedError

      for invalid values of `scalarPos`

    ValueError

      for inputs which are obviously not valid 3D rotation matrices or arrays thereof: if the size doesn’t end in (3, 3), if the matrix is not orthogonal, or not a proper rotation.

  See also

  `quaternionToMatrix`

  Notes

  New in version 0.2.2.

  No attempt is made to resolve the sign ambiguity; in particular, conversions of very similar matrices may result in equivalent quaternions with the opposite sign. This may have implications for interpolating a sequence of quaternions.

  The conversion of a rotation matrix to a quaternion suffers from some of the same disadvantages inherent to rotation matrices, such as potential numerical instabilities. Working in quaternion space as much as possible is recommended.

  There are several algorithms; the most well-known algorithm for this conversion is Shepperd’s 1, although the many “rediscoveries” indicate it is not sufficiently well-known. This function uses the method of Bar-Itzhack 2 (version 3), which should be resistant to small errors in the rotation matrix. As a result, the input checking is quite coarse and will likely accept many matrices that do not represent valid rotations.

  Also potentially of interest, although not implemented here, is Sarabandi and Thomas 3.

  References

  1

    S.W. Shepperd, “Quaternion from rotation matrix,” Journal of Guidance and Control, Vol. 1, No. 3, pp. 223-224, 1978, doi:10.2514/3.55767b

  2

    I. Y. Bar-Itzhack, “New method for extracting the quaternion from a rotation matrix”, AIAA Journal of Guidance, Control and Dynamics, 23 (6): 1085–1087, doi:10.2514/2.4654

  3

    S. Sarabandi and F. Thomas, “Accurate Computation of Quaternions from Rotation Matrices”, In: Lenarcic J., Parenti-Castelli V. (eds) Advances in Robot Kinematics 2018, Springer. doi:10.1007/978-3-319-93188-3_5

  Examples

      >>> import spacepy.coordinates
      >>> spacepy.coordinates.quaternionFromMatrix(
      ...     [[ 0.,  0.,  1.],
      ...      [ 1.,  0.,  0.],
      ...      [ 0.,  1.,  0.]])
      array([0.5, 0.5, 0.5, 0.5])