# 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] = | a_{0}a_{4}a_{8}a_{12}| | a_{1}a_{5}a_{9}a_{13}| | a_{2}a_{6}a_{10}a_{14}| | a_{3}a_{7}a_{11}a_{15}|

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 d_{k} for each k from 0 to s-1

Let r be the row where we find d_{k} as numbered from 0 to t-1.
Let c be the column where we find d_{k} as numbered from 0 to t-1

For each d_{k} we want to take the dot-product of the corresponding row in A and the corresponding column in B.

Therefore, d_{k} = 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