TExcelTAD
Home › Design Techniques: Dynamic Programming, Greedy & Amortized Analysis › Matrix-Chain Multiplication: The Table

Matrix-Chain Multiplication: The Table

The previous lesson reduced the best order for a matrix chain to the recurrence

m[i,j]=min⁡i≤k<j(m[i,k]+m[k+1,j]+pi−1 pk pj),m[i,i]=0,m[i, j] = \min_{i \le k < j} \left( m[i, k] + m[k+1, j] + p_{i-1}\, p_k\, p_j \right), \qquad m[i, i] = 0,

over the n(n+1)2\frac{n(n+1)}{2} subchains Ai..jA_{i..j}. This lesson evaluates it bottom-up. The new question compared to rod cutting is the order: m[i,j]m[i, j] 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 m[i,j]m[i, j] depends on is strictly shorter than j−i+1j - i + 1.

Watch the table fill

The animation fills the upper triangle of the table for the running example p=(12,4,10,3,8,5)p = (12, 4, 10, 3, 8, 5), 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 m[1,5]m[1, 5]. At each step it lists the candidate cost of every split kk.

The algorithm

text
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, s

The 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.

python · try it yourself
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 m[1,5]=540m[1, 5] = 540 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 m[1][5]m[1][5]: the split after A1A_1 costs 540, while splitting after A3A_3 (cost 564) is the runner-up. Splitting after A2A_2 is the worst at 1350: its last multiplication alone, 12×1012 \times 10 by 10×510 \times 5, costs 600, and the subchain A3..5A_{3..5} still has to be paid for.

Reconstructing the order

The table ss stores for every subchain the split kk 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 A1..5A_{1..5} splits at s[1,5]=1s[1, 5] = 1; the right side A2..5A_{2..5} splits at s[2,5]=3s[2, 5] = 3, giving (A2A3)(A4A5)(A_2 A_3)(A_4 A_5). To check that the order really costs what the table promises, the program below multiplies actual matrices in that order and counts.

python · try it yourself
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.

python · try it yourself
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 n(n+1)2\frac{n(n+1)}{2} subchains is solved once, and every split makes two calls, so there are 2⋅n3−n62 \cdot \frac{n^3 - n}{6} calls in all: the two edges per split of the subproblem graph. The naive recursion made 3n−13^{n-1} calls; for n=20n = 20 that is over a billion, against 2660 here.

Running time and space

The table has Θ(n2)\Theta(n^2) entries, and entry (i,j)(i, j) tries j−ij - i splits. Counting the inner steps exactly: a chain of length ℓ\ell has n−ℓ+1n - \ell + 1 positions and ℓ−1\ell - 1 splits, so

∑ℓ=2n(n−ℓ+1)(ℓ−1)=(n+13)=n3−n6.\sum_{\ell=2}^{n} (n - \ell + 1)(\ell - 1) = \binom{n+1}{3} = \frac{n^3 - n}{6}.

That is Θ(n3)\Theta(n^3) time and Θ(n2)\Theta(n^2) space, against 3n−13^{n-1} calls for naive recursion and Θ(4n/n3/2)\Theta(4^n / n^{3/2}) orders for brute force.

python · try it yourself
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 O(nlg⁡n)O(n \lg n) algorithm in the 1980s, based on a correspondence between parenthesizations and triangulations of a polygon. It is much more intricate, and the Θ(n3)\Theta(n^3) 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 i..ji..j 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_dot chooses the multiplication order for a chain of arrays with exactly this DP (for three arrays it uses a direct formula), so multi_dot([A, B, C, D]) can be much faster than A @ 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.

cpp · try it yourself
#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 603−606=35,990\frac{60^3 - 60}{6} = 35{,}990 steps; brute force would face P(60)=C59≈4×1032P(60) = C_{59} \approx 4 \times 10^{32} 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?

  1. Because longer chains are more expensive
  2. Because m[i,j]m[i, j] depends only on entries for strictly shorter subchains
  3. Because the rows are independent
  4. Because the main diagonal is zero

How many split evaluations does MATRIX-CHAIN-ORDER make for n=6n = 6 matrices?

  1. 1515
  2. 2020
  3. 3535
  4. 3636

The table gives s[1,6]=2s[1, 6] = 2, s[1,2]=1s[1, 2] = 1, s[3,6]=5s[3, 6] = 5, s[3,5]=4s[3, 5] = 4, s[3,4]=3s[3, 4] = 3. What is the optimal order?

  1. ((A1A2)(((A3A4)A5)A6))((A_1 A_2)(((A_3 A_4) A_5) A_6))
  2. (A1(A2((A3A4)(A5A6))))(A_1 (A_2 ((A_3 A_4)(A_5 A_6))))
  3. (((A1A2)A3)(A4(A5A6)))(((A_1 A_2) A_3)(A_4 (A_5 A_6)))
  4. ((A1A2)((A3A4)(A5A6)))((A_1 A_2)((A_3 A_4)(A_5 A_6)))