Professional Documents
Culture Documents
Matrix-chain Multiplication
contd
Matrix-chain Multiplication
contd
11-3
Matrix-chain Multiplication
Example: Consider three matrices A10100, B1005, and C550 There are 2 ways to parenthesize
((AB)C) = D105 C550
contd
AB 101005=5,000 scalar multiplications Total: DC 10550 =2,500 scalar multiplications 7,500 BC 100550=25,000 scalar multiplications AE 1010050 =50,000 scalar multiplications Total: 75,000
11-5
Matrix-chain Multiplication
Matrix-chain multiplication problem
contd
Given a chain A1, A2, , An of n matrices, where for i=1, 2, , n, matrix Ai has dimension pi-1pi Parenthesize the product A1A2An such that the total number of scalar multiplications is minimized
11-7
Key observation: parenthesizations of the subchains A1A2Ak and Ak+1Ak+2An must also be optimal if the parenthesization of the chain A1A2An is optimal (why?) That is, the optimal solution to the problem contains within it the optimal solution to subproblems
11-8
11-9
Ai..j = (Ai Ai+1Ak)(Ak+1Ak+2Aj)= Ai..k Ak+1..j Cost of computing Ai..j = cost of computing Ai..k + cost of computing Ak+1..j + cost of multiplying Ai..k and Ak+1..j Cost of multiplying Ai..k and Ak+1..j is pi-1pk pj m[i, j ] = m[i, k] + m[k+1, j ] + pi-1pk pj for i k < j m[i, i ] = 0 for i=1,2,,n
11-10
But optimal parenthesization occurs at one value of k among all possible i k < j Check all these and select the best one
0 m[i, j ] =
i k< j
if i=j if i<j
11-11
To keep track of how to construct an optimal solution, we use a table s s[i, j ] = value of k at which Ai Ai+1 Aj is split for optimal parenthesization Algorithm: next slide
First computes costs for chains of length l=1 Then for chains of length l=2,3, and so on Computes the optimal cost bottom-up
11-12
11-14
Example
Show how to multiply this matrix chain optimally Matrix Dimension A1 A2 3035 3515 155
A3
A4
A5 A6
510
1020 2025
11-15