I've been reading the wikipedia page on rotation matrices and I know the reverse (or at least a very related) version of this question has been asked many times before on this site. However my high-school trig is failing me.
I have a three axis magnometer. It can sense the earth's magnetic field on each axis. I also have a three axis accelerometer. It can sense the earth's gravitational pull in the same axis system. These two systems are intrinsically tied, the way one moves the other moves too.
Neither of these axis systems are tied to the earth however. Which means that as the chip moves the axes move. This makes it trickier to find North at any given time because the vector that represents north will be broken across three axes of the magnometer (whereas normally it is always in the X-Y plane in a right-handed system).
The way to correct for this is to look at the accelerometer's vector. It always points down, even if the current axis system says it points elsewhere. So the question becomes, what three angles represent the rotation of the axis system?
Once we know those angles, we can take the components of the magnometer's readings that are parallel to those and, bam, North will be along the X-Y plane again.
If I had an axis system and a set of angles, I know I'd have to apply some matrix of trig functions to a vector to find the vector in the rotated system. I don't know which ones, but I know that's what I'd have to do. However I need to find the angles, and I already have the rotated vector - so I have the reverse of the canonical problem. Do I need a matrix of inverse trig functions?
tl;dr
(1) Given a vector which represents down(-Z) in axis system A, and the same vector in rotated axis system B, find the angles that describe the rotation.
(2) Apply found angles to a different vector, which represents North
I'm not big on math, so please clearly explain any symbols you use. Pictures are awesome.