How do you generate a rotation matrix in 3D for some given angle and axis

geometrylinear algebraMATLABmatrices

I like to write a Matlab script to do this but first I need to know myself how this could be done "by hand".

Let's say the axis is $\begin{pmatrix}
1\\
1\\
1
\end{pmatrix}$
and let's say the angle is $\frac{\pi}{4}$. How can I determine a rotation matrix for this given axis and angle?

There is already known rotation around $x$ axis for example by $\alpha$: \begin{pmatrix}
1 & 0 & 0\\
0 & \cos(\alpha) & -\sin(\alpha)\\
0 & \sin(\alpha) & \cos(\alpha)
\end{pmatrix}

I thought maybe I can take my axis $\begin{pmatrix}
1\\
1\\
1
\end{pmatrix}$
and replace it with $x$ axis in that matrix, and set $\alpha=\frac{\pi}{4}$. Buut I don't see how this could be possible here? :/ There must be another way because this one seems wrong way to go.

I'm not asking for Matlab code, I really like to know how this is done "on paper"! 🙂

Best Answer

Proper rotation matrix $\mathbf{R}$ by angle $\theta$ around unit vector $\hat{a} = (a_x, a_y, a_z)$ is $$\mathbf{R} = \left[ \begin{matrix} R_{11} & R_{12} & R_{13} \\ R_{21} & R_{22} & R_{23} \\ R_{31} & R_{32} & R_{33} \\ \end{matrix} \right] = \left[ \begin{matrix} U a_x^2 + C & U a_x a_y - S a_z & U a_x a_z + S a_y \\ U a_x a_y + S a_z & U a_y^2 + C & U a_y a_z - S a_x \\ U a_x a_z - S a_y & U a_y a_z + S a_x & U a_z^2 + C \\ \end{matrix} \right] \tag{1a}\label{G1a}$$ where $$\begin{aligned} C & = \cos\theta \\ S & = \sin\theta \\ U & = 1 - \cos\theta \\ a_x^2 + a_y^2 + a_z^2 & = 1 \\ \end{aligned} \tag{1b}\label{G1b}$$
Note that this assumes column vectors; that vector $\vec{p} = (x, y, z)$ rotated by $\mathbf{R}$ yields $\vec{p}^\prime = (x^\prime, y^\prime, z^\prime)$, $$\vec{p}^\prime = \mathbf{R}\vec{p} \quad \iff \quad \left[\begin{matrix} x^\prime \\ y^\prime \\ z^\prime \end{matrix}\right] = \left[\begin{matrix} R_{11} & R_{12} & R_{13} \\ R_{21} & R_{22} & R_{23} \\ R_{31} & R_{32} & R_{33} \end{matrix} \right] \left[ \begin{matrix} x \\ y \\ z \end{matrix} \right]$$ See e.g. the Wikipedia Rotation matrix article for details.

To combine multiple rotation matrices, multiply them together from right to left, i.e. oldest/first rotation rightmost, last rotation leftmost.

If you have an arbitrary vector $\vec{u} = (u_x, u_y, u_z)$ you wish to use as the axis, you must remember to normalize it to unit length: $$\left\lbrace\begin{aligned} a_x &= \frac{u_x}{\sqrt{u_x^2 + u_y^2 + u_z^2}} \\ a_y &= \frac{u_y}{\sqrt{u_x^2 + u_y^2 + u_z^2}} \\ a_z &= \frac{u_z}{\sqrt{u_x^2 + u_y^2 + u_z^2}} \\ \end{aligned}\right.$$