To main page | 3dengine.org

Matrix Math


Matrix math is presented for row-major matrices. Please note that OpenGL stores matrices in column-major order.

Addition of matrices

Just add the corresponding elements:
[0  1  2]     [6  7  8]     [0+6  1+7  2+8]   [6   8 10]
[3  4  5]  +  [9 10 11]  =  [3+9 4+10 5+11] = [12 14 16]

Multiplication of matrices

Rules:
Matrix A multiplied by matrix B is not the same as matrix B multiplied by A.
Matrix A multiplied by matrix B assumes right-multiplication (i.e. B goes to the right of A).
The size of matrix is 2x3 means it has 2 rows of numbers and 3 columns.
The number of columns must be equal to number of rows in second matrix.
If the size of matrix A is 2x3 and matrix B is 3x4 then the result is 2x4: 2x3 x 3x4 = 2x4. (In most cases OpenGL matrices are 4x4 and result of multiplication of two 4x4 matrices is 4x4 matrix).
To find element 3,2 of new matrix: multiply 3rd LINE of matrix A by 2nd COLUMN of matrix B.

Always multiply line by column
[0 1 2]   [6  7 ]    [0*6+1*8+2*10 0*7+1*9+2*11]   [28 31]
[3 4 5] x [8  9 ] =  [3*6+4*8+5*10 3*7+4*9+5*11] = [100 112]
          [10 11]
OpenGL math is the same:
GLfloat m1[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
glLoadMatrixf(m1);
GLfloat m2[] = {16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
glMultMatrixf(m2);
// result in current matrix will be {440,510,580,650,536,.... see below
meaning:
[ 0 4  8 12 ]   [ 16 20 24 28 ]   [ 440  536  632  728 ]
[ 1 5  9 13 ] x [ 17 21 25 29 ] = [ 510  622  734  846 ]
[ 2 6 10 14 ]   [ 18 22 26 30 ]   [ 580  708  836  964 ]
[ 3 7 11 15 ]   [ 19 23 27 31 ]   [ 650  794  938 1082 ]

440 = 0*16 + 4*17 + 8*18 + 12*19 : 
1st line [0 4 8 12] by 1st column [16 17 18 19]

Transpose

Matrix Transpose is basically flipping a matrix along it's diagonal. It converts row-major to column-major matrices and vice versa.
[  0  1  2  3 ] T     [ 0 4  8 12 ] 
[  4  5  6  7 ]       [ 1 5  9 13 ] 
[  8  9 10 11 ]    =  [ 2 6 10 14 ] 
[ 12 13 14 15 ]       [ 3 7 11 15 ] 
The diagonal of both matrices is elements [0 5 10 15].