Matrix Chain Multiplication Algorithm
Matrix Chain Multiplication Algorithm
• Matrix chain multiplication is an algorithm that is applied to determine the lowest cost way
for multiplying matrices.
• The actual multiplication is done using the standard way of multiplying the matrices, that is it
follows the basic rule that the number of rows in one matrix must be equal to the number of
columns in another matrix.
• Hence, multiple scalar multiplications must be done to achieve the product.
• Matrix chain multiplication algorithm is only applied to find the minimum cost way to
multiply a sequence of matrices. Therefore, the input taken by the algorithm is the sequence
of matrices while the output achieved is the lowest cost parenthesization.
Algorithm
• Count the number of parenthesization. Find the number of ways in which the input matrices
can be multiplied using the formulae −
k=1 if n ≥ 2
(or)
P(n)= {2(n-1)Cn-1 if n ≥ 2
-------------- if n = 1
n
• Once the parenthesization is done, the optimal substructure must be devised as the first
step of dynamic programming approach so the final product achieved is optimal. In matrix
chain multiplication, the optimal substructure is found by dividing the sequence of
matrices A[i….j] into two parts A[i,k] and A[k+1,j]. It must be ensured that the parts are
divided in such a way that optimal solution is achieved.
• find the lowest cost parenthesization of the sequence of matrices by constructing cost tables
and corresponding k values table.
• Once the lowest cost is found, print the corresponding parenthesization as the output.
Pseudocode
Pseudocode to find the lowest cost of all the possible parenthesizations −
MATRIX-CHAIN-MULTIPLICATION(p)
n = p.length ─ 1
let m[1…n, 1…n] and s[1…n ─ 1, 2…n] be new matrices
for i = 1 to n
m[i, i] = 0
for l = 2 to n // l is the chain length
for i = 1 to n - l + 1
j = i + l - 1
m[i, j] = ∞
for k = i to j - 1
q = m[i, k] + m[k + 1, j] + pi-1pkpj
if q < m[i, j]
m[i, j] = q
s[i, j] = k
return m and s
Output
PRINT-OPTIMAL-OUTPUT(s, i, j )
if i == j
print “A”i
else print “(”
PRINT-OPTIMAL-OUTPUT(s, i, s[i, j])
PRINT-OPTIMAL-OUTPUT(s, s[i, j] + 1, j)
print “)”