# I need to know if my quaternion to matrix function is correct.

This topic is 2846 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have a function that converts a quaternion to a 3x3 row major matrix. I'm not sure if it's correct though since I got the code from a random site.

Here is the source:

AxMatrix33 AxMatrixQuaternion( AxVector4* q ){    AxMatrix33 out = {0};    float sqw = q->w * q->w;    float sqx = q->x * q->x;    float sqy = q->y * q->y;    float sqz = q->z * q->z;    float invs = 1 / (sqx + sqy + sqz + sqw);    out._11 = ( sqx - sqy - sqz + sqw) * invs;    out._22 = (-sqx + sqy - sqz + sqw) * invs;    out._33 = (-sqx - sqy + sqz + sqw) * invs;    float tmp1 = q->x * q->y;    float tmp2 = q->z * q->w;    out._21 = 2.0f * (tmp1 + tmp2) * invs;    out._12 = 2.0f * (tmp1 - tmp2) * invs;    tmp1 = q->x * q->z;    tmp2 = q->y * q->w;    out._31 = 2.0f * (tmp1 - tmp2) * invs;    out._13 = 2.0f * (tmp1 + tmp2) * invs;    tmp1 = q->y * q->z;    tmp2 = q->x * q->w;    out._32 = 2.0f * (tmp1 + tmp2) * invs;    out._23 = 2.0f * (tmp1 - tmp2) * invs;    return out;}

##### Share on other sites
I didn't proof the code, but there are many references available online that show how to convert a quaternion to a rotation matrix. What I'd recommend is finding maybe four or five such references and checking your code against them. There's always a chance a reference will be incorrect, but if you check against several of them, you should be fine.

One variation you'll see is that some of the references will assume column vectors are being used, while others will assume row vectors are being used. So, if your indices are transposed relative to what you see in the reference, that's fine; it just means that the conventions are opposite.

That said, it *is* important to make sure your matrix is set up correctly for whatever convention you're using (row or column vectors). I've seen math libraries that have gotten this wrong (that is, the 'quaternion' matrix is transposed relative to what it should be). Here's how you can check that this is correct: for row vectors, the expression for matrix element 12 (using 1-based indexing) should incorporate an addition rather than a subtraction, and for column vectors, element 21 should incorporate an addition (pretty sure I got that right).

1. 1
2. 2
3. 3
4. 4
5. 5
Rutin
11

• 12
• 16
• 9
• 14
• 10
• ### Forum Statistics

• Total Topics
632659
• Total Posts
3007689
• ### Who's Online (See full list)

There are no registered users currently online

×