- What matrix multiplication means โ rows of A dot columns of B
- Why the inner dimensions must match (
m ร ntimesn ร p) - How to write a triple nested loop for the dot product
- Why the result has dimensions
m ร p - How matrix multiplication relates to machine learning, graphics, and linear systems
What matrix multiplication means
Matrix multiplication is not elementwise like addition. If C = A ร B, each cell of C is the dot product of a row of A with a column of B. Specifically, C[i][j] = sum over k of (A[i][k] ร B[k][j]) โ you multiply the corresponding entries of row i of A and column j of B, and sum the products. This is the most important operation in linear algebra, and the foundation of machine learning, computer graphics, and scientific computing.
The formula imposes a strict compatibility condition: for the dot product to be well-defined, row i of A (length n) must have the same length as column j of B (length n). That means A's number of columns must equal B's number of rows. So an m ร n matrix can multiply an n ร p matrix, and the result is m ร p. The inner dimensions (both n) must match, and the outer dimensions (both m and p) determine the result's shape.
This contrasts with matrix addition, which requires both matrices to have the same shape. Matrix multiplication is more flexible (different shapes can multiply) but stricter (the inner dimensions must match). It's also much more expensive: addition is O(mรn), but multiplication is O(mรnรp). For a 1000ร1000 matrix times another 1000ร1000, that's a billion multiplications โ a real workload for a modern CPU, and the reason GPUs are used for large matrix multiplications.
The reason matrix multiplication matters so much is that it expresses linear transformations. A matrix is a linear function that takes a vector and produces another vector. Composing two linear functions corresponds to multiplying their matrices. Neural networks are stacks of linear transformations (with nonlinearities in between), and training them involves billions of matrix multiplications. Graphics pipelines transform 3D coordinates by multiplying them with view, projection, and model matrices. Solving linear systems (like Ax = b) often involves matrix decompositions that are built on matrix multiplication. If you understand how one matrix times another works, you understand the fundamental operation of modern computing.
๐ก In one line: for each cell C[i][j], loop k over the shared dimension, accumulating A[i][k] * B[k][j]. Three nested loops โ one per dimension of the problem.
Designing the multiplyMatrices function
Three dimensions to track โ M (rows of A), N (cols of A = rows of B), P (cols of B):
| Part | Choice | Why |
|---|---|---|
| Function name | multiplyMatrices | Descriptive. Alternatives: matrixMultiply, matMul. |
| Input A | const int a[M][N] | Read-only. M ร N. |
| Input B | const int b[N][P] | Read-only. N ร P. The inner dimension N matches A's second dimension. |
| Output | int result[M][P] | M ร P โ outer dimensions only. The result has no N. |
| Return type | void | The result is written into the output parameter. |
The prototype:
#define M 2
#define N 3
#define P 2
void multiplyMatrices(const int a[M][N], const int b[N][P], int result[M][P]);
And the definition โ three nested loops:
void multiplyMatrices(const int a[M][N], const int b[N][P], int result[M][P]) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < P; j++) {
int sum = 0;
for (int k = 0; k < N; k++) {
sum += a[i][k] * b[k][j];
}
result[i][j] = sum;
}
}
}
Ten lines of logic. The outer two loops iterate over the result's cells โ M ร P cells total. The inner loop computes the dot product for each cell โ N multiplications and additions. So the total work is M ร P ร N multiplications, which is O(nยณ) for square matrices.
The pattern here is worth noting: sum is initialized to 0, and the inner loop accumulates into it. When the inner loop finishes, sum is the dot product for the current cell, and we store it in result[i][j]. This "accumulate, then store" shape is the essence of matrix multiplication โ and it's why the inner loop's variable is often called k, a convention borrowed from mathematical notation.
And a version that uses C99 VLAs for runtime-size matrices:
void multiplyMatricesVLA(int m, int n, int p,
const int a[m][n], const int b[n][p], int result[m][p]) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
int sum = 0;
for (int k = 0; k < n; k++) {
sum += a[i][k] * b[k][j];
}
result[i][j] = sum;
}
}
}
Same logic, but the dimensions are passed as parameters. This is more flexible โ you can multiply any compatible matrices at runtime. The VLA syntax requires C99 or later; for older compilers, you'd need to use fixed dimensions or dynamic allocation.
And here's an optimized version that improves cache behavior by transposing B first:
void multiplyTransposed(const int a[M][N], const int b[N][P], int result[M][P]) {
/* Transpose B so we can access column j as a row */
int bt[P][N];
for (int i = 0; i < N; i++)
for (int j = 0; j < P; j++)
bt[j][i] = b[i][j];
for (int i = 0; i < M; i++) {
for (int j = 0; j < P; j++) {
int sum = 0;
for (int k = 0; k < N; k++) {
sum += a[i][k] * bt[j][k]; /* both accessed along rows */
}
result[i][j] = sum;
}
}
}
The original code accesses b[k][j] โ walking down column j of B, which is not cache-friendly in row-major storage (each access jumps to the next row, potentially a different cache line). Transposing B first gives you bt[j][k], which walks bt's row j contiguously โ much faster on modern CPUs. This transpose-and-multiply technique is a classic optimization, and it's the kind of trick you'll see in optimized libraries like BLAS.
๐ฏ Key idea: the inner loop computes a dot product โ sum of products across the shared dimension N. The outer two loops assign the result to each cell of the M ร P output. Get this pattern right, and matrix multiplication is done.
Complete C Program
Program: read two matrices, multiply them, print the result
#include <stdio.h>
#define M 2
#define N 3
#define P 2
/* Function prototype */
void multiplyMatrices(const int a[M][N], const int b[N][P], int result[M][P]);
int main(void) {
int A[M][N], B[N][P], C[M][P];
printf("Enter matrix A (%d rows, %d columns):\n", M, N);
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
if (scanf("%d", &A[i][j]) != 1) return 1;
printf("Enter matrix B (%d rows, %d columns):\n", N, P);
for (int i = 0; i < N; i++)
for (int j = 0; j < P; j++)
if (scanf("%d", &B[i][j]) != 1) return 1;
multiplyMatrices(A, B, C);
printf("\nMatrix A:\n");
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) printf("%4d", A[i][j]);
printf("\n");
}
printf("\nMatrix B:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < P; j++) printf("%4d", B[i][j]);
printf("\n");
}
printf("\nMatrix A * B:\n");
for (int i = 0; i < M; i++) {
for (int j = 0; j < P; j++) printf("%4d", C[i][j]);
printf("\n");
}
return 0;
}
/* Matrix multiplication โ three nested loops */
void multiplyMatrices(const int a[M][N], const int b[N][P], int result[M][P]) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < P; j++) {
int sum = 0;
for (int k = 0; k < N; k++) {
sum += a[i][k] * b[k][j];
}
result[i][j] = sum;
}
}
}
And a version that traces the computation of each result cell, useful for understanding:
Variant: verbose multiplication with step trace
#include <stdio.h>
#define M 2
#define N 3
#define P 2
void multiplyVerbose(const int a[M][N], const int b[N][P], int result[M][P]) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < P; j++) {
int sum = 0;
printf("C[%d][%d] = ", i, j);
for (int k = 0; k < N; k++) {
int term = a[i][k] * b[k][j];
sum += term;
printf("%d*%d", a[i][k], b[k][j]);
if (k < N - 1) printf(" + ");
}
printf(" = %d\n", sum);
result[i][j] = sum;
}
}
}
int main(void) {
int A[M][N] = {{1, 2, 3}, {4, 5, 6}};
int B[N][P] = {{7, 8}, {9, 10}, {11, 12}};
int C[M][P];
multiplyVerbose(A, B, C);
return 0;
}
The verbose variant prints each dot product: "C[0][0] = 1*7 + 2*9 + 3*11 = 58". This makes the algorithm transparent โ you can see exactly what matrix multiplication computes for each cell, and verify by hand that the results are correct.
And a version that handles runtime matrix sizes:
Variant: any-size matrices with VLAs
#include <stdio.h>
void multiply(int m, int n, int p,
int a[m][n], int b[n][p], int result[m][p]) {
for (int i = 0; i < m; i++)
for (int j = 0; j < p; j++) {
int sum = 0;
for (int k = 0; k < n; k++) sum += a[i][k] * b[k][j];
result[i][j] = sum;
}
}
int main(void) {
int m = 2, n = 3, p = 4;
int A[m][n], B[n][p], C[m][p];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) A[i][j] = i + j;
for (int i = 0; i < n; i++)
for (int j = 0; j < p; j++) B[i][j] = i * j + 1;
multiply(m, n, p, A, B, C);
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) printf("%5d", C[i][j]);
printf("\n");
}
return 0;
}
This version lets you multiply matrices of any compatible shape at runtime. The VLA syntax requires C99; for older compilers, you'd need dynamic allocation with malloc and pointer arithmetic for indexing.
Program Output
A typical run with simple matrices:
Enter matrix A (2 rows, 3 columns):
1 2 3
4 5 6
Enter matrix B (3 rows, 2 columns):
7 8
9 10
11 12
Matrix A:
1 2 3
4 5 6
Matrix B:
7 8
9 10
11 12
Matrix A * B:
58 64
139 154
Let's verify the first cell: C[0][0] = 1ร7 + 2ร9 + 3ร11 = 7 + 18 + 33 = 58. โ
C[0][1] = 1ร8 + 2ร10 + 3ร12 = 8 + 20 + 36 = 64. โ
C[1][0] = 4ร7 + 5ร9 + 6ร11 = 28 + 45 + 66 = 139. โ
C[1][1] = 4ร8 + 5ร10 + 6ร12 = 32 + 50 + 72 = 154. โ
All four cells are correct. Note the shapes: A is 2ร3, B is 3ร2, and the result is 2ร2. The inner dimension (3) cancels out โ you can see it in the fact that the result has no 3 in its shape.
With identity matrices:
Enter matrix A (2 rows, 3 columns):
1 2 3
4 5 6
Enter matrix B (3 rows, 2 columns):
1 0
0 1
0 0
Matrix A * B:
1 2
4 5
Here B is an identity-like matrix (a 3ร2 subset of the 3ร3 identity). Multiplying A by it essentially projects out the first two columns of A โ C[i][j] = A[i][j] for j=0,1. This demonstrates that the "identity matrix" acts as the multiplicative identity: multiplying by it leaves the matrix unchanged (for compatible shapes). Matrix multiplication has an identity, just like scalar multiplication.
With a zero matrix:
Enter matrix A (2 rows, 3 columns):
1 2 3
4 5 6
Enter matrix B (3 rows, 2 columns):
0 0
0 0
0 0
Matrix A * B:
0 0
0 0
Multiplying any matrix by the zero matrix gives the zero matrix, regardless of shape. This is the analog of x ร 0 = 0 for scalars. The result is always zero, which is a useful sanity check.
And the verbose version on the first example:
C[0][0] = 1*7 + 2*9 + 3*11 = 58
C[0][1] = 1*8 + 2*10 + 3*12 = 64
C[1][0] = 4*7 + 5*9 + 6*11 = 139
C[1][1] = 4*8 + 5*10 + 6*12 = 154
Each line shows one dot product: the pairs being multiplied, then the sum. This is the clearest way to see what matrix multiplication actually does โ every result cell is one of these sums of products.
Step-by-Step Explanation
Let's trace the algorithm and look at the triple-loop structure.
1. The three nested loops
The outer loop i goes over the rows of the result (rows of A). The middle loop j goes over the columns of the result (columns of B). The inner loop k goes over the shared dimension (columns of A = rows of B). So each combination of (i, j) defines a result cell, and the inner loop computes the dot product for that cell.
The order of the loops matters for cache performance but not for correctness. In a row-major layout, iterating k innermost gives the best cache behavior for a[i][k] (contiguous access) but the worst for b[k][j] (column-by-column). Transposing B or reordering loops can speed things up considerably, but the algorithm is the same.
2. The sum variable
int sum = 0; โ the accumulator for the dot product. The inner loop adds products to it, one at a time: sum += a[i][k] * b[k][j]. After the loop, sum holds the full dot product. It's declared inside the middle loop, so it's freshly initialized to 0 for each cell. If you declared it outside the loops and forgot to reset it, you'd get the wrong result โ a common bug in matrix multiplication code.
3. Tracing multiplyMatrices for the 2ร3 ร 3ร2 example
A = {{1, 2, 3}, {4, 5, 6}} (2ร3), B = {{7, 8}, {9, 10}, {11, 12}} (3ร2). Expected result: 2ร2.
i=0, j=0 (top-left cell):
- k=0: sum += A[0][0] * B[0][0] = 1 * 7 = 7. sum = 7.
- k=1: sum += A[0][1] * B[1][0] = 2 * 9 = 18. sum = 25.
- k=2: sum += A[0][2] * B[2][0] = 3 * 11 = 33. sum = 58.
- Store C[0][0] = 58.
i=0, j=1 (top-right cell):
- k=0: sum += A[0][0] * B[0][1] = 1 * 8 = 8. sum = 8.
- k=1: sum += A[0][1] * B[1][1] = 2 * 10 = 20. sum = 28.
- k=2: sum += A[0][2] * B[2][1] = 3 * 12 = 36. sum = 64.
- Store C[0][1] = 64.
i=1, j=0 (bottom-left cell):
- k=0: sum += A[1][0] * B[0][0] = 4 * 7 = 28. sum = 28.
- k=1: sum += A[1][1] * B[1][0] = 5 * 9 = 45. sum = 73.
- k=2: sum += A[1][2] * B[2][0] = 6 * 11 = 66. sum = 139.
- Store C[1][0] = 139.
i=1, j=1 (bottom-right cell):
- k=0: sum += A[1][0] * B[0][1] = 4 * 8 = 32. sum = 32.
- k=1: sum += A[1][1] * B[1][1] = 5 * 10 = 50. sum = 82.
- k=2: sum += A[1][2] * B[2][1] = 6 * 12 = 72. sum = 154.
- Store C[1][1] = 154.
Result: C = {{58, 64}, {139, 154}}. This matches the expected output. โ
4. Dimension compatibility
For matrix multiplication to be valid, A's column count must equal B's row count. In our example, A is 2ร3 and B is 3ร2, so the shared dimension is 3 โ matches. The result is 2ร2. If you tried to multiply A (2ร3) by a matrix C (2ร5), the inner dimensions wouldn't match (3 โ 2), and the formula wouldn't be well-defined. Our program's type signature enforces this: a[M][N] times b[N][P] โ the shared N dimension is explicit in both parameters.
5. Non-commutativity
Matrix multiplication is not commutative: A ร B โ B ร A in general. Even for square matrices, the order matters โ this is one of the key differences from scalar multiplication. In fact, sometimes A ร B is defined but B ร A isn't (when dimensions don't match in the reverse order), or they produce results of different shapes. This is why matrix multiplication is written explicitly with the order, never as "A times B" in the commutative sense.
6. The O(nยณ) complexity
For m ร n times n ร p, the total number of multiplications is m ร n ร p. For square nรn matrices, that's nยณ. For n=100, that's a million multiplications โ noticeable but fast. For n=1000, that's a billion โ a second or so on a modern CPU. For n=10,000, that's 10ยนยฒ โ seconds to minutes, which is why large-scale matrix multiplication (like deep learning) relies on GPUs, whose thousands of cores are optimized exactly for this kind of parallel workload.
7. Cache optimization
Naive triple-loop matrix multiplication is O(nยณ) in time but also incurs cache misses: b[k][j] walks down a column of B, which is not contiguous in memory (row-major storage). Transposing B first, or using blocked (tiled) multiplication, dramatically improves performance by ensuring cache locality. For a 1000ร1000 matrix, transposed multiplication can be 2โ3ร faster than the naive version โ a real and significant gain. This is one of the first optimizations taught in high-performance computing, and it's why BLAS libraries are so heavily tuned.
8. Matrix multiplication in machine learning
In a neural network, each layer computes Y = X ร W + b โ a matrix multiply of the input batch X (batch_size ร input_dim) with the weight matrix W (input_dim ร output_dim), plus a bias vector b. That's the fundamental operation, repeated across dozens or hundreds of layers, for every training batch, for hours. Modern GPUs can do trillions of matrix multiplications per second, precisely because this operation is so important. Understanding it at the C level โ the triple loop, the dot product per cell โ gives you insight into what the hardware is doing under the abstractions of deep learning frameworks.
9. Association and distributivity
Matrix multiplication is associative: (A ร B) ร C = A ร (B ร C). This is important because it means you can compute A ร B ร C in either order, and get the same result โ but the cost can differ dramatically. For example, if A is 1000ร10, B is 10ร10, and C is 10ร1000, computing (A ร B) ร C costs 1000ร10ร10 + 1000ร10ร1000 = 100,000 + 10,000,000 = 10 million operations. Computing A ร (B ร C) costs 10ร10ร1000 + 1000ร10ร1000 = 100,000 + 10,000,000 = also 10 million โ but the intermediate matrices have different sizes, so memory usage differs. In large systems, choosing the right association order can be a significant optimization. This is called dynamic programming for chain matrix multiplication, and it's a classic interview problem.
10. Beyond integers: floating-point and other types
Our implementation uses int, but matrix multiplication works for any type that supports addition and multiplication โ float, double, complex numbers, quaternions, even polynomials. For floating-point matrices, you'd change the parameter types to const double a[...][...], use double sum = 0.0, and everything else stays the same. Numerical stability becomes a concern for floating-point (catastrophic cancellation, ordering effects), but the algorithm is unchanged. The simplicity of the triple loop is its strength: it generalizes to any arithmetic system.
๐ Try this: verify associativity by computing (A ร B) ร C vs A ร (B ร C) for some small matrices. The results should be identical. Then compute the number of multiplications each way, and check whether one is faster. For "tall-skinny" matrices, one order is usually much cheaper than the other โ a nice demonstration of why matrix multiplication is both mathematically elegant and computationally expensive.
Frequently Asked Questions
1. Why is matrix multiplication O(nยณ)?
Because it has three nested loops, each of size n for nรn matrices. The outer two loops iterate over the nยฒ cells of the result. The inner loop iterates n times to compute each cell's dot product. So the total number of multiplications is n ร n ร n = nยณ. For 100ร100 matrices, that's 1 million operations. For 1000ร1000, it's a billion โ a real cost that drives GPU optimization. There are sub-cubic algorithms (Strassen's is O(n^2.81), and there are theoretical algorithms as low as O(n^2.37)), but they have large constants and are rarely faster in practice for realistic sizes.
2. Why must A's columns equal B's rows?
Because each result cell is the dot product of a row of A and a column of B. A row of A has length = number of columns of A. A column of B has length = number of rows of B. For the dot product to make sense, these lengths must be equal. That's the compatibility condition: A is m ร n, B must be n ร p, and the result is m ร p. The inner dimension n must match; the outer dimensions can be anything.
3. Why doesn't A ร B = B ร A?
Because each cell of A ร B is a dot product of A's row with B's column, while each cell of B ร A is a dot product of B's row with A's column โ different cells entirely. Even for square matrices (where both products are defined), the results differ. In fact, A ร B might be defined while B ร A isn't (if dimensions are compatible one way but not the other). This non-commutativity is a key property of matrix algebra and one of the reasons it's a richer structure than scalar arithmetic.
4. Why does matrix multiplication matter so much?
Because it expresses linear transformations and their compositions. Many real-world operations are linear (or approximated as linear): rotations, projections, scaling, convolutions (in neural networks), translations (in graphics). Composing two such transformations corresponds to multiplying their matrices. So matrix multiplication is the fundamental operation behind machine learning (every layer's forward pass), computer graphics (every 3D transformation), physics simulations (solving linear systems, computing eigenvalues), and much more. Understanding it at the code level is the foundation for understanding all of these fields.
5. How do I speed up matrix multiplication?
Several techniques. (a) Transpose B before multiplying, so the inner loop accesses both A's row and B's row contiguously โ improves cache locality dramatically. (b) Block (tile) the multiplication โ break the matrices into small blocks and multiply block by block, keeping blocks in cache. (c) Use SIMD instructions โ modern CPUs can do 4, 8, or 16 floating-point operations per instruction. (d) Use multi-threading โ divide the work across cores. (e) Use GPUs โ thousands of cores optimized for matrix operations. (f) Use sub-cubic algorithms like Strassen (rarely worth it in practice). Libraries like BLAS, cuBLAS, and Intel MKL implement all these tricks and more. Our naive triple loop is 10โ100ร slower than a well-optimized library โ that's why everyone uses libraries.
6. Can I multiply matrices of different element types?
Yes, in principle โ but you need to decide what the result type should be. For example, int ร int gives int (with potential overflow). int ร double usually promotes to double. float ร float gives float (with rounding). Complex numbers multiply via (a + bi)(c + di) = (ac - bd) + (ad + bc)i โ a different formula per element. In C, you'd have separate functions for each type combination, or use generics (C11 _Generic, or a C++ template equivalent). For teaching, we stick to int; for production, use a library that handles all the type combinations.
๐ก Tip: Once this works, try the transposed-B optimization: transpose B first, then rewrite the inner loop as sum += a[i][k] * bt[j][k]. Benchmark both versions on a large matrix (say, 500ร500) โ you should see a 2โ3ร speedup on modern hardware. Then try a blocked version: split the matrices into 32ร32 blocks and multiply block by block. That's the technique used in real BLAS libraries, and it can give another 2โ3ร speedup. These exercises show you how much you can squeeze out of the same O(nยณ) algorithm with just better memory access patterns.