Matrices are tables of numbers used for graphics transformations, graph adjacency, systems of equations and machine learning. Multiplying two of them is one of the most common heavy computations in computing. This page analyses the standard method.
The problem
The algorithm
Matrix multiplication pseudocode
MatrixMultiply(A, B, n)for i ← 0 to n − 1 do for j ← 0 to n − 1 do C[i][j] ← 0 for k ← 0 to n − 1 do C[i][j] ← C[i][j] + A[i][k] * B[k][j]return C
Analysis
The outer loop runs n times; for each i the middle loop runs n times, so the assignment C[i][j] ← 0 runs n2 times.
For each (i,j) the inner loop runs n times, so the multiply-add line runs n⋅n⋅n=n3 times.
Total: n3 multiplications, n3 additions and n2 initialisations, i.e. Θ(n3).
The input itself has 2n2 numbers, so the algorithm does about n operations per input number.
C · matrix_mult.c
#include <stdio.h>#define N 3int main(void){ int A[N][N] = {{1, 2, 3}, {2, 3, 4}, {4, 5, 6}}; int B[N][N] = {{1, 1, 1}, {2, 3, 2}, {3, 2, 1}}; int C[N][N]; long mults = 0; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) { C[i][j] = 0; for (int k = 0; k < N; k++) { C[i][j] += A[i][k] * B[k][j]; mults++; } } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf("%4d", C[i][j]); printf("\n"); } printf("multiplications: %ld = n^3 = %d\n", mults, N * N * N); return 0;}
This program answers Check Your Progress 2 with fixed matrices. The study material’s version reads the matrices with scanf; that works too, but a program that reads input should check that scanf returned 1 for each value.
Key takeaways
cij=∑kaikbkj: row i of A times column j of B.
Three nested loops of n: n3 multiplications and additions.
The standard algorithm is Θ(n3).
Initialise each cij to 0 before summing.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Multiply A=(1324) and B=(5768) and state how many multiplications you used.
Show worked answer
c₁₁ = 1·5 + 2·7 = 19; c₁₂ = 1·6 + 2·8 = 22; c₂₁ = 3·5 + 4·7 = 43; c₂₂ = 3·6 + 4·8 = 50. So C = [[19, 22], [43, 50]]. Each entry used 2 multiplications, 8 = 2³ in total.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-211/complexity-analysis-of-simple-algorithms/matrix-multiplication/ to read this page.