Matrix Multiplication
Copyright © 2002 - Angelo Bertolli
A little bit of math goes a long way when dealing with matrices. I have found it much easier and less confusing to do matrix multiplication using long single-dimensional arrays. This article will guide you through how to multiply such matrices and provides C code.
Let's say we declare 4 x 4 matrices as A[16], B[16], and D[16] (some floating point type) as they would use in OpenGL. Therefore:
[A][B] = [D]
Where the matrices are structured (as in OpenGL):
[A] = | a0 a4 a8 a12 |
| a1 a5 a9 a13 |
| a2 a6 a10 a14 |
| a3 a7 a11 a15 |
Let s be the size of the square matrix. Let t be the number of elements in a row or column.
We want to find dk for each k from 0 to s-1
Let r be the row where we find dk as numbered from 0 to t-1. Let c be the column where we find dk as numbered from 0 to t-1
For each dk we want to take the dot-product of the corresponding row in A and the corresponding column in B.
Therefore, dk = the sum over i from 0 to t-1 of [a(r+it) * b(ct+i)], where r = k mod t and c = k div t (integer modulo and division)
Code
double A[16];
double B[16];
double D[16];
int s = 16
int t = 4
int r;
int c;
for (int k=0;k<s;k++) {
r = k % t;
c = (int)(k / t);
D[k] = 0.0;
for (int i=0;i<t;i++)
D[k] += A[r+(i*t)] * B[(c*t)+i];
}
Angelo's Computer Page