# Averaging Quaternions

Previously I used an IMU to measure orientation of a device, and wondered what would be a good way to provide a moving average of the individual attitude observations. One of the forms in which the device library reported orientations is a quaternion form.

Where complex numbers can be visualized on a 2d plane, and multiplication with i is a rotation in this plane, the mathematical object that corresponds to 3d is a quaternion. The book Quaternions for computer graphics by John Vince provides an introduction to quaternions, quaternion algebra and many historic references. Most interesting is rotating a vector p with quaternion q using the product qpq-1, which is clearly explained in the book, including the historic background on the discovery of the half angle coefficients.

The domain of all quaternions, combined with a number of operators, form the quaternion algebra. Both quaternion sum and division by a scalar are defined in this algebra. Does this provide a natural way to calculate the average of a series of attitude observations?

In the paper Averaging quaternions F. Landis Markley et.al. describe two flaws for the simple average using quaternion sum and division by n, and provide an average algorithm without those flaws, using the eigenvector of a matrix composed of the set of quaternions to average.

Tolga Birdal has made a MATLAB implementation of Markley’s algorithm available on github. Since the code only uses matrix operations and not the actual Quaternion MATLAB class, it also works on Octave.