so long as the trace, , is not negative; otherwise, we risk dividing by (nearly) zero. In that case, suppose is the largest diagonal entry, so will have the largest magnitude (the other cases are derived by cyclic permutation); 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. (If is truly a rotation matrix, that value will be 1.) The quaternion so obtained will correspond to the rotation matrix closest to the given matrix (Note: formulation of the cited article is post-multiplied, works with row vectors). 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, Find minimizing , subject to . 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(s), we may employ a standard technique, Lagrange multipliers, assembled as a symmetric matrix, . Thus our method is: Differentiate with respect to (the entries of) , and equate to zero. 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 (and hence ) 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