logo back up home forward   further reading more topics »

Maths - Conversion Quaternion to Matrix - Normalization

By: hamouras - hamouras
file Quaternion to Matrix with normalization  
2006-08-24 18:10

Hi Matrin. 
 
In the quaternion to matrix page you mention that you need to normalize the quaternion before you convert it. However you can normalize the output matrix instead which is faster since you don't have to use an sqrt. 
 
Since the matrix is created by multiplying pairs of quaternion components (x*y, x*z, etc) you can normalize the matrix by dividing with the square length of the quaternion. Below i have the modified code. Also the same can be done for rotating a vector (since it actually uses the same matrix). 
 
 
public final void quatToMatrix(Quat4d q){ 
double sqw = q.w*q.w; 
double sqx = q.x*q.x; 
double sqy = q.y*q.y; 
double sqz = q.z*q.z; 
// get the invert square length 
double invs = 1 / (sqx + sqy + sqz + sqw); 
 
// rotation matrix is scaled by inverse square length 
m00 = ( sqx - sqy - sqz + sqw) * invs; 
m11 = (-sqx + sqy - sqz + sqw) * invs; 
m22 = (-sqx - sqy + sqz + sqw) * invs; 
 
double tmp1 = q.x*q.y; 
double tmp2 = q.z*q.w; 
m10 = 2.0 * (tmp1 + tmp2) * invs; 
m01 = 2.0 * (tmp1 - tmp2) * invs; 
 
tmp1 = q.x*q.z; 
tmp2 = q.y*q.w; 
m20 = 2.0 * (tmp1 - tmp2) * invs; 
m02 = 2.0 * (tmp1 + tmp2) * invs; 
tmp1 = q.y*q.z; 
tmp2 = q.x*q.w; 
m21 = 2.0 * (tmp1 + tmp2) * invs; 
m12 = 2.0 * (tmp1 - tmp2) * invs;  
}


metadata block
see also:

 

Correspondence about this page

Book Shop - Further reading.

Where I can, I have put links to Amazon for books that are relevant to the subject, click on the appropriate country flag to get more details of the book or to buy it from them.

cover us uk de jp fr ca Matrix Computations

Commercial Software Shop

Where I can, I have put links to Amazon for commercial software, not directly related to the software project, but related to the subject being discussed, click on the appropriate country flag to get more details of the software or to buy it from them.

 

cover Dark Basic Professional Edition - It is better to get this professional edition

cover This is a version of basic designed for building games, for example to rotate a cube you might do the following:
make object cube 1,100
for x=1 to 360
rotate object 1,x,x,0
next x

cover Game Programming with Darkbasic - book for above software

Can you help?

Please send me any improvements to here. I would appreciate ideas to make the pages more useful including error correction, ideas for new pages, improvements to wording. It helps if you quote the full URL of the page.

 

progam

I am working on a project which uses these principles, if you would like to help me with this you are welcome to join in, here:

http://sourceforge.net/projects/mjbworld/

This site may have errors. Don't use for critical systems.

Copyright (c) 1998-2008 Martin John Baker - All rights reserved.