Matrix-Chain Multiplication: The Table
The previous lesson reduced the best order for a matrix chain to the recurrence
over the subchains . This lesson evaluates it bottom-up. The new question compared to rod cutting is the order: needs entries in its own row to the left and in its own column below, so neither "row by row from the top" nor "column by column" works directly. What does work is to fill the table by chain length: every subchain that depends on is strictly shorter than .
Watch the table fill
The animation fills the upper triangle of the table for the running example , one diagonal at a time: length 1 (the zeros on the main diagonal), then all subchains of length 2, then 3, and so on up to the corner . At each step it lists the candidate cost of every split .
The algorithm
MATRIX-CHAIN-ORDER(p) // A_i is p[i-1] x p[i], i = 1..n
1 n = length(p) - 1
2 m = new table [1..n, 1..n]; s = new table [1..n, 1..n]
3 for i = 1 to n
4 m[i, i] = 0
5 for len = 2 to n // chain length
6 for i = 1 to n - len + 1
7 j = i + len - 1
8 m[i, j] = infinity
9 for k = i to j - 1 // last multiplication A_{i..k} times A_{k+1..j}
10 cost = m[i, k] + m[k + 1, j] + p[i - 1] * p[k] * p[j]
11 if cost < m[i, j]
12 m[i, j] = cost
13 s[i, j] = k // remember the best split
14 return m, sThe table is indexed from 1 to match the matrix names; the Python version uses a list with an unused row and column 0. It prints one line per entry, the same text as the animation's steps.
def matrix_chain_order(p):
n = len(p) - 1
INF = float("inf")
m = [[0] * (n + 1) for _ in range(n + 1)]
s = [[0] * (n + 1) for _ in range(n + 1)]
for length in range(2, n + 1):
for i in range(1, n - length + 2):
j = i + length - 1
m[i][j] = INF
tries = []
for k in range(i, j):
cost = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]
tries.append(f"k={k}: {cost}")
if cost < m[i][j]:
m[i][j], s[i][j] = cost, k
print(f"m[{i}][{j}] = min({', '.join(tries)}) = {m[i][j]}")
return m, s
def parens(s, i, j):
if i == j:
return f"A{i}"
return "(" + parens(s, i, s[i][j]) + parens(s, s[i][j] + 1, j) + ")"
p = [12, 4, 10, 3, 8, 5]
m, s = matrix_chain_order(p)
n = len(p) - 1
print("m table (row i, columns i..n):")
for i in range(1, n + 1):
print(" " + " " * (i - 1) + "".join(f"{m[i][j]:6}" for j in range(i, n + 1)))
print("best order:", parens(s, 1, n), "with", m[1][n], "scalar multiplications")m[1][2] = min(k=1: 480) = 480
m[2][3] = min(k=2: 120) = 120
m[3][4] = min(k=3: 240) = 240
m[4][5] = min(k=4: 120) = 120
m[1][3] = min(k=1: 264, k=2: 840) = 264
m[2][4] = min(k=2: 560, k=3: 216) = 216
m[3][5] = min(k=3: 270, k=4: 640) = 270
m[1][4] = min(k=1: 600, k=2: 1680, k=3: 552) = 552
m[2][5] = min(k=2: 470, k=3: 300, k=4: 376) = 300
m[1][5] = min(k=1: 540, k=2: 1350, k=3: 564, k=4: 1032) = 540
m table (row i, columns i..n):
0 480 264 552 540
0 120 216 300
0 240 270
0 120
0
best order: (A1((A2A3)(A4A5))) with 540 scalar multiplications
The corner entry matches the cheapest of the 14 orders found by brute force in the previous lesson, and the printed order is the same one. Read the line for : the split after costs 540, while splitting after (cost 564) is the runner-up. Splitting after is the worst at 1350: its last multiplication alone, by , costs 600, and the subchain still has to be paid for.
Reconstructing the order
The table stores for every subchain the split of its last multiplication, exactly like the first-piece table in Reconstructing an Optimal Solution. The function parens above reads it recursively: the outermost product of splits at ; the right side splits at , giving . To check that the order really costs what the table promises, the program below multiplies actual matrices in that order and counts.
def matrix_chain_order(p):
n = len(p) - 1
m = [[0] * (n + 1) for _ in range(n + 1)]
s = [[0] * (n + 1) for _ in range(n + 1)]
for length in range(2, n + 1):
for i in range(1, n - length + 2):
j = i + length - 1
m[i][j] = min(m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j] for k in range(i, j))
s[i][j] = next(k for k in range(i, j)
if m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j] == m[i][j])
return m, s
count = 0
def matmul(A, B):
global count
count += len(A) * len(B) * len(B[0])
return [[sum(A[i][t] * B[t][j] for t in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))]
def chain_product(mats, s, i, j):
if i == j:
return mats[i]
k = s[i][j]
return matmul(chain_product(mats, s, i, k), chain_product(mats, s, k + 1, j))
p = [12, 4, 10, 3, 8, 5]
mats = [None] + [[[(r + 2 * c + i) % 5 - 2 for c in range(p[i])] for r in range(p[i - 1])] for i in range(1, 6)]
m, s = matrix_chain_order(p)
best = chain_product(mats, s, 1, 5)
count_best = count
count = 0
left_to_right = mats[1]
for i in range(2, 6):
left_to_right = matmul(left_to_right, mats[i])
print("optimal order:", count_best, "multiplications (table says", m[1][5], ")")
print("left to right:", count, "multiplications")
print("same product:", best == left_to_right, " result is", len(best), "x", len(best[0]))optimal order: 540 multiplications (table says 540 )
left to right: 1608 multiplications
same product: True result is 12 x 5
The same table, top down
Memoizing the recursive formulation from the previous lesson gives the same values without having to think about the order: the recursion finds it. The program counts how many calls do real work and how many are answered from the cache, for the running example and for a chain of 20 matrices.
from functools import cache
def memo_chain(p):
n = len(p) - 1
stats = {"calls": 0, "solved": 0}
@cache
def m(i, j):
stats["solved"] += 1
if i == j:
return 0
best = None
for k in range(i, j):
stats["calls"] += 2
cost = m(i, k) + m(k + 1, j) + p[i - 1] * p[k] * p[j]
best = cost if best is None else min(best, cost)
return best
return m(1, n), stats
print(memo_chain([12, 4, 10, 3, 8, 5]))
q = [(7 * t) % 11 + 2 for t in range(21)]
best, stats = memo_chain(q)
n = 20
print(f"n = {n}: best {best}, subproblems solved {stats['solved']} = n(n+1)/2 = {n * (n + 1) // 2}, "
f"recursive calls {stats['calls']} = 2 (n^3 - n)/6 = {2 * (n ** 3 - n) // 6}")(540, {'calls': 40, 'solved': 15})
n = 20: best 1764, subproblems solved 210 = n(n+1)/2 = 210, recursive calls 2660 = 2 (n^3 - n)/6 = 2660
Each of the subchains is solved once, and every split makes two calls, so there are calls in all: the two edges per split of the subproblem graph. The naive recursion made calls; for that is over a billion, against 2660 here.
Running time and space
The table has entries, and entry tries splits. Counting the inner steps exactly: a chain of length has positions and splits, so
That is time and space, against calls for naive recursion and orders for brute force.
def steps(n):
count = 0
for length in range(2, n + 1):
for i in range(1, n - length + 2):
j = i + length - 1
count += j - i # splits k = i .. j-1
return count
for n in [5, 10, 20, 40, 80]:
print(f"n = {n:2}: {steps(n):6} split evaluations, (n^3 - n)/6 = {(n ** 3 - n) // 6:6}")n = 5: 20 split evaluations, (n^3 - n)/6 = 20
n = 10: 165 split evaluations, (n^3 - n)/6 = 165
n = 20: 1330 split evaluations, (n^3 - n)/6 = 1330
n = 40: 10660 split evaluations, (n^3 - n)/6 = 10660
n = 80: 85320 split evaluations, (n^3 - n)/6 = 85320
The cubic bound is not the last word for this particular problem: Hu and Shing found an algorithm in the 1980s, based on a correspondence between parenthesizations and triangulations of a polygon. It is much more intricate, and the DP is what everyone uses for small chains. More important than this one problem is the pattern: interval DP, where the subproblems are contiguous pieces and the table is filled by increasing length. Optimal binary search trees, polygon triangulation and the parsing of context-free grammars (the CYK algorithm) are all built the same way.
In practice: NumPy's
numpy.linalg.multi_dotchooses the multiplication order for a chain of arrays with exactly this DP (for three arrays it uses a direct formula), somulti_dot([A, B, C, D])can be much faster thanA @ B @ C @ D, which always multiplies left to right.
In C++
The same table in C++, printing the corner value, the order and the step count, here for the running example and a chain of 60 matrices with pseudo-random dimensions.
#include <climits>
#include <cstdio>
#include <string>
#include <vector>
struct Result { std::vector<std::vector<long long>> m; std::vector<std::vector<int>> s; long long steps; };
Result matrix_chain_order(const std::vector<int>& p) {
int n = static_cast<int>(p.size()) - 1;
Result r{std::vector<std::vector<long long>>(n + 1, std::vector<long long>(n + 1, 0)),
std::vector<std::vector<int>>(n + 1, std::vector<int>(n + 1, 0)), 0};
for (int len = 2; len <= n; ++len)
for (int i = 1; i + len - 1 <= n; ++i) {
int j = i + len - 1;
r.m[i][j] = LLONG_MAX;
for (int k = i; k < j; ++k) {
++r.steps;
long long cost = r.m[i][k] + r.m[k + 1][j] + 1LL * p[i - 1] * p[k] * p[j];
if (cost < r.m[i][j]) { r.m[i][j] = cost; r.s[i][j] = k; }
}
}
return r;
}
std::string parens(const std::vector<std::vector<int>>& s, int i, int j) {
if (i == j) return "A" + std::to_string(i);
return "(" + parens(s, i, s[i][j]) + parens(s, s[i][j] + 1, j) + ")";
}
int main() {
std::vector<int> p = {12, 4, 10, 3, 8, 5};
Result r = matrix_chain_order(p);
std::printf("best %lld: %s (%lld steps)\n", r.m[1][5], parens(r.s, 1, 5).c_str(), r.steps);
std::vector<int> q;
unsigned x = 7;
for (int t = 0; t <= 60; ++t) { x = x * 1103515245u + 12345u; q.push_back(5 + (x >> 16) % 46); }
Result big = matrix_chain_order(q);
std::printf("60 matrices: best %lld scalar multiplications (%lld steps)\n", big.m[1][60], big.steps);
}best 540: (A1((A2A3)(A4A5))) (20 steps)
60 matrices: best 264410 scalar multiplications (35990 steps)
For 60 matrices the table needs steps; brute force would face orders. The practice problem Matrix Chain Multiplication asks for the minimum cost; the DSA course shows more DP problems at an introductory level.
Test yourself
Why is the matrix-chain table filled by increasing chain length?
- Because longer chains are more expensive
- Because depends only on entries for strictly shorter subchains
- Because the rows are independent
- Because the main diagonal is zero
How many split evaluations does MATRIX-CHAIN-ORDER make for matrices?
The table gives , , , , . What is the optimal order?