Chain Matrix Multiplication
# Chain Matrix Multiplication
# Problem Formulation
Satisfaction of the Principle of Optimality: Let $A_i$ represent the $i^{th}$ matrix with dimensions $(d_{i-1}\times d_i)$. The optimal way to multiply matrices $A_i \\ to\\ A_j$ can be broken down into the optimal way to multiply the matrices $A_i \\ to\\ A_k + A_{k+1} \\ to\\ A_j$ (for some k) + the cost to multiply the final 2 matrices = $d_i \times d_k \times d_j$
Define $OptCost(i,j)$ to be the optimal cost of multiplying matrices with dimensions $d_i, d_{i+1},…d_j$
Base case: $$OptCost(i,j) = 0 \qquad j-i=1$$ Recursive equation can be formed as follows: loop through possible k to find min $$OptCost(i,j) = \min_{i+1\le k\le j-1}(OptCost(i,k)+OptCost(k,j)+d_i\times d_k\times d_j) $$
# Strategy
Store the solutions to subproblems in cost 2d array. $Cost[i][j]$ represents the optimal cost of multiplying matrices $A_{i+1} \to A_j$
Store the optimal values of k (index to split the matrix multiplication) in last 2d array.
# Pseudocode
|
|
# Exercises
Suppose the dimensions of the matrices A, B, C, and D are 20x2, 2x15, 15x40, and 40x4, respectively, and we want to know how best to compute AxBxCxD. Show the arrays cost, last, and multOrder computed by Algorithms matrixOrder() in the lecture notes.
0 | 1 | 2 | 3 | 4 | |
---|---|---|---|---|---|
0 | - | 0 | 600 | min{$(0,1)+(1,3)+d_0d_1d_3$ $(0,2)+(2,3)+d_0d_2d_3$} = 2800 | min{$(0,1)+(1,4)+d_0d_1d_4$ $(0,2)+(2,4)+d_0d_2d_4$ $(0,3)+(3,4)+d_0d_3d_4$} = 1680 |
1 | 0 | 1200 | min{$(1,2)+(2,4)+d_1d_2d_4$ $(1,3)+(3,4)+d_1d_3d_4$} = 1520 | ||
2 | 0 | 2400 | |||
3 | 0 | ||||
4 | |||||
Last Table |
0 | 1 | 2 | 3 | 4 | |
---|---|---|---|---|---|
0 | - | - | 1 | 1 | 1 |
1 | 2 | 3 | |||
2 | 3 | ||||
3 | |||||
4 | |||||
Final order: $A_1*((A_2*A_3)*A_4)$ |