Rotation matrix


In linear algebra, a rotation matrix is a matrix that is used to perform a rotation in Euclidean space. For example, using the convention below, the matrix
rotates points in the -plane counterclockwise through an angle with respect to the axis about the origin of a two-dimensional Cartesian coordinate system. To perform the rotation on a plane point with standard coordinates =, it should be written as a column vector, and multiplied by the matrix R:
The examples in this article apply to active rotations of vectors counterclockwise in a right-handed coordinate system by pre-multiplication. If any one of these is changed, then the inverse of the example matrix should be used, which coincides with its transpose.
Since matrix multiplication has no effect on the zero vector, rotation matrices describe rotations about the origin. Rotation matrices provide an algebraic description of such rotations, and are used extensively for computations in geometry, physics, and computer graphics. In some literature, the term rotation is generalized to include improper rotations, characterized by orthogonal matrices with determinant −1. These combine proper rotations with reflections. In other cases, where reflections are not being considered, the label proper may be dropped. The latter convention is followed in this article.
Rotation matrices are square matrices, with real entries. More specifically, they can be characterized as orthogonal matrices with determinant 1; that is, a square matrix is a rotation matrix if and only if and. The set of all orthogonal matrices of size with determinant +1 forms a group known as the special orthogonal group, one example of which is the rotation group SO. The set of all orthogonal matrices of size with determinant +1 or −1 forms the orthogonal group.

In two dimensions

In two dimensions, the standard rotation matrix has the following form:
This rotates column vectors by means of the following matrix multiplication,
Thus, the new coordinates of a point after rotation are

Examples

For example, when the vector is rotated by an angle, its new coordinates are,
and when the vector is rotated by an angle, its new coordinates are

Direction

The direction of vector rotation is counterclockwise if is positive, and clockwise if is negative. Thus the clockwise rotation matrix is found as
The two-dimensional case is the only non-trivial case where the rotation matrices group is commutative, so that it does not matter in which order multiple rotations are performed. An alternative convention uses rotating axes, and the above matrices also represent a rotation of the axes clockwise through an angle.

Non-standard orientation of the coordinate system

If a standard right-handed Cartesian coordinate system is used, with the to the right and the up, the rotation is counterclockwise. If a left-handed Cartesian coordinate system is used, with directed to the right but directed down, is clockwise. Such non-standard orientations are rarely used in mathematics but are common in 2D computer graphics, which often have the origin in the top left corner and the down the screen or page.
See below for other alternative conventions which may change the sense of the rotation produced by a rotation matrix.

Common rotations

Particularly useful are the matrices,, for 90°, 180°, and 270° counter-clockwise rotations.

Complex planes in M(2, ℝ)

Since the plane of matrices is isomorphic to the complex number plane ℂ, and the above rotation matrix is a point on its unit circle, which acts on the plane as a rotation of θ radians.
Let It can be shown that the negative of the identity matrix, and is a plane of matrices isomorphic to ℂ. Then according to Euler's formula, any
For more details on the number planes in M and their types of rotations, see 2 × 2 real matrices.

In three dimensions

Basic rotations

A basic rotation is a rotation about one of the axes of a coordinate system. The following three basic rotation matrices rotate vectors by an angle about the -, -, or -axis, in three dimensions, using the right-hand rule—which codifies their alternating signs.
For column vectors, each of these basic vector rotations appears counterclockwise when the axis about which they occur points toward the observer, the coordinate system is right-handed, and the angle is positive., for instance, would rotate toward the a vector aligned with the, as can easily be checked by operating with on the vector :
This is similar to the rotation produced by the above-mentioned two-dimensional rotation matrix. See below for alternative conventions which may apparently or actually invert the sense of the rotation produced by these matrices.

General rotations

Other rotation matrices can be obtained from these three using matrix multiplication. For example, the product
represents a rotation whose yaw, pitch, and roll angles are, and, respectively. More formally, it is an intrinsic rotation whose Tait–Bryan angles are,,, about axes,,, respectively.
Similarly, the product
represents an extrinsic rotation whose Euler angles are,,, about axes,,.
These matrices produce the desired effect only if they are used to premultiply column vectors, and only if they are applied in the specified order.

Conversion from and to axis–angle

Every rotation in three dimensions is defined by its axis, and its angle — the amount of rotation about that axis.
There are several methods to compute the axis and angle from a rotation matrix. Here, we only describe the method based on the computation of the eigenvectors and eigenvalues of the rotation matrix. It is also possible to use the trace of the rotation matrix.

Determining the axis

Given a rotation matrix, a vector parallel to the rotation axis must satisfy
since the rotation of around the rotation axis must result in. The equation above may be solved for which is unique up to a scalar factor unless.
Further, the equation may be rewritten
which shows that lies in the null space of.
Viewed in another way, is an eigenvector of corresponding to the eigenvalue. Every rotation matrix must have this eigenvalue, the other two eigenvalues being complex conjugates of each other. It follows that a general rotation matrix in three dimensions has, up to a multiplicative constant, only one real eigenvector.
One way to determine the rotation axis is by showing that:
Since is a skew-symmetric matrix, we can choose such that
The matrix–vector product becomes a cross product of a vector with itself, ensuring that the result is zero:
Therefore, if
then
The magnitude of computed this way is, where is the angle of rotation.
This does not work if is symmetric. Above, if is zero, then all subsequent steps are invalid. In this case, it is necessary to diagonalize and find the eigenvector corresponding to an eigenvalue of 1.

Determining the angle

To find the angle of a rotation, once the axis of the rotation is known, select a vector perpendicular to the axis. Then the angle of the rotation is the angle between and .
A more direct method, however, is to simply calculate the trace, i.e., the sum of the diagonal elements of the rotation matrix. Care should be taken to select the right sign for the angle to match the chosen axis:
from which follows that the angle's absolute value is

Rotation matrix from axis and angle

The matrix of a proper rotation R by angle θ around the axis, a unit vector with, is given by:
A derivation of this matrix from first principles can be found in section 9.2 here. The basic idea to derive this matrix is dividing the problem into few known simple steps.
  1. First rotate the given axis and the point such that the axis lies in one of the coordinate planes
  2. Then rotate the given axis and the point such that the axis is aligned with one of the two coordinate axes for that particular coordinate plane
  3. Use one of the fundamental rotation matrices to rotate the point depending on the coordinate axis with which the rotation axis is aligned.
  4. Reverse rotate the axis-point pair such that it attains the final configuration as that was in step 2
  5. Reverse rotate the axis-point pair which was done in step 1
This can be written more concisely as
where is the cross product matrix of ; the expression is the outer product, and is the identity matrix. Alternatively, the coordinates are:
where is the Levi-Civita symbol with. This is a matrix form of Rodrigues' rotation formula, with
In the rotation of a vector around the axis by an angle can be written as:
If the 3D space is right-handed and, this rotation will be counterclockwise when points towards the observer.
Note the striking merely apparent differences to the equivalent Lie-algebraic formulation below.

Properties

For any -dimensional rotation matrix acting on,
It follows that:
A rotation is termed proper if det R = 1, and improper if det R = –1. For even dimensions n = 2k, the n eigenvalues λ of a proper rotation occur as pairs of complex conjugates which are roots of unity: for j = 1,..., k, which is real only for. Therefore, there may be no vectors fixed by the rotation, and thus no axis of rotation. Any fixed eigenvectors occur in pairs, and the axis of rotation is an even-dimensional subspace.
For odd dimensions n = 2k + 1, a proper rotation R will have an odd number of eigenvalues, with at least one and the axis of rotation will be an odd dimensional subspace. Proof:
Here I is the identity matrix, and we use that , as well as since n is odd. Therefore, det = 0, meaning there is a null vector v with = 0, i.e. R = v, a fixed eigenvector. There may also be pairs of fixed eigenvectors in the even-dimensional subspace orthogonal to v, so the total dimension of fixed eigenvectors is odd.
For example, in 2-space n = 2, a rotation by angle θ has eigenvalues, so there is no axis of rotation except when θ = 0, the case of the null rotation. In 3-space n = 3, the axis of a non-null proper rotation is always a unique line, and a rotation around this axis by angle θ has eigenvalues. In 4-space n = 4, the four eigenvalues are of the form. The null rotation has. The case of is called a simple rotation, with two unit eigenvalues forming an axis plane, and a two-dimensional rotation orthogonal to the axis plane. Otherwise, there is no axis plane. The case of is called an isoclinic rotation, having eigenvalues, each repeated twice, so every vector is rotated through an angle θ.
The trace of a rotation matrix is equal to the sum of its eigenvalues. For n = 2, a rotation by angle θ has trace 2 cos θ. For n = 3, a rotation around any axis by angle θ has trace 1 + 2 cos θ. For n = 4, and the trace is, which becomes 4 cos θ for an isoclinic rotation.

Examples

In Euclidean geometry, a rotation is an example of an isometry, a transformation that moves points without changing the distances between them. Rotations are distinguished from other isometries by two additional properties: they leave one point fixed, and they leave "handedness" unchanged. By contrast, a translation moves every point, a reflection exchanges left- and right-handed ordering, and a glide reflection does both.
A rotation that does not leave handedness unchanged is an improper rotation or a rotoinversion.
If a fixed point is taken as the origin of a Cartesian coordinate system, then every point can be given coordinates as a displacement from the origin. Thus one may work with the vector space of displacements instead of the points themselves. Now suppose are the coordinates of the vector from the origin to point. Choose an orthonormal basis for our coordinates; then the squared distance to, by Pythagoras, is
which can be computed using the matrix multiplication
A geometric rotation transforms lines to lines, and preserves ratios of distances between points. From these properties it can be shown that a rotation is a linear transformation of the vectors, and thus can be written in matrix form,. The fact that a rotation preserves, not just ratios, but distances themselves, is stated as
or
Because this equation holds for all vectors,, one concludes that every rotation matrix,, satisfies the orthogonality condition,
Rotations preserve handedness because they cannot change the ordering of the axes, which implies the special matrix condition,
Equally important, it can be shown that any matrix satisfying these two conditions acts as a rotation.

Multiplication

The inverse of a rotation matrix is its transpose, which is also a rotation matrix:
The product of two rotation matrices is a rotation matrix:
For, multiplication of rotation matrices is generally not commutative.
Noting that any identity matrix is a rotation matrix, and that matrix multiplication is associative, we may summarize all these properties by saying that the rotation matrices form a group, which for is non-abelian, called a special orthogonal group, and denoted by,,, or, the group of rotation matrices is isomorphic to the group of rotations in an space. This means that multiplication of rotation matrices corresponds to composition of rotations, applied in left-to-right order of their corresponding matrices.

Ambiguities

The interpretation of a rotation matrix can be subject to many ambiguities.
In most cases the effect of the ambiguity is equivalent to the effect of a rotation matrix inversion.
; Alias or alibi transformation
; Pre-multiplication or post-multiplication
; Right- or left-handed coordinates
; Vectors or forms

Decompositions

Independent planes

Consider the rotation matrix
If acts in a certain direction,, purely as a scaling by a factor, then we have
so that
Thus is a root of the characteristic polynomial for,
Two features are noteworthy. First, one of the roots is 1, which tells us that some direction is unaffected by the matrix. For rotations in three dimensions, this is the axis of the rotation. Second, the other two roots are a pair of complex conjugates, whose product is 1, and whose sum is . This factorization is of interest for rotation matrices because the same thing occurs for all of them. Furthermore, a similar factorization holds for any rotation matrix. If the dimension,, is odd, there will be a "dangling" eigenvalue of 1; and for any dimension the rest of the polynomial factors into quadratic terms like the one here. We are guaranteed that the characteristic polynomial will have degree and thus eigenvalues. And since a rotation matrix commutes with its transpose, it is a normal matrix, so can be diagonalized. We conclude that every rotation matrix, when expressed in a suitable coordinate system, partitions into independent rotations of two-dimensional subspaces, at most of them.
The sum of the entries on the main diagonal of a matrix is called the trace; it does not change if we reorient the coordinate system, and always equals the sum of the eigenvalues. This has the convenient implication for and rotation matrices that the trace reveals the angle of rotation,, in the two-dimensional space. For a matrix the trace is, and for a matrix it is. In the three-dimensional case, the subspace consists of all vectors perpendicular to the rotation axis. Thus we can extract from any rotation matrix a rotation axis and an angle, and these completely determine the rotation.

Sequential angles

The constraints on a rotation matrix imply that it must have the form
with. Therefore, we may set and, for some angle. To solve for it is not enough to look at alone or alone; we must consider both together to place the angle in the correct quadrant, using a two-argument arctangent function.
Now consider the first column of a rotation matrix,
Although will probably not equal 1, but some value, we can use a slight variation of the previous computation to find a so-called Givens rotation that transforms the column to
zeroing. This acts on the subspace spanned by the - and -axes. We can then repeat the process for the -subspace to zero. Acting on the full matrix, these two rotations produce the schematic form
Shifting attention to the second column, a Givens rotation of the -subspace can now zero the value. This brings the full matrix to the form
which is an identity matrix. Thus we have decomposed as
An rotation matrix will have, or
entries below the diagonal to zero. We can zero them by extending the same idea of stepping through the columns with a series of rotations in a fixed sequence of planes. We conclude that the set of rotation matrices, each of which has entries, can be parameterized by angles.
In three dimensions this restates in matrix form an observation made by Euler, so mathematicians call the ordered sequence of three angles Euler angles. However, the situation is somewhat more complicated than we have so far indicated. Despite the small dimension, we actually have considerable freedom in the sequence of axis pairs we use; and we also have some freedom in the choice of angles. Thus we find many different conventions employed when three-dimensional rotations are parameterized for physics, or medicine, or chemistry, or other disciplines. When we include the option of world axes or body axes, 24 different sequences are possible. And while some disciplines call any sequence Euler angles, others give different names to different sequences.
One reason for the large number of options is that, as noted previously, rotations in three dimensions do not commute. If we reverse a given sequence of rotations, we get a different outcome. This also implies that we cannot compose two rotations by adding their corresponding angles. Thus Euler angles are not vectors, despite a similarity in appearance as a triplet of numbers.

Nested dimensions

A rotation matrix such as
suggests a rotation matrix,
is embedded in the upper left corner:
This is no illusion; not just one, but many, copies of -dimensional rotations are found within -dimensional rotations, as subgroups. Each embedding leaves one direction fixed, which in the case of matrices is the rotation axis. For example, we have
fixing the -axis, the -axis, and the -axis, respectively. The rotation axis need not be a coordinate axis; if is a unit vector in the desired direction, then
where,, is a rotation by angle leaving axis fixed.
A direction in -dimensional space will be a unit magnitude vector, which we may consider a point on a generalized sphere,. Thus it is natural to describe the rotation group as combining and. A suitable formalism is the fiber bundle,
where for every direction in the base space,, the fiber over it in the total space,, is a copy of the fiber space,, namely the rotations that keep that direction fixed.
Thus we can build an rotation matrix by starting with a matrix, aiming its fixed axis on , aiming the resulting rotation on, and so on up through. A point on can be selected using numbers, so we again have numbers to describe any rotation matrix.
In fact, we can view the sequential angle decomposition, discussed previously, as reversing this process. The composition of Givens rotations brings the first column to, so that the remainder of the matrix is a rotation matrix of dimension one less, embedded so as to leave fixed.

Skew parameters via Cayley's formula

When an rotation matrix, does not include a −1 eigenvalue, thus none of the planar rotations which it comprises are 180° rotations, then is an invertible matrix. Most rotation matrices fit this description, and for them it can be shown that is a skew-symmetric matrix,. Thus ; and since the diagonal is necessarily zero, and since the upper triangle determines the lower one, contains independent numbers.
Conveniently, is invertible whenever is skew-symmetric; thus we can recover the original matrix using the Cayley transform,
which maps any skew-symmetric matrix to a rotation matrix. In fact, aside from the noted exceptions, we can produce any rotation matrix in this way. Although in practical applications we can hardly afford to ignore 180° rotations, the Cayley transform is still a potentially useful tool, giving a parameterization of most rotation matrices without trigonometric functions.
In three dimensions, for example, we have
If we condense the skew entries into a vector,, then we produce a 90° rotation around the -axis for, around the -axis for, and around the -axis for. The 180° rotations are just out of reach; for, in the limit as, does approach a 180° rotation around the axis, and similarly for other directions.

Decomposition into shears

For the 2D case, a rotation matrix can be decomposed into three shear matrices :
This is useful, for instance, in computer graphics, since shears can be implemented with fewer multiplication instructions than rotating a bitmap directly. On modern computers, this may not matter, but it can be relevant for very old or low-end microprocessors.
A rotation can also be written as two shears and scaling :

Group theory

Below follow some basic facts about the role of the collection of all rotation matrices of a fixed dimension in mathematics and particularly in physics where rotational symmetry is a requirement of every truly fundamental law, and where the same symmetry, when present, is a simplifying property of many problems of less fundamental nature. Examples abound in classical mechanics and quantum mechanics. Knowledge of the part of the solutions pertaining to this symmetry applies to all such problems and it can be factored out of a specific problem at hand, thus reducing its complexity. A prime example - in mathematics and physics - would be the theory of spherical harmonics. Their role in the group theory of the rotation groups is that of being a representation space for the entire set of finite-dimensional irreducible representations of the rotation group SO. For this topic, see Rotation group SO § Spherical harmonics.
The main articles listed in each subsection are referred to for more detail.

Lie group

The rotation matrices for each form a group, the special orthogonal group,. This algebraic structure is coupled with a topological structure inherited from in such a way that the operations of multiplication and taking the inverse are analytic functions of the matrix entries. Thus is for each a Lie group. It is compact and connected, but not simply connected. It is also a semi-simple group, in fact a simple group with the exception SO. The relevance of this is that all theorems and all machinery from the theory of analytic manifolds apply and the well-developed representation theory of compact semi-simple groups is ready for use.

Lie algebra

The Lie algebra of is given by
and is the space of skew-symmetric matrices of dimension, see classical group, where is the Lie algebra of, the orthogonal group. For reference, the most common basis for is

Exponential map

Connecting the Lie algebra to the Lie group is the exponential map, which is defined using the standard matrix exponential series for For any skew-symmetric matrix, is always a rotation matrix.
An important practical example is the case. In rotation group SO, it is shown that one can identify every with an Euler vector, where is a unit magnitude vector.
By the properties of the identification, is in the null space of. Thus, is left invariant by and is hence a rotation axis.
According to Rodrigues' rotation formula on matrix form, one obtains,
where
This is the matrix for a rotation around axis by the angle. For full detail, see exponential map SO.

Baker–Campbell–Hausdorff formula

The BCH formula provides an explicit expression for in terms of a series expansion of nested commutators of and. This general expansion unfolds as
In the case, the general infinite expansion has a compact form,
for suitable trigonometric function coefficients, detailed in the Baker–Campbell–Hausdorff formula for SO.
As a group identity, the above holds for all faithful representations, including the doublet, which is simpler. The same explicit formula thus follows straightforwardly through Pauli matrices; see the derivation for SU. For the general case, one might use Ref.

Spin group

The Lie group of rotation matrices,, is not simply connected, so Lie theory tells us it is a homomorphic image of a universal covering group. Often the covering group, which in this case is called the spin group denoted by, is simpler and more natural to work with.
In the case of planar rotations, SO is topologically a circle,. Its universal covering group, Spin, is isomorphic to the real line,, under addition. Whenever angles of arbitrary magnitude are used one is taking advantage of the convenience of the universal cover. Every rotation matrix is produced by a countable infinity of angles, separated by integer multiples of 2. Correspondingly, the fundamental group of is isomorphic to the integers,.
In the case of spatial rotations, SO is topologically equivalent to three-dimensional real projective space,. Its universal covering group, Spin, is isomorphic to the,. Every rotation matrix is produced by two opposite points on the sphere. Correspondingly, the fundamental group of SO is isomorphic to the two-element group,.
We can also describe Spin as isomorphic to quaternions of unit norm under multiplication, or to certain real matrices, or to complex special unitary matrices, namely SU. The covering maps for the first and the last case are given by
and
For a detailed account of the and the quaternionic covering, see spin group SO.
Many features of these cases are the same for higher dimensions. The coverings are all two-to-one, with,, having fundamental group. The natural setting for these groups is within a Clifford algebra. One type of action of the rotations is produced by a kind of "sandwich", denoted by. More importantly in applications to physics, the corresponding spin representation of the Lie algebra sits inside the Clifford algebra. It can be exponentiated in the usual way to give rise to a representation, also known as projective representation of the rotation group. This is the case with SO and SU, where the representation can be viewed as an "inverse" of the covering map. By properties of covering maps, the inverse can be chosen ono-to-one as a local section, but not globally.

Infinitesimal rotations

The matrices in the Lie algebra are not themselves rotations; the skew-symmetric matrices are derivatives, proportional differences of rotations. An actual "differential rotation", or infinitesimal rotation matrix has the form
where is vanishingly small and, for instance with,
The computation rules are as usual except that infinitesimals of second order are routinely dropped. With these rules, these matrices do not satisfy all the same properties as ordinary finite rotation matrices under the usual treatment of infinitesimals. It turns out that the order in which infinitesimal rotations are applied is irrelevant. To see this exemplified, consult infinitesimal rotations SO.

Conversions

We have seen the existence of several decompositions that apply in any dimension, namely independent planes, sequential angles, and nested dimensions. In all these cases we can either decompose a matrix or construct one. We have also given special attention to rotation matrices, and these warrant further attention, in both directions.

Quaternion

Given the unit quaternion, the equivalent left-handed rotation matrix is
Now every quaternion component appears multiplied by two in a term of degree two, and if all such terms are zero what is left is an identity matrix. This leads to an efficient, robust conversion from any quaternion – whether unit or non-unit – to a rotation matrix. Given:
we can calculate
Freed from the demand for a unit quaternion, we find that nonzero quaternions act as homogeneous coordinates for rotation matrices. The Cayley transform, discussed earlier, is obtained by scaling the quaternion so that its component is 1. For a 180° rotation around any axis, will be zero, which explains the Cayley limitation.
The sum of the entries along the main diagonal, plus one, equals, which is. Thus we can write the trace itself as ; and from the previous version of the matrix we see that the diagonal entries themselves have the same form:,, and. So we can easily compare the magnitudes of all four quaternion components using the matrix diagonal. We can, in fact, obtain all four magnitudes using sums and square roots, and choose consistent signs using the skew-symmetric part of the off-diagonal entries:
where is with the sign of, that is
Alternatively, use a single square root and division
This is numerically stable so long as the trace,, is not negative; otherwise, we risk dividing by zero. In that case, suppose is the largest diagonal entry, so will have the largest magnitude ; then the following is safe.
If the matrix contains significant error, such as accumulated numerical error, we may construct a symmetric matrix,
and find the eigenvector,, of its largest magnitude eigenvalue. The quaternion so obtained will correspond to the rotation matrix closest to the given matrix.

Polar decomposition

If the matrix is nonsingular, its columns are linearly independent vectors; thus the Gram–Schmidt process can adjust them to be an orthonormal basis. Stated in terms of numerical linear algebra, we convert to an orthogonal matrix,, using QR decomposition. However, we often prefer a closest to, which this method does not accomplish. For that, the tool we want is the polar decomposition.
To measure closeness, we may use any matrix norm invariant under orthogonal transformations. A convenient choice is the Frobenius norm,, squared, which is the sum of the squares of the element differences. Writing this in terms of the trace,, our goal is,
Though written in matrix terms, the objective function is just a quadratic polynomial. We can minimize it in the usual way, by finding where its derivative is zero. For a matrix, the orthogonality constraint implies six scalar equalities that the entries of must satisfy. To incorporate the constraint, we may employ a standard technique, Lagrange multipliers, assembled as a symmetric matrix,. Thus our method is:

Consider a example. Including constraints, we seek to minimize
Taking the derivative with respect to,,, in turn, we assemble a matrix.

In general, we obtain the equation
so that
where is orthogonal and is symmetric. To ensure a minimum, the matrix must be positive definite. Linear algebra calls the polar decomposition of, with the positive square root of.
When is non-singular, the and factors of the polar decomposition are uniquely determined. However, the determinant of is positive because is positive definite, so inherits the sign of the determinant of. That is, is only guaranteed to be orthogonal, not a rotation matrix. This is unavoidable; an with negative determinant has no uniquely defined closest rotation matrix.

Axis and angle

To efficiently construct a rotation matrix from an angle and a unit axis, we can take advantage of symmetry and skew-symmetry within the entries. If,, and are the components of the unit vector representing the axis, and
then
Determining an axis and angle, like determining a quaternion, is only possible up to the sign; that is, and correspond to the same rotation matrix, just like and. Additionally, axis–angle extraction presents additional difficulties. The angle can be restricted to be from 0° to 180°, but angles are formally ambiguous by multiples of 360°. When the angle is zero, the axis is undefined. When the angle is 180°, the matrix becomes symmetric, which has implications in extracting the axis. Near multiples of 180°, care is needed to avoid numerical problems: in extracting the angle, a two-argument arctangent with equal to avoids the insensitivity of arccos; and in computing the axis magnitude in order to force unit magnitude, a brute-force approach can lose accuracy through underflow.
A partial approach is as follows:
The -, -, and -components of the axis would then be divided by. A fully robust approach will use a different algorithm when, the trace of the matrix, is negative, as with quaternion extraction. When is zero because the angle is zero, an axis must be provided from some source other than the matrix.

Euler angles

Complexity of conversion escalates with Euler angles. The first difficulty is to establish which of the twenty-four variations of Cartesian axis order we will use. Suppose the three angles are,, ; physics and chemistry may interpret these as
while aircraft dynamics may use
One systematic approach begins with choosing the rightmost axis. Among all permutations of, only two place that axis first; one is an even permutation and the other odd. Choosing parity thus establishes the middle axis. That leaves two choices for the left-most axis, either duplicating the first or not. These three choices gives us variations; we double that to 24 by choosing static or rotating axes.
This is enough to construct a matrix from angles, but triples differing in many ways can give the same rotation matrix. For example, suppose we use the convention above; then we have the following equivalent pairs:
Angles for any order can be found using a concise common routine.
The problem of singular alignment, the mathematical analog of physical gimbal lock, occurs when the middle rotation aligns the axes of the first and last rotations. It afflicts every axis order at either even or odd multiples of 90°. These singularities are not characteristic of the rotation matrix as such, and only occur with the usage of Euler angles.
The singularities are avoided when considering and manipulating the rotation matrix as orthonormal row vectors instead of as angles. The singularities are also avoided when working with quaternions.

Uniform random rotation matrices

We sometimes need to generate a uniformly distributed random rotation matrix. It seems intuitively clear in two dimensions that this means the rotation angle is uniformly distributed between 0 and 2. That intuition is correct, but does not carry over to higher dimensions. For example, if we decompose rotation matrices in axis–angle form, the angle should not be uniformly distributed; the probability that the angle is at most should be, for.
Since is a connected and locally compact Lie group, we have a simple standard criterion for uniformity, namely that the distribution be unchanged when composed with any arbitrary rotation. This definition corresponds to what is called Haar measure. show how to use the Cayley transform to generate and test matrices according to this criterion.
We can also generate a uniform distribution in any dimension using the subgroup algorithm of. This recursively exploits the nested dimensions group structure of, as follows. Generate a uniform angle and construct a rotation matrix. To step from to, generate a vector uniformly distributed on the -sphere, embed the matrix in the next larger size with last column, and rotate the larger matrix so the last column becomes.
As usual, we have special alternatives for the case. Each of these methods begins with three independent random scalars uniformly distributed on the unit interval. takes advantage of the odd dimension to change a Householder reflection to a rotation by negation, and uses that to aim the axis of a uniform planar rotation.
Another method uses unit quaternions. Multiplication of rotation matrices is homomorphic to multiplication of quaternions, and multiplication by a unit quaternion rotates the unit sphere. Since the homomorphism is a local isometry, we immediately conclude that to produce a uniform distribution on SO we may use a uniform distribution on. In practice: create a four-element vector where each element is a sampling of a normal distribution. Normalize its length and you have a uniformly sampled random unit quaternion which represents a uniformly sampled random rotation. Note that the aforementioned only applies to rotations in dimension 3. For a generalised idea of quaternions, one should look into Rotors.
Euler angles can also be used, though not with each angle uniformly distributed.
For the axis–angle form, the axis is uniformly distributed over the unit sphere of directions,, while the angle has the nonuniform distribution over noted previously.

Remarks