Matrix Chain Multiplication
Matrix Chain Multiplication
multiplying a sequence of matrices. The goal is to determine the most efficient way to
multiply a given set of matrices together. The efficiency is measured in terms of the number
of scalar multiplications required, which can be significant depending on the order of
multiplication.
Problem Definition
If AAA is of size p×qp \times qp×q and BBB is of size q×rq \times rq×r, the number
of scalar multiplications required is p×q×rp \times q \times rp×q×r.
Example
The goal is to compute the product A1A2A3A_1 A_2 A_3A1A2A3 with the minimum
number of multiplications.
The Matrix Chain Multiplication problem can be efficiently solved using a dynamic
programming approach. Here’s a step-by-step breakdown of the algorithm:
Let's solve the problem step-by-step with matrices A1,A2,A3A_1, A_2, A_3A1,A2,A3:
1. Dimensions:
o p=[10,30,5,60]p = [10, 30, 5, 60]p=[10,30,5,60]
2. Initialization:
o Create a 3x3 cost matrix mmm:
css
Copy code
m = [ [0, ∞, ∞],
[∞, 0, ∞],
[∞, ∞, 0]
]
3. Calculating Costs:
o For chain length=2chain\ length = 2chain length=2:
For (i,j)=(1,2)(i, j) = (1, 2)(i,j)=(1,2):
Calculate m[1][2]m[1][2]m[1][2]:
m[1][2]=m[1][1]+m[2][2]+p0×p1×p2=0+0+10×30×5=1500m[1][2] =
m[1][1] + m[2][2] + p_0 \times p_1 \times p_2 = 0 + 0 + 10 \times 30 \
times 5 = 1500m[1][2]=m[1][1]+m[2][2]+p0×p1×p2
=0+0+10×30×5=1500
m[2][3]=m[2][2]+m[3][3]+p1×p2×p3=0+0+30×5×60=9000m[2][3] =
m[2][2] + m[3][3] + p_1 \times p_2 \times p_3 = 0 + 0 + 30 \times 5 \
times 60 = 9000m[2][3]=m[2][2]+m[3][3]+p1×p2×p3
=0+0+30×5×60=9000
css
Copy code
m = [ [0, 1500, ∞],
[∞, 0, 9000],
[∞, ∞, 0]
]
m[1][3]=4500m[1][3] = 4500m[1][3]=4500
css
Copy code
m = [ [0, 1500, 4500],
[∞, 0, 9000],
[∞, ∞, 0]
]
Complexity Analysis
Applications
Conclusion
Matrix Chain Multiplication is a fundamental problem in algorithm design that showcases the
power of dynamic programming. By breaking the problem into smaller subproblems and
utilizing optimal substructure, it provides an efficient method to determine the best order of
operations for matrix multiplication.