You are on page 1of 34

4/2/2017 MatrixandQuaternionFAQ

TheMatrixandQuaternionsFAQ
==============================

Version1.2130thNovember2003

Pleasemailfeedbacktomatrix_faq@j3d.org
withasubjectstartingwithMATRIXFAQ
(otherwisemyspamfilterwillsimplykillyourmessage).
Anyadditionalsuggestionsorrelatedquestionsarewelcome.
JustsendEmailtotheaboveaddress.
ThelatestcopyofthisFAQcanbefoundatthefollowingwebpage:

http://www.j3d.org/matrix_faq/matrfaq_latest.html
FeelfreetodistributeorcopythisFAQasyouplease.

Contributions

IntroductionI1:Steve?????
CorrectiontoQ55untilQ59:
AndreasJunghanns
CorrectiontoQ50:MortenOfstad
NotetoQ39:TomNuydens
CorrectionstoQ29andQ37:EricReiss
ClarificationtoQ56:DuncanMurdoch
ClarificationtoQ37:RonAvitzur
CorrectiontoQ1:MonaWong
CorrectionstoQ36andQ37:EricReiss
ImprovementtoQ34andQ38:JonWatte
WarningandalternativetoQ58andQ59:PaulPedriana
Correction(andoptimization[Lee])toQ53:EleanorGroundwaterandLeeMorgan
ImprovementtoQ39:jhunpingco
CorrectionstoQ11andoptimizationtoQ12:Gordon
CorrectionstoQ54toQ60:EleanorGroundwater
CorrectionsandimprovementstoQ23andQ24:BenHouston
AdditiontoQ39:JonWatte
CorrectiontoQ61:AdamD.Moss
AdditionofQ63:MikeCline
AdditionofI2:JacobMarner
CorrectiontoQ38andinceptionofI2:ArminMller
AdditionofQ60:PabloFigueroa
CorrentionsandadditionstoQ14,Q16,Q21andQ34:TronsterHartley
CorrectiontoQ12andQ54:FrankDJ
CorrectiontoQ34:RobertFunnell

History

I(Andreas)triedtofind"hexapod@(nospam)netcom.com"whoseemedtohavemaintained
thisforawhile,butthesiteatnetcom.comdoesn'texistanymore,
emailsbounce.SinceI(andcolleques)wastedquitesometimefiguringout
whatwaswrongwithsomeofthealgorithmsgivenintheearlierversionsof
thisdocument,Idecidedtocorrectitandputitbackontheweb.
Theformerlygivensitesforthelocationofthesedocumentsdo
notexistanymore:
ftp://ftp.netcom.com/pub/he/hexapod/index.html
http://www.glue.umd.edu/~rsrodger
Versions,datesandlinkstolocalcopies(soyoucancompare):
matrfaq_1.02.html:Version1.22ndSeptember1997
matrfaq_1.04.html:Version1.426thDecember1998
matrfaq_1.06.html:Version1.630thSeptember2000
matrfaq_1.07.html:Version1.720thDecember2000
matrfaq_1.08.html:Version1.821thDecember2000
matrfaq_1.09.html:Version1.916thJanuary2001
matrfaq_1.10.html:Version1.1030thJanuary2001
matrfaq_1.11.html:Version1.119thFebruary2001
matrfaq_1.12.html:Version1.1226thMarch2001
matrfaq_1.13.html:Version1.1320thJuly2001
matrfaq_1.14.html:Version1.1417thAugust2001
http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 1/34
4/2/2017 MatrixandQuaternionFAQ

matrfaq_1.15.html:Version1.1520thAugust2001
matrfaq_1.16.html:Version1.162ndOctober2001
matrfaq_1.17.html:Version1.1730thNovember2001
matrfaq_1.18.html:Version1.1827thJanuary2002
matrfaq_1.19.html:Version1.1920thMarch2002
matrfaq_1.20.html:Version1.2031stJanuary2002
matrfaq_1.21.html:Version1.2130thNovember2003

Pleaserefrainfromaskingmemathquestions.IamonlymaintainingthisFAQ
andhaveverylittleknowledgeaboutthesubject.But,ifyouhavea
questionthatisnotansweredbythisFAQandlaterhappentofindthe
answerandbelieveittoberelevantforthisFAQ(oritsreaders),please
sendallrelevantinformation,hopefullyinapredigestedform,tometo
beincludedhere.Thanks!
Ifyouprefertoappearas"anonymous"inthecontributionslist,letme
know,otherwiseI'lljustputyoudownwithwhatevernameIcangatherfrom
youremailheader.

Introduction

I1.ImportantnoterelatingtoOpenGLandthisdocument
I2.Importantnotewithrespecttonormalizedinputs

Questions

BASICS
======
Q1.Whatisamatrix?
Q2.Whatistheorderofamatrix?
Q3.HowdoIrepresentamatrixusingtheC/C++programminglanguages?
Q4.Whataretheadvantagesofusingmatrices?
Q5.Howdomatricesrelatetocoordinatesystems?

ARITHMETIC
==========
Q6.Whatistheidentitymatrix?
Q7.Whatisthemajordiagonalmatrixofamatrix?
Q8.Whatisthetransposeofamatrix?
Q9.HowdoIaddtwomatricestogether?
Q10.HowdoIsubtracttwomatrices?
Q11.HowdoImultiplytwomatricestogether?
Q12.HowdoIsquareorraiseamatrixtoapower?
Q13.HowdoImultiplyoneormorevectorsbyamatrix?

DETERMINANTSANDINVERSES
=========================
Q14.Whatisthedeterminantofamatrix?
Q15.HowdoIcalculatethedeterminantofamatrix?
Q16.WhatareIsotropicandAnisotropicmatrices?
Q17.Whatistheinverseofamatrix?
Q18.HowdoIcalculatetheinverseofanarbitarymatrix?
Q19.HowdoIcalculatetheinverseofanidentitymatrix?
Q20.HowdoIcalculatetheinverseofarotationmatrix?
Q21.HowdoIcalculatetheinverseofamatrixusingKramer'srule?
Q22.HowdoIcalculatetheinverseofa2x2matrix?
Q23.HowdoIcalculatetheinverseofa3x3matrix?
Q24.HowdoIcalculatetheinverseofa4x4matrix?
Q25.HowdoIcalculatetheinverseofamatrixusinglinearequations?

TRANSFORMS
==========
Q26.Whatisarotationmatrix?
Q27.Howdorotationmatricesrelatetocoordinatesystems?
Q28.HowdoIgeneratearotationmatrixintheXaxis?
Q29.HowdoIgeneratearotationmatrixintheYaxis?
Q30.HowdoIgeneratearotationmatrixintheZaxis?
Q31.WhatareEulerangles?

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 2/34
4/2/2017 MatrixandQuaternionFAQ

Q32.Whatareyaw,rollandpitch?
Q33.HowdoIcombinerotationmatrices?
Q34.WhatisGimbalLock?
Q35.Whatisthecorrectwaytocombinerotationmatrices?
Q36.HowdoIgeneratearotationmatrixfromEulerangles?
Q37.HowdoIgenerateEuleranglesfromarotationmatrix?
Q38.HowdoIgeneratearotationmatrixforaselectedaxisandangle?
Q39.HowdoIgeneratearotationmatrixtomaponevectorontoanother?
Q40.HowdoIusematricestoconvertbetweentwocoordinatesystems?
Q41.Whatisatranslationmatrix?
Q42.Whatisascalingmatrix?
Q43.Whatisashearingmatrix?
Q44.HowdoIperformlinearinterpolationbetweentwomatrices?
Q45.HowdoIperformcubicinterpolationbetweenfourmatrices?
Q46.HowcanIrenderamatrix?

QUATERNIONS
===========
Q47.Whatarequaternions?
Q48.Howdoquaternionsrelateto3Danimation?
Q49.HowdoIcalculatetheconjugateofaquaternion?
Q50.HowdoIcalculatetheinverseofaquaternion?
Q51.HowdoIcalculatethemagnitudeofaquaternion?
Q52.HowdoInormaliseaquaternion?
Q53.HowdoImultiplytwoquaternionstogether?
Q54.HowdoIconvertaquaterniontoarotationmatrix?
Q55.HowdoIconvertarotationmatrixtoaquaternion?
Q56.HowdoIconvertarotationaxisandangletoaquaternion?
Q57.HowdoIconvertaquaterniontoarotationaxisandangle?
Q58.HowdoIconvertsphericalrotationanglestoaquaternion?
Q59.HowdoIconvertaquaterniontosphericalrotationangles?
Q60.HowdoIconvertEulerrotationanglestoaquaternion?
Q61.HowdoIusequaternionstoperformlinearinterpolationbetweenmatrices?
Q62.HowdoIusequaternionstoperformcubicinterpolationbetweenmatrices?
Q63.HowdoIusequaternionstorotateavector?

Introduction

I1.ImportantnoterelatingtoOpenGlandthisdocument

Inthisdocument(asinmostmathtextbooks),allmatricesaredrawn
inthestandardmathematicalmanner.Unfortunatelygraphicslibraries
likeIrisGL,OpenGLandSGI'sPerformerallrepresentthemwiththe
rowsandcolumnsswapped.
Hence,inthisdocumentyouwillsee(forexample)a4x4Translation
matrixrepresentedasfollows:

|100X|
||
|010Y|
M=||
|001Z|
||
|0001|

InPerformer(forexample)thiswouldbepopulatedasfollows:

M[0][1]=M[0][2]=M[0][3]=
M[1][0]=M[1][2]=M[1][3]=
M[2][0]=M[2][1]=M[2][3]=0;
M[0][0]=M[1][1]=M[2][2]=m[3][3]=1;
M[3][0]=X;
M[3][1]=Y;
M[3][2]=Z;

ie,thematrixisstoredlikethis:

|M[0][0]M[1][0]M[2][0]M[3][0]|

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 3/34
4/2/2017 MatrixandQuaternionFAQ

||
|M[0][1]M[1][1]M[2][1]M[3][1]|
M=||
|M[0][2]M[1][2]M[2][2]M[3][2]|
||
|M[0][3]M[1][3]M[2][3]M[3][3]|

OpenGLusesaonedimensionalarraytostorematricesbutfortunately,
thepackingorderresultsinthesamelayoutofbytesinmemoryso
takingtheaddressofapfMatrixandcastingittoafloat*willallow
youtopassitdirectlyintoroutineslikeglLoadMatrixf.
Inthecodesnippetsscatteredthroughoutthisdocument,aonedimensional
arrayisusedtostoreamatrix.Theorderingofthearrayelementsis
transposedwithrespecttoOpenGL.

ThisDocumentOpenGL
|0123||04812|
||||
|4567||15913|
M=||M=||
|891011||261014|
||||
|12131415||371115|

I2.Importantnotewithrespecttonormalizedinputs

Notethatmostalgorithmsassumenormalizedinputs,suchasvectorsof
unionlength,ormatriceswithnormalizedmaindiagonaletc.Itispossible,
andoftenenoughthecase,thatalgorithms(andthecodesnippetsprovidedhere)
workcorrectlywitharbitraryinputs,butitisusuallyconsideredbadpractise
(andyouwillpayindebuggingtimeifyoufailtoobservethissuggestion)to
relyonthisproperty.

Answers

BASICS
======
Q1.Whatisamatrix?

Amatrixisatwodimensionalarrayofnumericdata,whereeach
roworcolumnconsistsofoneormorenumericvalues.
Arithmeticoperationswhichcanbeperformedwithmatricesinclude
addition,subtraction,multiplicationanddivision.
Thesizeofamatrixisdefinedintermsofthenumberofrows
andcolumns.
AmatrixwithMrowsandNcolumnsisdefinedasaMxNmatrix.
Individualelementsofthematrixarereferencedusingtwoindex
values.Usingmathematicalnotationtheseareusuallyassignedthe
variables'i'and'j'.Theorderisrowfirst,columnsecond
Forexample,ifamatrixMwithorder4x4exists,thentheelements
ofthematrixareindexedbythefollowingrow:columnpairs:

|00010203|
M=|10111213|
|20212223|
|30313233|

Theelementatthetoprightofthematrixhasi=0andj=3
Thisisreferencedasfollows:

M=M
i,j0,3

Incomputeranimation,themostcommonlyusedmatriceshaveeither
2,3or4rowsandcolumns.Thesearereferredtoas2x2,3x3and4x4
matricesrespectively.
2x2matricesareusedtoperformrotations,shearsandothertypes

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 4/34
4/2/2017 MatrixandQuaternionFAQ

ofimageprocessing.GeneralpurposeNxNmatricescanbeusedto
performimageprocessingfunctionssuchasconvolution.
3x3matricesareusedtoperformlowbudget3Danimation.Operations
suchasrotationandmultiplicationcanbeperformedusingmatrix
operations,butperspectivedepthprojectionisperformedusing
standardoptimisedintopuredivideoperations.
4x4matricesareusedtoperformhighend3Danimation.Operations
suchasmultiplicationandperspectivedepthprojectioncanbe
performedusingmatrixmathematics.

Q2.Whatisthe"order"ofamatrix?

The"order"ofamatrixisanothernameforthesizeofthematrix.
AmatrixwithMrowsandNcolumnsissaidtohaveorderMxN.

Q3.HowdoIrepresentamatrixusingtheC/C++programminglanguages?

ThesimplestwayofdefiningamatrixusingtheC/C++programming
languagesistomakeuseofthe"typedef"keyword.Both3x3and4x4
matricesmaybedefinedinthiswayie:

typedeffloatMATRIX3[9];
typedeffloatMATRIX4[16];

Sinceeachtypeofmatrixhasdimensions3x3and4x4,thisrequires
9and16dataelementsrespectively.
Atfirstglance,theuseofasinglelineararrayofdatavaluesmay
seemcounterintuitive.Theuseoftwodimensionalarraysmayseem
moreconvenientie.

typedeffloatMATRIX3[3][3];
typedeffloatMATRIX4[4][4];

However,theuseoftworeferencesystemsforeachmatrixelement
veryoftenleadstoconfusion.Withmathemetics,theorderisrow
first(i),columnsecond(j)ie.

Mij

UsingC/C++,thisbecomes

matrix[j][i]

UsingtwodimensionalarraysalsoincursaCPUperformancepenaltyin
thatCcompilerswilloftenmakeuseofmultiplicationoperationsto
resolvearrayindexoperations.
So,itismoreefficienttostickwithlineararrays.However,oneissue
stillremainstoberesolved.Howisantwodimensionalmatrixmapped
ontoalineararray?Sincethereareonlytwomethods(rowfirst/column
secondorcolumnfirst/rowcolumn).
Theperformancedifferencesbetweenthetwoaresubtle.Ifallfornext
loopsareunravelled,thenthereisverylittledifferenceinthe
performanceforoperationssuchasmatrixmatrixmultiplication.
UsingtheC/C++programminglanguagesthelinearorderingofeach
matrixisasfollows:

mat[0]=Mmat[3]=M
0003
mat[12]=Mmat[15]=M
3033

|0123|
|||012|
|4567|||
M=||M=|345|
|891011|||
|||678|
|12131415|

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 5/34
4/2/2017 MatrixandQuaternionFAQ

Q4.Whataretheadvantagesofusingmatrices?

Oneofthefirstquestionsaskedabouttheuseofmatricesincomputer
animationiswhytheyshouldbeusedatallinthefirstplace.
Intuitively,itwouldappearthattheoverheadoffornextloopsand
matrixmultiplicationwouldslowdownanapplication.
Argumentsthatresolvetheseobjectionscanbepointedout.Theseinclude
theuseofCPUregisterstohandleloopcountersonboarddatacaches
tooptimisememoryaccesses.
Advantagescanalsobepointedout.Byfollowingamathematicalapproach
todefining3Dalgorithms,itispossibletopredictandplanthe
designofa3Danimationsystem.Suchmathematicalapproachesallow
fortheimplementationofcharacteranimation,splinecurvesandinverse
kinematics.
However,oneobjectionthatfrequentlycomesupisthatitwouldbe
quickertojustmultiplyeachpairofcoordinatesbytherotation
coefficientsforthataxis,ratherthanperformafullvectormatrix
multiplication.
ie.RotationinXtransformsYandZ
RotationinYtransformsXandZ
RotationinZtransformsXandY
Theargumenttothisgoesasfollows:
GivenavertexV=(x,y,z),rotationangles(A,BandC)andtranslation
(D,E,F).Athealgorithm
isdefinedasfollows:

sx=sin(A)//Setuponlydoneonce
cx=cos(A)
sy=sin(B)
cy=cos(B)
sz=sin(C)
cz=cos(C)
x1=x*cz+y*sz//Rotationofeachvertex
y1=y*czx*sz
z1=z
x2=x1*cy+z1*sy
y2=z1
z2=z1*cyx1*sy
x3=x2
y3=y2*cx+z1*sx
z3=z2*cxx1*sx
xr=x3+D//Translationofeachvertex
yr=y3+E
zr=z3+F

Altogether,thisalgorithmwillusethefollowingamountsofprocessing
time:
SetupPervertex

6trigonometricfunctions
6assignmentoperations.12assignment
12multiplication
9addition

Assumethatthesameoperationsisbeingperformedusingmatrix
multiplication.
Witha4x4matrix,theprocesingtimeisusedasfollows:
SetupChangePervertexChange

6trigonometricfunctions00
18assignmentoperation123assignment9
12multiplication+129multiplication3
6subtraction+66addition3

Comparingthetwotables,itcanbeseenthatsettinguparotation
matrixcostsatleast12multiplicationcalculationsandanextra
18assignmentcalls.
However,whilethismayseemextravagant,thesavingscomefrom
processingeachvertex.Usingmatrixmultiplication,thesavingsmade

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 6/34
4/2/2017 MatrixandQuaternionFAQ

fromprocessingjust4vertices,willoutweightheadditionalsetup
cost.

Q5.Howdomatricesrelatetocoordinatesystems?

Witheither3x3or4x4rotation,translationorshearingmatrices,there
isasimplerelationshipbetweeneachmatrixandtheresultingcoordinate
system.
Thefirstthreecolumnsofthematrixdefinethedirectionvectorofthe
X,YandZaxiirespectively.
Ifa4x4matrixisdefinedas:

|ABCD|
M=|EFGH|
|IJKL|
|MNOP|

Thenthedirectionvectorforeachaxisisasfollows:

Xaxis=[AEI]
Yaxis=[BFJ]
Zaxis=[CGK]

ARITHMETIC
==========

Q6.Whatistheidentitymatrix?

Theidentitymatrixismatrixinwhichhasanidenticalnumberofrows
andcolumns.Also,alltheelementsinwhichi=jaresetone.Allothers
aresettozero.Forexamplea4x4identitymatrixisasfollows:

|1000|
M=|0100|
|0010|
|0001|

Q7.Whatisthemajordiagonalofamatrix?

Themajordiagonalofamatrixisthesetofelementswherethe
rownumberisequaltothecolumnnumberie.

Mwherei=j
ij

Inthecaseoftheidentitymatrix,onlytheelementsonthemajor
diagonalaresetto1,whileallothersaresetto0.

Q8.Whatisthetransposeofamatrix?

Thetransposeofmatrixisthematrixgeneratedwheneveryelementin
thematrixisswappedwiththeoppositerelativetothemajordiagonal
Thiscanbeexpressedasthemathematicaloperation:

M'=M
ijji

However,thiscanonlybeperformedifamatrixhasanequalnumber
ofrowsandcolumns.
IfthematrixMisdefinedas:

|0.7070.866|
M=||
|0.8660.707|

Thenthetransposeisequalto:

|0.7070.866|
T=||

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 7/34
4/2/2017 MatrixandQuaternionFAQ

|0.8660.707|

Ifthematrixisarotationmatrix,thenthetransposeisguaranteed
tobetheinverseofthematrix.

Q9.HowdoIaddtwomatricestogether?

Theruleofthumbwithaddingtwomatricestogetheris:
"addrowandcolumntorowandcolumn"
Thiscanbeexpressedmathematicallyas:

R=M+L
ijijij

However,bothmatricesmustbeidenticalinsize.
Forexample,ifthe2x2matrixMisaddedwiththe2x2matrixLthen
theresultisasfollow:

R=M+L
|ABC||JKL|
||||
=|DEF|+|MNO|
||||
|GHI||PQR|

|A+JB+KC+L|
||
=|D+ME+NF+O|
||
|G+PH+QI+R|

Q10.HowdoIsubtracttwomatrices?

Theruleofthumbwithsubtractingtwomatricesis:
"subtractrowandcolumnfromrowandcolumn"
Thiscanbeexpressedmathematicallyas:

R=ML
ijijij

However,bothmatricesmustbeidenticalinsize.
Forexample,ifthe2x2matrixLissubtractedfromthe2x2matrixMthen
theresultisasfollows:

R=ML
|ABC||JKL|
||||
=|DEF||MNO|
||||
|GHI||PQR|

|AJBKCL|
||
=|DMENFO|
||
|GPHQIR|

Q11.HowdoImultiplytwomatricestogether?

Theruleofthumbwithmultiplyingtwomatricestogetheris:
"multiplyrowintocolumnandsumtheresult".
Thiscanbeexpressedmathematicallyas:
n


R=\MxL
ij/ikkj

k=1

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 8/34
4/2/2017 MatrixandQuaternionFAQ

Ifthetwomatricestobemultipliedtogetherhaveorders:

M=AxBandL=CxD

thenthetwovaluesBandCmustbeidentical.
Also,theresultingmatrixhasanorderofAxD
Thus,itispossibletomultiplyaNx4matrixwitha4x4matrix
butnottheotherwayaround.
Forexample,ifthe4x4matrixMisdefinedas:

|ABCD|
M=|EFGH|
|IJKL|
|MNOP|

anda4x2matrixLisdefinedas:

L=|QR|
|ST|
|UV|
|WX|

thenthesizeoftheresultingmatrixis4x2.Theresultingmatrix
isdefinedas:

R=MxL

|ABCD||QR|
=|EFGH|x|ST|
|IJKL||UV|
|MNOP||WX|

|AQ+BS+CU+DWAR+BT+CV+DX|
=|EQ+FS+GU+HWER+FT+GV+HX|
|IQ+JS+KU+LWIR+JT+KV+LX|
|MQ+NS+OU+PWMR+NT+OV+PX|

Q12.HowdoIsquareorraiseamatrixtoapower?

Amatrixmaybesquaredorevenraisedtoanintegerpower.However
thereareseveralrestrictions.Forallpowers,thematrixmustbe
square,thatisorthogonalandthesamewidthandheight
Forexample,

1
Mistheinverseofthematrix

0
Mgeneratestheidentitymatrix

1
Mleavesthematrixunchanged.

2
Msquaresthematrixand

3
Mgeneratesthecubeofthematrix

Raisingamatrixtoapowergreaterthanoneinvolvesmultiplyingamatrix
byitselfaspecificnumberoftimes.
Forexample,

2
M=M.M

3
M=M.M.M

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 9/34
4/2/2017 MatrixandQuaternionFAQ

andsoon.

Raisingtheidentitymatrixtoanypoweralwaysgeneratestheidentity
matrixie.

n
I=I

Onecanbebitfasterusingthefollowingpieceofcode,notethatmandi
arebothgettingchanged:
m>matrixtoberaisedtoapower
i>powertoraisematrixto
a>matrixthatwillcontaintheresult
I>identitymatrix
/>integerdivision(ierounddowntonearestwholenumber)
%>integerremainderoperation
*>matrixmultiplication

a=I
while(i>0){
if(i%2)a=a*m
i=i/2
m=m*m
}

Q13.HowdoImultiplyoneormorevectorsbyamatrix?

Thebestwaytoperformthistaskistotreatthelistofvectorsas
asinglematrix,witheachvectorrepresentedasacolumnvector.
IfNvectorsaretobemultipliedbya4x4matrix,thentheycanbe
treatedasasingle4xNmatrix:
Ifthematrixisdefinedas:

|ABCD|
M=|EFGH|
|IJKL|
|MNOP|

andthelistofvectorsisdefinedas:

|x1x2x3x4x5|
V=|y1y2y3y4y5|
|z1z2z3z4z5|
|11111|

Notethatanadditionalrowofconstanttermsisaddedtothevector
list,allofwhicharesetto1.0.Inreallife,thisrowdoesnot
exist.ItissimplyusedtomaketheordersofthematrixMandthe
vectorlistVmatch.
Thenthemultiplicationisperformedasfollows:

M.V=V'

|ABCD||x1x2x3x4x5||A.x1+B.y1+C.z1+DA.x2+B.y2+C.z2+D...|
|EFGH|.|y1y2y3y4y5|=|E.x1+F.y1+G.z1+HE.x2+F.y2+G.z2+H...|
|IJKL||z1z2y3y4z5||I.x1+J.y1+K.z1+LI.x2+J.y2+K.z2+L...|
|MNOP||11111||M.x1+N.y1+O.z1+PM.x2+N.y2+O.z2+P...|

Foreachvectorinthelisttherewillbeatotalof12multiplication
16additionand1divisionoperation(forperspective).
Ifthematrixisknownnottobearotationortranslationmatrixthenthe
divisionoperationcanbeskipped.

DETERMINANTSANDINVERSES
=========================

Q14.Whatisthedeterminantofamatrix?

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 10/34
4/2/2017 MatrixandQuaternionFAQ


Thedeterminantofamatrixisafloatingpointvaluewhichisusedto
indicatewhetherthematrixhasaninverseornot.Ifzero,thenno
inverseexists.Ifnonzero,thenaninverseexists.
Asanexample,consideramatrixconsistingofasingleelement:

M=[1].

Foramatrixofthissize,thedeterminantissimplythevalueofthe
singleelement.
Also,theinverseissimplythereciprocalofthissingleelement:

1
M=[1/M[0][0]]

Ifthissinglevalueisnonzero,thenaninverseexists.Inthecase
oftheidentitymatrix,thishappenstobe1/1or1.0
However,ifthevalueofthissingleelementiszero,thenthedeterminant
isalsozero.

Attemptingtocalculatethereciprocalofzero,generatesavalueof
infinity.Thisisn'tpermittedasfaramatricesareconcerned,sono
inverseofthematrixexists.
Foranidentitymatrix,thedeterminantisalwaysequaltoone.
Anymatrixwithadeterminantof1.0issaidtobeisotropic.
Thusallrotationmatricesaresaidtobeisotropic,sincethe
determinantisalwaysequalto1.0.
Thiscanbeprovedasfollows:

|AB||cosXsinX|
M=||=||
|CD||sinXcosX|

D=ADBC

D=(cosX.cosX)(sinX.sinX)

22
D=(cosX)+(sinX)

22
But,cosX+sinX=1

Therefore,
D=1

Q15.HowdoIcalculatethedeterminantofamatrix?

ThedeterminantofamatrixiscalculatedusingKramer'srule,where
thevaluecanbecalculatedbybreakingthematrixintosmaller
matrices.
Fora2x2matrixM,thedeterminantDiscalculatedasfollows:

|AB|
M=||
|CD|

D=ADBC

For3x3and4x4matrices,thisismorecomplicated,butcanbesolved
bymethodssuchasKramer'sRule.

Q16.WhatareIsotropicandAnisotropicmatrices?

AnIsotropicmatrixisoneinwhichthesumofthesquaresofall
threerowsorcolumnsadduptoone.
Amatrixinwhichthisisnotthecase,issaidtobeAnisotropic.
When3x3or4x4matricesareusedtorotateandscaleanobject,it
issometimesnecessarytoenlargeorshrinkoneaxismorethanthe

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 11/34
4/2/2017 MatrixandQuaternionFAQ

others.
Forexample,withseismicsurveys,itisconvenienttoenlargethe
Zaxisbyafactoror50ormore,whilelettingtheXandYaxii
remainthesame.
Anotherexampleistheimplementationof"squash"and"stretch"
withcharacteranimation.Whenacharacterishitbyaheavyobject
eg.ananvil,thedesiredeffectistomakethecharacterlookstretchedout
sidewaysandsquashedvertically:
Asuitablematrixwouldbeasfollows:

|2000|
M=|0200|
|000.50|
|0001|

However,thereisproblemloomingahead.Whilethismatrixwillcause
noproblemswiththetransformationofvertexdata,itwillcause
problemswithgouraudshadingusingoutwardnormals.
Becausethetransformationstageisimplementedusingmatrix
multiplication,bothvertexdataandoutwardnormaldatawillbe
multipliedwiththismatrix.
Whilethisisnotaproblemwithvertexdata(itisthedesiredeffect)
itcausesamajorheadachewiththeoutwardnormaldata.
Afterrawmultiplication,eachoutwardnormalwillnolongerbe
normalisedandconsequentlywillaffectothercalculationssuchas
shadingandbackfaceculling.

Q17.Whatistheinverseofamatrix?

1
GivenamatrixM,thentheinverseofthatmatrix,denotedasM,is
thematrixwhichsatisfiesthefollowingexpression:

1
M.M=I

whereIistheidentitymatrix.
Thus,multiplyingamatrixwithitsinversewillgeneratetheidentity
matrix.However,severalrequirementsmustbesatisfiedbeforethe
inverseofamatrixcanbecalculated.
Theseincludethatthewidthandheightofthematrixareidenticaland
thatthedeterminantofthematrixisnonzero.
Calculatingtheinverseofamatrixisataskoftenperformedinorder
toimplementinversekinematicsusingsplinecurves.

Q18.HowdoIcalculatetheinverseofanarbitarymatrix?

Dependinguponthesizeofthematrix,thecalculationoftheinverse
canbetrivialorextremelycomplicated.
Forexample,theinverseofa1x1matrixissimplythereciprocalof
thesingleelement:

ie.M=|x|

Thentheinverseisdefinedas:

1|1|
M=||
|x|

Solving2x2matricesandlargercanbeachievedbyusingKramer'sRule
orbysolvingasasetofsimultaneousequations.
However,incertaincases,suchasidentityorrotationmatrices,the
inverseisalreadyknownorcanbedeterminedfromtakingthetranspose
ofthematrix.

Q19.HowdoIcalculatetheinverseofanidentitymatrix?

Don'tevenbother.Theinverseofanidentitymatrixistheidentity

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 12/34
4/2/2017 MatrixandQuaternionFAQ

matrix.ie.

1
I.I=I

Anyidentitymatrixwillalwayshaveadeterminantof+1.

Q20.HowdoIcalculatetheinverseofarotationmatrix?

Sincearotationmatrixalwaysgeneratesadeterminantof+1,
calculatingtheinverseisequivalentofcalculatingthetranspose.
Alternatively,iftherotationangleisknown,thentherotation
anglecanbenegatedandusedtocalculateanewrotationmatrix.

Q21.HowdoIcalculatetheinverseofamatrixusingKramer'srule?

Givena3x3matrixM:

|ABC|
||
M=|DEF|
||
|GHI|

Thenthedeterminantiscalculatedasfollows:

n

\i
detM=/M*submatM*1
0,i0,i
i=1
where

submatMdefinesthematrixcomposedofallrowsandcolumnsofM
ij

excludingrowiandcolumnj.submatmaybecalledrecursively.
ij
|ABC|
M=|DEF|becomessubmat=|EF|
|GHI|11|HI|

Ifthedeterminantisnonzerothentheinverseofthematrixexists.
Inthiscase,thevalueofeachmatrixelementisdefinedby:

11i+j
M=*detsubmatM*1
j,idetMi,j

Q22.HowdoIcalculatetheinverseofa2x2matrix?

Fora2x2matrix,thecalculationisslightlyharder.Ifthematrixis
definedasfollows:

|AB|
M=||
|CD|

Thenthedeterminantisdefinedas:

det=ADBC

Andtheinverseisdefinedas:

11|DB|
M=||
det|CA|

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 13/34
4/2/2017 MatrixandQuaternionFAQ

ThiscanbeprovedusingKramer'srule.GiventhematrixM:

|AB|
M=||
|CD|

Thenthedeterminantis:

01
det=M*submatM*1+M*submatM*1
0,00,00,10,1

<=>M*M*1+M*M*1
0,01,10,11,0

<=>A*D+B*C*1

<=>AD+BC.1

<=>ADBC

Andtheinverseisderivedfrom:

10+01
M=detsubmat*1<=>M=M*1<=>D
0,00,00,01,1

11+01
M=detsubmat*1<=>M=M*1<=>C*1
0,11,00,11,0

10+11
M=detsubmat*1<=>M=M*1<=>B*1
1,00,11,00,1

11+11
M=detsubmat*1<=>M=M*1<=>A
1,11,11,10,0

Thentheinversematrixisequalto:

11|DC|
M=||
det|BA|

Providingthatthedeterminantisnotzero.

Q23.HowdoIcalculatetheinverseofa3x3matrix?

For3x3matricesandlarger,theinversecanbecalculatedby
eitherapplyingKramer'sruleorbysolvingasasetoflinear
equations.
IfKramer'sruleisappliedtoamatrixM:

|ABC|
M=|DEF|
|GHI|

thenthedeterminantiscalculatedasfollows:
detM=A*(EIHF)B*(DIGF)+C*(DHGE)

Providingthatthedeterminantisnonzero,thentheinverseis
calculatedas:

11|EIFH(BIHC)BFEC|
M=.|(DIFG)AIGC(AFDC)|
detM|DHGE(AHGB)AEBD|

Thiscanbeimplementedusingapairof'C'functions:

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 14/34
4/2/2017 MatrixandQuaternionFAQ

VFLOATm3_det(MATRIX3mat)
{
VFLOATdet;
det=mat[0]*(mat[4]*mat[8]mat[7]*mat[5])
mat[1]*(mat[3]*mat[8]mat[6]*mat[5])
+mat[2]*(mat[3]*mat[7]mat[6]*mat[4]);
return(det);
}

intm3_inverse(MATRIX3mr,MATRIX3ma)
{
VFLOATdet=m3_det(ma);
if(fabs(det)<0.0005)
{

m3_identity(mr);
return(0);
}

mr[0]=ma[4]*ma[8]ma[5]*ma[7]/det;
mr[1]=(ma[1]*ma[8]ma[7]*ma[2])/det;
mr[2]=ma[1]*ma[5]ma[4]*ma[2]/det;
mr[3]=(ma[3]*ma[8]ma[5]*ma[6])/det;
mr[4]=ma[0]*ma[8]ma[6]*ma[2]/det;
mr[5]=(ma[0]*ma[5]ma[3]*ma[2])/det;
mr[6]=ma[3]*ma[7]ma[6]*ma[4]/det;
mr[7]=(ma[0]*ma[7]ma[6]*ma[1])/det;
mr[8]=ma[0]*ma[4]ma[1]*ma[3]/det;
return(1);
}

Q24.HowdoIcalculatetheinverseofa4x4matrix?

Aswith3x3matrices,eitherKramer'srulecanbeappliedorthe
matrixcanbesolvedasasetoflinearequations.
Anefficientwayistomakeuseoftheexisting'C'functionsdefined
tocalculatethedeterminantandinverseofa3x3matrix.
InordertoimplementKramer'srulewith4x4matrices,itisnecessary
todetermineindividualsubmatrices.Thisisachievedbythefollowing
routine:

void m4_submat(MATRIX4mr,MATRIX3mb,inti,intj){
intdi,dj,si,sj;
//loopthrough3x3submatrix
for(di=0;di<3;di++){
for(dj=0;dj<3;dj++){
//map3x3element(destination)to4x4element(source)
si=di+((di>=i)?1:0);
sj=dj+((dj>=j)?1:0);
//copyelement
mb[di*3+dj]=mr[si*4+sj];
}
}
}

Thedeterminantofa4x4matrixcanbecalculatedasfollows:

VFLOATm4_det(MATRIX4mr)
{
VFLOATdet,result=0,i=1;
MATRIX3msub3;
intn;
for(n=0;n<4;n++,i*=1)
{

m4_submat(mr,msub3,0,n);
det=m3_det(msub3);
result+=mr[n]*det*i;

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 15/34
4/2/2017 MatrixandQuaternionFAQ

}
return(result);
}

Andtheinversecanbecalculatedasfollows:

intm4_inverse(MATRIX4mr,MATRIX4ma)
{

VFLOATmdet=m4_det(ma);
MATRIX3mtemp;
inti,j,sign;
if(fabs(mdet)<0.0005)
m4_identity(mr);
return(0);
for(i=0;i<4;i++)
for(j=0;j<4;j++)
{
sign=1((i+j)%2)*2;
m4_submat(ma,mtemp,i,j);
mr[i+j*4]=(m3_det(mtemp)*sign)/mdet;
}
return(1);
}

Havingafunctionthatcancalculatetheinverseofany4x4matrixis
anincrediblyusefultool.Applicationincludebeingabletocalculate
thebasematrixforsplines,inverserotationsandrearrangingmatrix
equations.

Q25.HowdoIcalculatetheinverseofamatrixusinglinearequations?

IfamatrixMexists,suchthat:

|ABC|
M=|DEF|
|GHI|

thentheinverseexists:

|PQR|
M'=|STU|
|VWX|

andthefollowingexpressionisvalid:

1
M.M=I

|ABC||PQR||100|
|DEF|.|STU|=|010|
|GHI||VWX||001|

Theinversecanthenbecalculatedthroughthesolutionasasetof
linearequationsie.:

|AP+BS+CV||1|Column0(X)
|DP+ES+FV|=|0|
|GP+HS+IV||0|

|AQ+BT+CW||0|Column1(Y)
|DQ+ET+FW|=|1|
|GQ+HT+IW||0|

|AR+BU+CX||0|Column2(Z)
|DR+EU+FX|=|0|
|GR+HU+IX||1|

TRANSFORMS

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 16/34
4/2/2017 MatrixandQuaternionFAQ

==========

Q26.Whatisarotationmatrix?

Arotationmatrixisusedtorotateasetofpointswithina
coordinatesystem.Whiletheindividualpointsareassignednew
coordinates,theirrelativedistancesdonotchange.
Allrotationsaredefinedusingthetrigonometric"sine"and"cosine"
functions.
Foratwodimensionalcoordinatesystem,therotationmatrixisas
follows:

|cos(A)sin(A)|
||
|sin(A)cos(A)|

WiththerotationangleAsettozero,thisgeneratestheidentity
matrix:

|10|
I=||
|01|

Iftherotationissetto+90degrees,thenthematrixisasfollows:

|01|
M=||
|10|

Iftherotationissetto90degrees,thenthematrixisasfollows:

|01|
M=||
|10|

Negatingtherotationangleisequivalenttogeneratingthetranspose
ofthematrix.
Ifarotationmatrixismultipliedwithitstranspose,theresultis
theidentitymatrix.

Q27.Howdorotationmatricesrelatetocoordinatesystems?

Rotationmatricesrelatetocoordinatesystemsinthefollowingway.
Mathematicalconventionrequiresthatapositiverotationangle
generatesaclockwiserotationwhenlookingfromtheorigintowards
thepositiveendoftherotationaxis.
Applyingthisrule,allowsforthederivationofthreeCartesian
rotationmatrices.Considerarighthandedcoordinatesystem.Foreach
rotationaxis,lookfromtheorigintowardsthepositiveendofthe
selectedaxis.Thisgeneratesthefollowingthreeviews:
++
||
|XaxisYaxisZaxis|
||
||
|^Y^ZY^|
|||||
|||||
|||||
|||||
|O>ZO>XX<O|
||
++
Sinceapositiverotationanglegeneratesaclockwiserotation,itis
possibletogenerateasetofcoordinatemappingsforeachrotation.
Forsimplicity,arotationof+90willbeconsidered:
StartingwiththeXaxis:

(0,1,0)>(0,0,1)

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 17/34
4/2/2017 MatrixandQuaternionFAQ

(0,0,1)>(0,1,0)
(0,1,0)>(0,0,1)
(0,0,1)>(0,1,0)

Thesecanbesimplifiedto:

X'=X
Y'=Z
Z'=Y

Thesecanthenbeplacedintoamatrix:

|100|
Rx=|0cosAsinA|
|0sinAcosA|

DoingthesamefortheYaxis:

(0,0,1)>(1,0,0)
(1,0,0)>(0,0,1)
(0,0,1)>(1,0,0)
(1,0,0)>(0,0,1)

Thesecanbesimplifiedto:

X'=Z
Y'=Y
Z'=X

Thesecanthenbeplacedintoamatrix:

|cosA0sinA|
Ry=|010|
|sinA0cosA|

AndfinallyfortheZaxis:

(0,1,0)>(1,0,0)
(1,0,0)>(0,1,0)
(0,1,0)>(1,0,0)
(1,0,0)>(0,1,0)

Thesecanbesimplifiedto:

X'=Y
Y'=X
Z'=Z

Placingtheseintoamatrix:

|cosAsinA0|
Rz=|sinAcosA0|
|001|

ThesearethethreebasicrotationmatricesusedbyOpenGL.

Q28.HowdoIgeneratearotationmatrixintheXaxis?

Usethe4x4matrix:

|1000|
M=|0cos(A)sin(A)0|
|0sin(A)cos(A)0|
|0001|

Q29.HowdoIgeneratearotationmatrixintheYaxis?

Usethe4x4matrix:

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 18/34
4/2/2017 MatrixandQuaternionFAQ

|cos(A)0sin(A)0|
M=|0100|
|sin(A)0cos(A)0|
|0001|

Q30.HowdoIgeneratearotationmatrixintheZaxis?

Usethe4x4matrix:

|cos(A)sin(A)00|
M=|sin(A)cos(A)00|
|0010|
|0001|

Q31.WhatareEulerangles?

Euleranglesarethenamegiventothesetofrotationangleswhich
specifytherotationineachoftheX,YandZrotationaxii.
Thesearespecfiedinvectorformateg.|xyz|andcanbestored
asaVECTORdatastructure.
Forexample,theset

|000|

willalwaysgeneratetheidentitymatrix.
Otheranglesarerepresentedasfollows:

|9000|isarotationof+90degreesintheXaxis.
|0900|isarotationof+90degreesintheYaxisand
|0090|isarotationof+90degreesintheZaxis.

Euleranglescanberepresentedusingasinglevectordatastructure.

Q32.WhatareYaw,RollandPitch?

Yaw,RollandPitchareaeronauticaltermsforrotationusingthe
Euclideancoordinatesystem(Eulerangles),relativetothelocal
coordinatesystemofanaeroplane.
Imagineyouareviewinganaeroplanefromaboveandfromdirectlybehind.
TheZaxisislinedupwiththetailandnoseoftheaeroplane.
TheXaxisrunsfromthetipoftheleftwingtothetipoftheright
wing.
TheYaxispointsstraightupfromtheground.
PitchthenbecomesrotationintheXaxis,Yawbecomesrotationinthe
YaxisandRollbecomesrotationintheZaxis.

Q33.HowdoIcombinerotationmatrices?

Rotationmatricesarecombinedtogetherusingmatrixmultiplication.
Asaresult,theorderofmultiplicationisveryimportant.

Q34.WhatisGimballock?

Gimballockisthenamegiventoaproblemthatoccurswiththeuseof
Eulerangles.Becausethefinalrotationmatrixdependsontheorder
ofmultiplication,itissometimesthecasethattherotationinone
axiswillbemappedontoanotherrotationaxis.
Evenworse,itmaybecomeimpossibletorotateanobjectinadesired
axis.ThisiscalledGimballock.
Forexample,assumethatanobjectisbeingrotatedintheorderZ,Y,X
andthattherotationintheYaxisis90degrees.
Inthiscase,rotationintheZaxisisperformedfirstandtherefore
correctly.TheYaxisisalsorotatedcorrectly.However,after
rotationintheYaxis,theXaxisisrotatedontotheZaxis.
Thus,anyrotationintheXaxisactuallyrotatestheobjectinthe
Zaxis.Evenworse,itbecomesimpossibletorotatetheobjectintheXaxis.
AconvenientsolutiontothisproblemistomakeuseofQuaternions.

Q35.Whatisthecorrectwaytocombinerotationmatrices?

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 19/34
4/2/2017 MatrixandQuaternionFAQ


Really,thereisno"correctway"ofcombiningrotationmatrices.
However,inordertobeabletopredicttheresultofcombining
matricestogether,someorganisationisrequired.Thisisalso
necessaryifafull3Dmatrixlibraryistobebuilt.
Thesimplestwaytorotateanobjectistomultiplythematrices
usingtheorder:

M=X.Y.Z

whereMisthefinalrotationmatrix,andX,Y,Zaretheindividual
rotationmatrices.ThisdefinesarotationintheXaxis(pitch)first,
followedbytheYaxis(yaw)andafinalrotationintheZaxis(roll).
However,whenevertheviewfromthecameraviewpointisbeing
evaluated,thentheorderandsignsoftherotationisreversed.
Forexample,ifyouarestandingup,andturntoyourleft,everything
inyourfieldofviewappearstomovetowardstheright.
However,someoneelsefacingyouwillsaythatyouturnedtowardstheir
right.
Thustheviewfromthecameraismodelledusingtheorder:

M=Z.Y.X

Thisistheinverse(ortranspose)oftherotationmatrixgenerated
ifthecamerawerebeingrenderedasanotherobject.

Q36.HowdoIgeneratearotationmatrixfromEulerangles?

Atfirstglance,themostobviousmethodtogeneratearotationmatrix
fromasetofEuleranglesistogenerateeachmatrixindividuallyand
multiplyallthreetogetherie.

m3_rotx(mat_x,vec>angle_x);
m3_roty(mat_y,vec>angle_y);
m3_rotz(mat_z,vec>angle_z);
m3_mult(mat_tmp,mat_z,mat_y);
m3_mult(mat_final,mat_tmp,mat_x);

Thissetofcallscouldbeplacedinaseparateroutineeg.

m3_fromeuler(MATRIX*mat_final,VECTOR3*euler)

However,toperformthissequenceofcallsisverywastefulinterms
ofprocessingtime.Giventhateach4x4rotationmatrixisguaranteed
tohave10elementswithvaluezero(0),2elementswithvalueone(1)
andfourothersofarbitaryvalue,over75%ofeverymatrixoperation
iswasted.Thisdoesnotincludethesetupandinitialisationofeach
matrix.
Altogether,over75%ofallmatrixoperationsarespentprocessing
arithmeticexpressionswhichleadtoeitherzeroorone.
Amoreefficientwaymustbefound.Fortunately,thereisanotherway
ofdeterminingthefinalresultingmatrix.
Ifallthreematricesarecombinedinalgebraicformat,thefollowing
expressionisdefined:

M=X.Y.Z

whereMisthefinalmatrix,
XistherotationmatrixfortheXaxis,
YistherotationmatrixfortheYaxis,
ZistherotationmatrixfortheZaxis.

Expandingintorotationmatricesinalgebraicformatgives:

|100|
X=|0AB|
|0BA|

|C0D|

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 20/34
4/2/2017 MatrixandQuaternionFAQ

Y=|010|
|D0C|

|EF0|
Z=|FE0|
|001|

whereA,BarethecosineandsineoftheXaxisrotationaxis,
C,DarethecosineandsineoftheYaxisrotationaxis,
E,FarethecosineandsineoftheZaxisrotationaxis.

Thentheexpression:

M=X.Y.Z

canbesplitintotwomatrixmultiplications:

M'=X.Y
M=M'.Z

EvaluatingM'first:

M'=X.Y

|100||C0D|
M'=|0AB|.|010|
|0BA||D0C|

|1.C+0.0+0.D1.0+0.1+0.01.D+0.0+0.C|
M'=|0.C+A.0+B.D0.0+A.1+B.00.D+A.0+B.C|
|0.C+B.0+A.D0.0+B.1+A.00.D+B.0+A.C|

SimplifyingM'gives:

|C0D|
M'=|B.DAB.C|
|A.DBA.C|

EvaluatingMgives:

M=M'.Z

|C0D||EF0|
M=|BDABC|.|FE0|
|ADBAC||001|

|C.E+0.F+D.0C.F+0.E+D.0C.0+0.0+D.1|
M=|BD.E+A.F+BC.0BD.F+A.E+BC.0BD.0+A.0+BC.1|
|AD.E+B.F+AC.0AD.F+B.E+AC.0AD.0+0.0+AC.1|

SimplifyingMgivesa3x3matrix:

|CECFD|
M=|BDE+AFBDF+AEBC|
|ADE+BFADF+BEAC|

Thisisthefinalrotationmatrix.Asa4x4matrixthisis:

|CECFD0|
M=|BDE+AFBDF+AEBC0|
|ADE+BFADF+BEAC0|
|0001|

TheindividualvaluesofA,B,C,D,EandFareevaluatedfirst.Also,the
valuesofBDandADarealsoevaluatedsincetheyoccurmorethanonce.
Thus,thefinalalgorithmisasfollows:

A=cos(angle_x);
B=sin(angle_x);

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 21/34
4/2/2017 MatrixandQuaternionFAQ

C=cos(angle_y);
D=sin(angle_y);
E=cos(angle_z);
F=sin(angle_z);
AD=A*D;
BD=B*D;
mat[0]=C*E;
mat[1]=C*F;
mat[2]=D;

mat[4]=BD*E+A*F;
mat[5]=BD*F+A*E;
mat[6]=B*C;
mat[8]=AD*E+B*F;
mat[9]=AD*F+B*E;
mat[10]=A*C;
mat[3]=mat[7]=mat[11]=mat[12]=mat[13]=mat[14]=0;
mat[15]=1;

Usingbasicmatrixcalculations,theoperationcountwouldreach
128multiplications,96additionsand80assignmentsoperations.
Usingtheoptimisedalgorithm,only12multiplications,6subtractions
and18assignmentoperationsarerequired.
So,itisobviousthatbyusingtheoptimisedalgorithm,aperformance
achievementof1000%isachieved!

Q37.HowdoIconvertarotationmatrixtoEulerangles?

Thisoperationistheexactoppositetotheoneansweredinthequestion
above.Giventhattherotationmatrixis:

|CECFD0|
M=|BDE+AFBDF+AEBC0|
|ADE+BFADF+BEAC0|
|0001|

whereA,BarethecosineandsineoftheXaxisrotationaxis,
C,DarethecosineandsineoftheYaxisrotationaxis,
E,FarethecosineandsineoftheZaxisrotationaxis.

UsingtheCdatastructurefora4x4matrix,theindexvaluesare
asfollows:

|0123|
M=|4567|
|891011|
|12131415|

Fromlookingatthesetwotables,itcanbeseethatarrayelement
[2]hasthevalueofDorsin(Y).Thentherotationangleinthe
Yaxiscanbecalculatedfromacalltototheinversesinefunction.
PassingthisvaluetothecosinefunctionthengivesthevalueofC.

IfCisnotzero,thentherotationanglesineachoftheXandZ
axii,canbederivedfromthetermsonthethirdcolumnandfirstrow
respectively.Theseareasfollows:

Xaxis:M[6]=BC
M[10]=AC

Zaxis:M[0]=CE
M[1]=CF

Theactualrotationanglescanbederivedbytakingeachpairofvalues
dividingbyCandpassingtheresultstotheinversetangentfunction.
IfCiszero,thenthesecalculationsarenotpossible.Inthiscase
therotationangleintheYaxiswillbeeither90or+90.ThusD
willeitherhavethevalueof1or1.
Inthiscase,GimbalLockwillhaveoccurred.Rotationsinboththe

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 22/34
4/2/2017 MatrixandQuaternionFAQ

XandZaxiiwillappeartobeinthesameaxis.Thiscanbeseen
throughtheevaluationoftherotationaxis.

|0.E0.F10|
M=|B.1.E+AFB.1.F+AEB.00|
|A.1.E+BFA.1.F+BEA.00|
|0001|

Multiplyingouteachtermgives:

|0010|
M=|BE+AFBF+AE00|
|AE+BFAF+BE00|
|0001|

Rearrangingthesetermsgives:

|0010|
M=|BE+AFAEBF00|
|(AEBF)BE+AF00|
|0001|

Thenitcanbeseenthatthematrixisreallyoftheform:

|0010|
M=|VW00|
|WV00|
|0001|

WhereVhasthevalueofBE+AFand
WhasthevalueofAEBF

Thesetwovaluescanbeconsideredtobethesinandcosineofa
singlerotationaxis.
Thefinalalgorithmisthenasfollows:

angle_y=D=asin(mat[2]);/*CalculateYaxisangle*/
C=cos(angle_y);
angle_y*=RADIANS;
if(fabs(C)>0.005)/*Gimballlock?*/
{
trx=mat[10]/C;/*No,sogetXaxisangle*/
try=mat[6]/C;
angle_x=atan2(try,trx)*RADIANS;
trx=mat[0]/C;/*GetZaxisangle*/
try=mat[1]/C;
angle_z=atan2(try,trx)*RADIANS;
}
else/*Gimballlockhasoccurred*/
{
angle_x=0;/*SetXaxisangletozero*/
trx=mat[5];/*AndcalculateZaxisangle*/
try=mat[4];
angle_z=atan2(try,trx)*RADIANS;
}

/*returnonlypositiveanglesin[0,360]*/
if(angle_x<0)angle_x+=360;
if(angle_y<0)angle_y+=360;
if(angle_z<0)angle_z+=360;

Q38.HowdoIgeneratearotationmatrixforaselectedaxisandangle?

Thesimplestwaytogeneratethistypeofrotationmatrixisthroughthe
useofquaternionmathematics.
Seequestion[Q53:HowdoIconvertaquaterniontoarotationmatrix?]
forfurtherdetails.
Thefollowingcodesnippeddoesmostofthework(phibeingtherotation

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 23/34
4/2/2017 MatrixandQuaternionFAQ

angleand(u,v,w)therotation(axis)vector):

rcos=cos(phi);
rsin=sin(phi);
matrix[0][0]=rcos+u*u*(1rcos);
matrix[1][0]=w*rsin+v*u*(1rcos);
matrix[2][0]=v*rsin+w*u*(1rcos);
matrix[0][1]=w*rsin+u*v*(1rcos);
matrix[1][1]=rcos+v*v*(1rcos);
matrix[2][1]=u*rsin+w*v*(1rcos);
matrix[0][2]=v*rsin+u*w*(1rcos);
matrix[1][2]=u*rsin+v*w*(1rcos);
matrix[2][2]=rcos+w*w*(1rcos);

Don'tforgettosettherestofthematrixto0(1at[3][3])if
youareusing4x4matrices!

Q39.HowdoIgeneratearotationmatrixtomaponevectorontoanother?

Whendevelopinganimationsoftware,acommonrequirementistofind
arotationmatrixthatwillmaponedirectionvectorontoanother.
Thisproblemmaybevisualisedbyconsideringthetwodirection
vectorstobeattachedattheirstartingpoints.Thentheentire
rotationspaceformsaunitsphere.
Intheory,thereareaninfinitenumberofrotationaxiiandangles
thatwillmaponevectorontotheother.Alloftheseaxiilieonthe
planewhereallofthepointsaretheexactsamedistancefromboth
vectors.
However,onlyonesolutionisofpracticalinterest.Thisisthepath
whichcoverstheshortestangulardistancebetweenthetwovectors.
Therotationaxistothispathiscalculatedbytakingthecross
productbetweenthetwovectors:

Vaxis=VsxVf

Therotationangleiscalculatedbytakingthedotproductbetweenthe
twovectors:

1
Vangle=cos(Vs.Vf)

Onepracticalapplicationofthesolutiontothisproblemisfinding
theshortestflightpathbetweentwocities.Inthiscase,eachcity
isrepresentedasadirectionvectorgeneratedfromspherical
coordinates.SinceplanetEarthisspherical,thedesiredflightpath
istheshortestangularrotationbetweenthetwocities.

Note:IfVsandVfarecolinear,thecrossproductreturns(0,0,0).
Youshouldtestforthatcaseanduseanyofthe90degreerotations
ofeitherVsorVfasarotationaxis,e.g.(y,z,x).Ifx==y==z,then
usingoneofx,y,orzfromthesecondvectormighthelp.
>Isthereabetterway?

Havingtherotationangleandvector,generatingthecorrespondingmatrix
iseasy,see[Q38:HowdoIgeneratearotationmatrixfor
aselectedaxisandangle?]fordetails.

Don'tletthespectreofGimbalLockfoolyou:Euleranglesarestill
acompleterepresentationofanyrotationin3Dspace;it'sjustthat
theactualEuleranglesneededtoachievesomeparticulardesired
rotationmayberatherunintuitive.

Q40.HowdoIusematricestoconvertonecoordinatesystemtoanother?

Similartothepreviousproblem,therequirementistomapone
coordinatesystemontoanother.However,insteadofjusttryingto
maponecoordinateaxisontoanother,allthreeaxiihavetobematched.
Bothcoordinatesystemsarethereforerepresentedaseither3x3or
4x4matrices.

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 24/34
4/2/2017 MatrixandQuaternionFAQ

Theproblemisthereforetofindtherotationmatrixthatwillmapone
matrixontoanother.Thiscanbeexpressedmathematically:

Mfinal=Mrot.Morig

whereMfinalisthefinalcoordinatesystemmatrix,
Morigistheoriginalcoordinatesystemand
Mrotisthedesiredrotationmatrix.

ThegoalisthentofindthematrixMrot.Thiscanbeachievedby
rearrangingtheequationtogive:

1
Mfinal.Morig=Mrot

1
Mrot=Mfinal.Morig

Thus,thedesiredrotationmatrixcanbebycalculatngtheinverseof
theoriginalcoordinatesystemandmultiplyingitwiththefinal
rotationmatrix.

Asacheck,considerthecaseswheneithertheoriginalorfinal
rotationmatricesaretheidentitymatrix.Ineachcase,therotation
matrixshouldmatchthefinalmatrixandtheinverseofthefinal
matrixrespectively.

Oncecalculated,therotationmatrixmaybeconvertedintoa
quaternion.

Q41.Whatisatranslationmatrix?

Atranslationmatrixisusedtopositionanobjectwithin3Dspace
withoutrotatinginanyway.Translationoperationsusingmatrix
multiplicationcanonlybeperformedusing4x4matrices.

Ifthetranslationisdefinedbythevector[XYZ],thenthe4x4
matrixtoimplementtranslationisasfollows:

|100X|
||
|010Y|
M=||
|001Z|
||
|0001|

Ifthevectoris[000]thenthevertexlistwillremainasbefore.

Q42.Whatisascalingmatrix?

Ascalingmatrixisusedtoenlargeorshrinkthesizeofa3Dmodel.
Ifthescalingvectoris[XYZ]thenthematrixtoperformthisis
asfollows:

|X000|
||
|0Y00|
M=||
|00Z0|
||
|0001|

Ifthescalingvectoris[111],thenthisgeneratestheidentity
matrixandvertexgeometrywillremainunchanged.

Q43.Whatisashearingmatrix?

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 25/34
4/2/2017 MatrixandQuaternionFAQ

Ashearingmatrixisusedtomakea3Dmodelappeartoslantsideways.
Forexample,"italic"textrequireseachcharactertoslanttowardsthe
right.
Inthreedimensionssixpossibleshearingdirectionsexist:

oshearXbyY
oshearXbyZ
oshearYbyX
oshearYbyZ
oshearZbyX
oshearZbyY

Allsixshearingdirectionsmaybecombinedintoasinglematrix:

|1SyxSzx0|
||
|Sxy1Szy0|
M=||
|SxzSyz10|
||
|0001|
||

WhereSijimplementsashearofIbyJ
Thus,SxyshearsXbyY

Intheory,rotationinthreedimensionsmaybeconsideredacombination
ofsixshearingdirections.

Q44.HowdoIperformlinearinterpolationbetweentwomatrices?

Giventworotationmatrices,theproblemistofindawayof
determiningintermediatepositionsspecifiedbyaparametric
variablet,wheretrangesfrom0.0to1.0
Thiscanbeachievedbyconvertingthetwomatricesintoeither
EuleranglesorSphericalrotationangles(viaquaternions)and
atranslationvector.

Ineithercase,eachmatrixisconvertedintoapairof3Dvectors.
Interpolationbetweenthesetwovectorscanthenbeperformed
throughtheuseofthestandardlinearinterpolationequation:

Vr=Va+t.(VbVa)

whereVristheresultingvector
Vaisthestartpositionvector
Vbisthefinalpositionvector

Thisequationmaybeappliedtobothtranslationandrotationvectors.
Oncedetermined,theresultingtranslationandrotationarethen
convertedbackintothedesiredintermediatematrix.

Q45.HowdoIperformcubicinterpolationbetweenfourmatrices?

Givenfourrotationortranslationmatrices,theproblemisto
findawayofdeterminingintermediatepositionsspecifiedbya
parametricvariablet.

Thiscanbeachievedbymakinguseofcubicinterpolation.Aswith
linearinterpolation,thefourmatricesareconvertedintotheir
correspondingtranslationandrotationvectors(Again,eitherEuler
anglesorsphericalrotationangles).

Eachsetoffourvectorsisthenconvertedintoasinglegeometry
vectorG.Throughtheuseofsplinemathematics,thisgeometryvector
isconvertedintoaninterpolationmatrixM.

Ifthegeometryvectorisdefinedas:

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 26/34
4/2/2017 MatrixandQuaternionFAQ

|x1x2x3x4|
G=|y1y2y3y4|
|z1z2z3z4|

Thenmultiplicationbythebasematrix:

|4.59.05.51.0|
Mb=|13.522.59.00.0|
|13.518.04.50.0|
|4.54.51.00.0|

willgeneratethe3x4interpolationmatrixMi:

Mi=G.Mb

Thiscanbeimplementedthroughastandardmatrixvectormultiplication.
Interpolationcanthenbeperformedbytheuseoftheparametric
variablet:

R=Mi.t

|t^3|
|xr||ABCD||t^2|
|yr|=|EFGH|.|t|
|zr||IJKL||1|

Theresultvectorcanthenbeconvertedbackintoarotationor
translationmatrix.

Itshouldbenotedthattherotationpathsthataregeneratedmay
occasionallybecomeratherloopy.Thisisnormal,asthealgorithm
istryingtofindthepathwiththeleastamountofrotationbetween
allfourvectors.

Ofthetwomethods,sphericalrotationangleswillusuallybeseento
providethecleanestinterpolationpathsforrotation.

Q46.HowcanIrenderamatrix?

Whenusingagraphicswindowfor3Danimation,itisconvenienttobe
abletoviewarotationmatrixconcurrentlywiththeanimation.
However,displayingarotationmatrixasanarrayofnumericvalues
doesnotprovideaverymeaningfulcontext.
Analternativetorenderingnumericdataistomakeuseofgraphical
displaymethodssuchasbargraphs.

Muchlikeagraphicequalizeronastereo,arotationmatrixmaybe
displayedinabargraphformat.Eachelementoftherotationmatrix
isrenderedasanindividualbargraphintherange1to+1.
A3x3matrixwouldlooklikethefollowing:

++++++
|##|||||
++++++
||||||
++++++

++++++
|||##|||
++++++
||||||
++++++

++++++
|||||##|
++++++
||||||
++++++

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 27/34
4/2/2017 MatrixandQuaternionFAQ

Inthiscase,therotationmatrixistheidentitymatrix,sinceeach
elementinthemajordiagonalis+1,andallothersarezero.
Foraddedvisualclarity,parameterswhicharenegativemayshaded
inadifferentcolourthanthosewhicharepositive.

QUATERNIONS
===========

Q47.Whatarequaternions?

Quaternionsextendtheconceptofrotationinthreedimensionsto
rotationinfourdimensions.Thisavoidstheproblemof"gimballock"
andallowsfortheimplementationofsmoothandcontinuousrotation.
Ineffect,theymaybeconsideredtoaddaadditionalrotationangle
tosphericalcoordinatesie.Longitude,LatitudeandRotationangles
AQuaternionisdefinedusingfourfloatingpointvalues|xyzw|.
Thesearecalculatedfromthecombinationofthethreecoordinates
oftherotationaxisandtherotationangle.

Q48.Howdoquaternionsrelateto3Danimation?

Asmentionedbefore,Eulerangleshavethedisadvantageofbeing
susceptibleto"Gimballock"whereattemptstorotatean
objectfailtoappearasexpected,duetotheorderinwhichthe
rotationsareperformed.

Quaternionsareasolutiontothisproblem.Insteadofrotatingan
objectthroughaseriesofsuccessiverotations,quaternionsallow
theprogrammertorotateanobjectthroughanarbitaryrotationaxis
andangle.

Therotationisstillperformedusingmatrixmathematics.However,
insteadofmultiplyingmatricestogether,quaternionsrepresenting
theaxiiofrotationaremultipliedtogether.Thefinalresulting
quaternionisthenconvertedtothedesiredrotationmatrix.
Becausetherotationaxisisspecifedasaunitdirectionvector,
itmayalsobecalculatedthroughvectormathematicsorfrom
sphericalcoordinatesie(longitude/latitude).
Quaternionsofferanotheradvantageinthattheybeinterpolated.
Thisallowsforsmoothandpredictablerotationeffects.

Q49.HowdoIcalculatetheconjugateofaquaternion?

Thiscanbeachievedbyreversingthepolarity(ornegating)the
vectorpartofthequaternion,ie:

Qr=(Qr.scalar,Qr.vector)

quaternion_conjugate(QUAT*qr,QUAT*qa)
{
qr>qw=qa>qw;
qr>qx=qa>qx;
qr>qy=qa>qy;
qr>qz=qa>qz;
}

Q50.HowdoIcalculatetheinverseofaquaternion?

Thisisequivalenttocalculatingtheconjugateofthequaternion,
ifthequaternionisnormalized(oraunitquaternion).
Inallothercases,themagnitudeoftheinverseis1/|q|.
SeeQ49:HowdoIcalculatetheconjugateofaquaternion?

Q51.HowdoIcalculatethemagnitudeofaquaternion?

Themagnitudeofaquaternioniscalculatedbymultiplyingthe
quaternionwithitsconjugateie:

/

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 28/34
4/2/2017 MatrixandQuaternionFAQ

|Qr|=\/Qr.Qr
Thiscanbeimplementedasthefollowingcodesequence:

QFLOATquaternion_magnitude(QUAT*qa)
{
return(sqrt(qa>qw*qa>qw+
qa>qx*qa>qx+qa>qy*qa>qy+qa>qz*qa>qz))
}

Q52.HowdoInormaliseaquaternion?

Aquaternioncanbenormalisedinawaysimilartovectors.The
magnitudeofthequaternioniscalculatedfirst.Thenboththe
scalarandvectorpartofthequaternionaredividedbythisvalue.
Aunitquaternionwillalwayshaveamagnitudeof1.0

Q53.HowdoImultiplytwoquaternionstogether?

GiventwoquaternionsQ1andQ2,thegoalistocalculatethe
combinedrotationQr:

Qr=Q1.Q2

Thisisachievedthroughtheexpression:

Qr=Q1.Q2=(w1.w2v1.v2,w1.v2+w2.v1+v1xv2)

wherev1=(x,y,z)ofQ1
w1=(w)ofQ1
v2=(x,y,z)ofQ2
w2=(w)ofQ2

andboth.andxarethestandardvectordotandcrossproducts.
Thiscanbeimplementedusingthefollowingcodesegment:

quaternion_multiply(QUAT*qr,QUAT*qa,QUAT*qb)
{
qr.scalar=qa>scalar*qb>scalarv3_dot(&qa>vector,&qb>vector);
v3_cross(&va,&qa>vector,&qb>vector);
v3_scalef(&vb,&qa>vector,&qb>scalar);
v3_scalef(&vc,&qb>vector,&qa>scalar);
v3_add(&va,&va,&vb);
v3_add(&qr>vector,&va,&vc);
quaternion_normalise(qr);
}


Anoptimizationcanalsobemadebyrearrangingto
w=w1w2x1x2y1y2z1z2
x=w1x2+x1w2+y1z2z1y2
y=w1y2+y1w2+z1x2x1z2
z=w1z2+z1w2+x1y2y1x2

Q54.HowdoIconvertaquaterniontoarotationmatrix?

Assumingthataquaternionhasbeencreatedintheform:

Q=|XYZW|

Thenthequaternioncanthenbeconvertedintoa4x4rotation
matrixusingthefollowingexpression(Warning:youmighthaveto
transposethismatrixifyou(donot)followtheOpenGLorder!):

22
1(2Y+2Z)2XY+2ZW2XZ2YW

22
M=2XY2ZW1(2X+2Z)2YZ+2XW

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 29/34
4/2/2017 MatrixandQuaternionFAQ

22
2XZ+2YW2YZ2XW1(2X+2Y)

Ifa4x4matrixisrequired,thenthebottomrowandrightmostcolumn
maybeadded.
Thematrixmaybegeneratedusingthefollowingexpression:

xx=X*X;
xy=X*Y;
xz=X*Z;
xw=X*W;
yy=Y*Y;
yz=Y*Z;
yw=Y*W;
zz=Z*Z;
zw=Z*W;
mat[0]=12*(yy+zz);
mat[1]=2*(xyzw);
mat[2]=2*(xz+yw);
mat[4]=2*(xy+zw);
mat[5]=12*(xx+zz);
mat[6]=2*(yzxw);
mat[8]=2*(xzyw);
mat[9]=2*(yz+xw);
mat[10]=12*(xx+yy);
mat[3]=mat[7]=mat[11]=mat[12]=mat[13]=mat[14]=0;
mat[15]=1;

Theresultingmatrixusesthefollowingpositions:

mat[0]mat[4]mat[8]mat[12]
M=mat[1]mat[5]mat[9]mat[13]
mat[2]mat[6]mat[10]mat[14]
mat[3]mat[7]mat[11]mat[15]

Q55.HowdoIconvertarotationmatrixtoaquaternion?

Arotationmaybeconvertedbacktoaquaternionthroughtheuseof
thefollowingalgorithm:
Theprocessisperformedinthefollowingstages,whichareasfollows:

CalculatethetraceofthematrixTfromtheequation:

222
T=44x4y4z

222
=4(1xyz)

=1+mat[0]+mat[5]+mat[10]

Ifthetraceofthematrixisgreaterthanzero,then
performan"instant"calculation.
Importantnotewrt.rouningerrors:

Testif(T>0.00000001)toavoidlargedistortions!

S=sqrt(T)*2;
X=(mat[9]mat[6])/S;
Y=(mat[2]mat[8])/S;
Z=(mat[4]mat[1])/S;
W=0.25*S;

Ifthetraceofthematrixisequaltozerothenidentify
whichmajordiagonalelementhasthegreatestvalue.
Dependingonthis,calculatethefollowing:

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 30/34
4/2/2017 MatrixandQuaternionFAQ

if(mat[0]>mat[5]&&mat[0]>mat[10]){ //Column0:
S=sqrt(1.0+mat[0]mat[5]mat[10])*2;
X=0.25*S;
Y=(mat[4]+mat[1])/S;
Z=(mat[2]+mat[8])/S;
W=(mat[9]mat[6])/S;
}elseif(mat[5]>mat[10]){ //Column1:
S=sqrt(1.0+mat[5]mat[0]mat[10])*2;
X=(mat[4]+mat[1])/S;
Y=0.25*S;
Z=(mat[9]+mat[6])/S;
W=(mat[2]mat[8])/S;
}else{ //Column2:
S=sqrt(1.0+mat[10]mat[0]mat[5])*2;
X=(mat[2]+mat[8])/S;
Y=(mat[9]+mat[6])/S;
Z=0.25*S;
W=(mat[4]mat[1])/S;
}

Thequaternionisthendefinedas:
Q=|XYZW|

Q56.HowdoIconvertarotationaxisandangletoaquaternion?

Givenarotationaxisandangle,thefollowing
algorithmmaybeusedtogenerateaquaternion:

vector_normalize(axis);
sin_a=sin(angle/2);
cos_a=cos(angle/2);
X=axis>x*sin_a;
Y=axis>y*sin_a;
Z=axis>z*sin_a;
W=cos_a;

Itisnecessarytonormalisethequaternionincaseanyvaluesare
veryclosetozero.

Q57.HowdoIconvertaquaterniontoarotationaxisandangle?

Aquaternioncanbeconvertedbacktoarotationaxisandangle
usingthefollowingalgorithm:

quaternion_normalise(|X,Y,Z,W|);
cos_a=W;
angle=acos(cos_a)*2;
sin_a=sqrt(1.0cos_a*cos_a);
if(fabs(sin_a)<0.0005)sin_a=1;
axis>x=X/sin_a;
axis>y=Y/sin_a;
axis>z=Z/sin_a;

Q58.HowdoIconvertsphericalrotationanglestoaquaternion?

Arotationaxisitselfmaybedefinedusingsphericalcoordinates
(latitudeandlongitude)andarotationangle
Inthiscase,thequaternioncanbecalculatedasfollows:

sin_a=sin(angle/2)
cos_a=cos(angle/2)
sin_lat=sin(latitude)
cos_lat=cos(latitude)
sin_long=sin(longitude)
cos_long=cos(longitude)
X=sin_a*cos_lat*sin_long
Y=sin_a*sin_lat
Z=sin_a*sin_lat*cos_long
W=cos_a

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 31/34
4/2/2017 MatrixandQuaternionFAQ

WARNING:Theremightbeaprobleminthiscode.
Analternativeisthecodesnippedgivenin[Q60:How
doIconvertEulerrotationanglestoaquaternion?"].

Q59.HowdoIconvertaquaterniontosphericalrotationangles?

Aquaternioncanbeconvertedtosphericalcoordinatesbyextending
theconversionprocess:

cos_a=W;
sin_a=sqrt(1.0cos_a*cos_a);
angle=acos(cos_a)*2;
if(fabs(sin_angle)<0.0005)sin_a=1;
tx=X/sin_a;
ty=Y/sin_a;
tz=Z/sin_a;
latitude=asin(ty);
if(tx*tx+tz*tz<0.0005)
longitude=0;
else
longitude=atan2(tx,tz);
if(longitude<0)
longitude+=360.0;

WARNING:Inthiscodemightstillbeaproblem.
Pleaseletmeknowwhatitisandhowtofixthis.

Q60.HowdoIconvertEulerrotationanglestoaquaternion?

ConvertingEulerrotationanglestoquaterionscanbeachievedthrough
theuseofquaternionmultiplication.Eachrotationangleisconverted
toanaxisanglepair,withtheaxiscorrespondingtooneofthe
Euclideanaxii.Theaxisanglepairsareconvertedtoquaternionsand
multipliedtogether.Thefinalquaternionisthedesiredresult.

Thefollowingcodesegmentdemonstratesthis:

quaternion_from_euler(QUATERNION*q,VFLOATax,VFLOATay,VFLOATaz)
{
VECTOR3vx={1,0,0},vy={0,1,0},vz={0,0,1};
QUATERNIONqx,qy,qz,qt;
quaternion_from_axisangle(qx,&vx,rx);
quaternion_from_axisangle(qy,&vy,ry);
quaternion_from_axisangle(qz,&vz,rz);
quaternion_multiply(&qt,&qx,&qy);
quaternion_multiply(&q,&qt,&qz);
}

Thefollowingmoreorlesscomesfrom:
http://vered.rose.utoronto.ca/people/david_dir/GEMS/GEMS.html

//Pitch>Xaxis,Yaw>Yaxis,Roll>Zaxis
Quaternion::Quaternion(floatfPitch,floatfYaw,floatfRoll)
{
constfloatfSinPitch(sin(fPitch*0.5F));
constfloatfCosPitch(cos(fPitch*0.5F));
constfloatfSinYaw(sin(fYaw*0.5F));
constfloatfCosYaw(cos(fYaw*0.5F));
constfloatfSinRoll(sin(fRoll*0.5F));
constfloatfCosRoll(cos(fRoll*0.5F));
constfloatfCosPitchCosYaw(fCosPitch*fCosYaw);
constfloatfSinPitchSinYaw(fSinPitch*fSinYaw);
X=fSinRoll*fCosPitchCosYawfCosRoll*fSinPitchSinYaw;
Y=fCosRoll*fSinPitch*fCosYaw+fSinRoll*fCosPitch*fSinYaw;
Z=fCosRoll*fCosPitch*fSinYawfSinRoll*fSinPitch*fCosYaw;
W=fCosRoll*fCosPitchCosYaw+fSinRoll*fSinPitchSinYaw;
}

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 32/34
4/2/2017 MatrixandQuaternionFAQ

Thefollowingmightalsowork:
QUATERNIONqx={cos(pitch/2f),sin(pitch/2f),0,0}
QUATERNIONqy={cos(yaw/2f),0,sin(yaw/2f),0}
QUATERNIONqz={cos(roll/2f),0,0,sin(roll/2f)}
quaternion_multiply(&qt,&qx,&qy);
quaternion_multiply(&q,&qt,&qz);

InJavalookslikethis:

publicstaticvoidsetQ(Quat4fq,floatpitch,floatyaw,floatroll)
{
Quat4fqx=newQuat4f((float)Math.cos(pitch/2f),
(float)Math.sin(pitch/2f),0,0);
Quat4fqy=newQuat4f((float)Math.cos(yaw/2f),0,
(float)Math.sin(yaw/2f),0);
Quat4fqz=newQuat4f((float)Math.cos(roll/2f),0,0,
(float)Math.sin(roll/2f));
Quat4fqt=newQuat4f();
qt.set(qx);
qt.mul(qy);
qt.mul(qz);
q.set(qt);
}

Q61.HowdoIusequaternionstoperformlinearinterpolationbetweenmatrices?

Formanyanimationapplications,itisnecessarytointerpolate
betweentworotationpositionsofagivenobject.Thesepositionsmay
havebeenspecifiedusingkeyframeanimationorinversekinematics.
Usingeithermethod,atleasttworotationmatricesmustbeknown,and
thedesiredgoalistointerpolatebetweenthem.Thetwomatricesare
referredtoasthestartingandfinishmatrices(MSandMF).
Usinglinearinterpolation,theinterpolatedrotationmatrixis
generatedusingablendingequationwiththeparameterT,which
rangesfrom0.0to1.0.

AtT=0,theinterpolatedmatrixisequaltothestartingmatrix.
AtT=1,theinterpolatedmatrixisequaltothefinishingmatrix.
Thentheinterpolatedrotationmatrix(MI)isspecifiedas:

MI=F(MS,MF,T)

whereFisablendingfunction.
Thefirststageininterpolatingbetweenthetwomatricesisto
determinetherotationmatrixthatwillconvertMStoMF.
Thisisachievedusingthefollowingexpression:

1
T=Ms.Mf

whereMsisthestartmatrix,
Mfisthefinishmatrix,
andTistheintermediatematrix.

Thenextstageistoconvertthismatrixintoarotationaxisand
angle.Thisisachievedbyconvertingthematrixintoaquaternion
andfinallyintotherequiredrotationaxisandangle.
Inordertogeneratetheinterpolatedrotationmatrix,itisonly
necessarytoscaletherotationangleandconvertthisangleand
therotationaxisbackintoarotationmatrix.

Usinga4x4matrixlibrary,thisisasfollows:

m4_transpose(mt,ms);/*Inverse*/
m4_mult(ms,mt,mb);/*Rotationmatrix*/
m4_to_axisangle(ms,axis,angle);/*Rotationaxis/angle*/
for(t=0;t<1.0;t+=0.05)
{

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 33/34
4/2/2017 MatrixandQuaternionFAQ

m4_from_axisangle(mi,axis,angle*t);/*Finalinterpolation*/
...whatever...
}

wheretistheinterpolationfactorrangingfrom0.0to1.0

Q62.HowdoIusequaternionstoperformcubicinterpolationbetweenmatrices?

Forsomeapplications,itmaynotbeconvenientorpossibletouselinear
interpolationforanimationpurposes.Inthiscase,cubicinterpolation
isanotheralternative.
Inordertousecubicinterpolation,atleastfourrotationmatricesmust
beknown.

Eachoftheseisthenconvertedintoasetofsphericalrotations
viaquaternionsandsphericalrotationangles(ie.longitude,latitude
androtationangle).

ThesearethenmultipliedwiththebasematrixforaCardinalspline
curve.Thisinterpolationmatrixcanthenbeusedtodeterminethe
intermediatesphericalrotationangles.
Oncetheinterpolatedcoordinatesareknown(latitude,longitudeand
rotationangle),theinterpolatedrotationmatrixcanthenbegenerated
throughtheconversiontoquaternions.

Usinga4x4matrixlibrary,thealgorithmisasfollows:

for(n=0;n<4;n++)
m4_to_spherical(mat[n],&v_sph[n]);/*Sphericalcoordinates*/
m4_multspline(m_cardinal,v_sph,v_interp);/*Interpolationvector*/
...
v3_cubic(v_pos,v_interp,t);/*Interpolation*/
m4_from_spherical(m_rot,v_pos);/*Backtoamatrix*/

Q63.HowdoIusequaternionstorotateavector?

Aratherelegantwaytorotateavectorusingaquaterniondirectly
isthefollowing(qrbeingtherotationquaternion):

1
v'=qr*v*qr

Thiscaneasilyberealisedandismostlikelyfasterthenthetransformation
usingarotationmatrix.

http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60 34/34