# What is the smallest 3D rotation to make the axes line up

A 3x3 rotation matrix is considered axis-aligned if it consists of only 1, -1, and 0. Given an arbitrary rotation matrix, what is the smallest rotation required to make it axis-aligned?

For example, given

$$R=\begin{pmatrix} 0.0281568 & 0.8752862 & 0.4827849\\ 0.9936430 & 0.0281568 & -0.1089990\\ -0.1089990 & 0.4827849 & -0.8689292 \end{pmatrix}$$

The best I can think of is to try to get R closer to identity by permuting and negating the rows, and then compute the angle from identity (by converting to axis-angle form).

So in the example I would multiply R by

$$R'= \begin{pmatrix} 0 & 1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & -1 \end{pmatrix} * R$$

and R' is about 30 degrees away from identity, so the answer is 30.

My method to compute the permutation is rather adhoc. Is there an better way?

It appears that the general solution will require searching. There are 24 possible 3x3 axis-aligned rotations. You could just compute the angle from R to each of these and choose the minimum.

For efficiency, you could reduce the set of possibilities from 24 down to 3 as follows. Add the columns of R together to get the vector m. The signs of the components of m tells you the octant of m and hence the octant that is nearest to R. Each octant has 3 axis-aligned matrices, so you only have to test the angle from R to each of these 3 and choose the minimum. I'm pretty sure the minimum solution will never cause the middle vector, m, to change to a different octant. But I can't prove it.

In the example, the sum of columns is approx $$[1.4, 0.9, -0.5]$$ so the octant is (+ + -). The three axis-aligned rotations in that octant are:

$$I_1 = \begin{pmatrix} 0 & 1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & -1 \end{pmatrix}$$

$$I_2 = \begin{pmatrix} 0 & 0 & -1 \\ 0 & 1 & 0 \\ 1 & 0 & 0 \end{pmatrix}$$ $$I_3 = \begin{pmatrix} 1 & 0 & 0 \\ 0 & 0 & -1 \\ 0 & 1 & 0 \end{pmatrix}$$ Find the angle from R to each of these (using $$R' = I_i^T R$$), and choose the smallest. In this example, it is pretty obvious that $$I_1$$ will be the winner, but another example may be less obvious.

There is a unique matrix that will rotate the three axes of an arbitrary rotation matrix into standard position. And that matrix is just the transpose of the given matrix, because

$$R^T R = I$$