Matrix Representation
While working with libraries like OpenGL, matrices are represented as a 16-element array. There are two representations, row- or column-major and this indicates how elements are stored and manipulated. So if a translation matrix looks like this:
For OpenGL, which uses column-major style, elements
,
, and
are accessed with indices 13, 14, and 15. In a system that uses row-major style, these same elements will be accessed with indices 3, 7, and 11. The code fragments below uses column-major style.
Matrix Multiplication
Finding matrix product of two
matrices
and
involves calculating for each element:
In C code this translates to a function like:
void Multiply( const float* A, float* B )
{
float t[16];
t[0] = A[0] * B[0] + A[1] * B[4] + A[2] * B[8] + A[3] * B[12];
t[1] = A[0] * B[1] + A[1] * B[5] + A[2] * B[9] + A[3] * B[13];
t[2] = A[0] * B[2] + A[1] * B[6] + A[2] * B[10] + A[3] * B[14];
t[3] = A[0] * B[3] + A[1] * B[7] + A[2] * B[11] + A[3] * B[15];
t[4] = A[4] * B[0] + A[5] * B[4] + A[6] * B[8] + A[7] * B[12];
t[5] = A[4] * B[1] + A[5] * B[5] + A[6] * B[9] + A[7] * B[13];
t[6] = A[4] * B[2] + A[5] * B[6] + A[6] * B[10] + A[7] * B[14];
t[7] = A[4] * B[3] + A[5] * B[7] + A[6] * B[11] + A[7] * B[15];
t[8] = A[8] * B[0] + A[9] * B[4] + A[10] * B[8] + A[11] * B[12];
t[9] = A[8] * B[1] + A[9] * B[5] + A[10] * B[9] + A[11] * B[13];
t[10] = A[8] * B[2] + A[9] * B[6] + A[10] * B[10] + A[11] * B[14];
t[11] = A[8] * B[3] + A[9] * B[7] + A[10] * B[11] + A[11] * B[15];
t[12] = A[12] * B[0] + A[13] * B[4] + A[14] * B[8] + A[15] * B[12];
t[13] = A[12] * B[1] + A[13] * B[5] + A[14] * B[9] + A[15] * B[13];
t[14] = A[12] * B[2] + A[13] * B[6] + A[14] * B[10] + A[15] * B[14];
t[15] = A[12] * B[3] + A[13] * B[7] + A[14] * B[11] + A[15] * B[15];
// result overwrites B
memcpy(B, t, sizeof(float) * 16);
}
Transforms
Apply transforms is the same as multiplying with the corresponding transformation matrices.
Translate
To move by a translation vector
:
Scale
To scale by a factor in each axis:
Rotate
Basic rotations about the x, y, and z axes:
rotates the y-axis towards the z-axis
rotates the z-axis towards the x-axis
rotates the x-axis towards the y-axis
To rotate
radians about an arbitrary, normalized axis
:
where

and

Shear
To apply shear along x-, y-, or z-axis, modify the coefficients below:
References
- Akenine-Moller, Tomas and Eric Haines, Real-Time Rendering 2nd Edition, A K Peters: 42-43, 725.