- A matrix of size can be multiplied with a matrix of size
- The resulting matrix will have size
- The computational cost of multiplying these two matrices is
- Matrix Chain Multiplication Problem:
- Given:
- A sequence of matrices
- A sequence of dimensions such that the size of matrix is
- is the size of the final matrix product
- Goal: Determine the order of multiplication that minimizes the total cost of multiplying all the matrices
- Given:
- Dynamic Programming Solution:
- Subproblems:
- Let represent the minimum cost of multiplying matrices
- Recurrence Relation:
- Subproblems:
# Python code to implement the
# matrix chain multiplication using tabulation
def matrixMultiplication(arr):
n = len(arr)
# Create a 2D DP array to store min
# multiplication costs
dp = [[0] * n for _ in range(n)]
# dp[i][j] stores the minimum cost of
# multiplying matrices from i to j
# Fill the DP array
# length is the chain length
for length in range(2, n):
for i in range(n - length):
j = i + length
dp[i][j] = float('inf')
for k in range(i + 1, j):
cost = dp[i][k] + dp[k][j] + arr[i] * arr[k] * arr[j]
dp[i][j] = min(dp[i][j], cost)
# Minimum cost is in dp[0][n-1]
return dp[0][n - 1]
arr = [1, 2, 3, 4, 3]
print(matrixMultiplication(arr))