exp5 2056
exp5 2056
Date: 30/01/2023
Objective:
To write a program to find a optimal ordering of matrix multiplication using dynamic
programming
Description:
Problem Statement:
Given a sequence of matrices A1, A2,An, insert parentheses so that the product of the
matrices, in order, is unambiguous and needs the minimal number of multiplication
Solution:
Consider matrix product A1×⋯× An. Let the dimensions of matrix Ai be di−1×di. Thus,
the dimensions of matrix product Ai×⋯× Aj is di−1×dj
Example:
Array dimensions:
A1: 2 x 3
A2: 3 x 5
A3: 5 x 2
A4: 2 x 4
A5: 4 x 3
1
20CS2018L Design and Analysis Algorithms Lab URK21CS2064
Algorithm:
Bottom-Up Algorithm to Calculate Minimum Number of Multiplications:
n - Number of arrays
d - array of dimensions of arrays 1 .. n
P - 2D array of locations of M[i, j]
min_value := integer'lastf;or k
in i .. j-1 loop
current := M[i, k] + M[k+1, j] + d(i-1)*d(k)*d(j)if current <
min_value then
min_value := current
mink := k
end
ifend loop
M[i, j] := mi_nvalueP(i,
j) := mink
end
loopend loop
printbest(P, i, j)i:f i=j
thenprint "A"_i
else
print '('
printbest(P, i, M[i, j])
printbest(P, M[i, j] + 1 j)
print ')'
2
20CS2018L Design and Analysis Algorithms Lab URK21CS2064
Program:
def check(matrix):
n = len(matrix)
m = [[0 for x in range(n)] for y in range(n)]
for i in range(1, n):
m[i][i] = 0
for L in range(2, n):
for i in range(1, n - L + 1):
j=i+L-1
m[i][j] = float("inf")
for k in range(i, j):
q = m[i][k] + m[k + 1][j] + matrix[i - 1] * matrix[k] * matrix[j]
if q < m[i][j]:
m[i][j] = q
return m[1][n - 1]
3
20CS2018L Design and Analysis Algorithms Lab URK21CS2064
Output:
Result:
The program to solve dynamic programming solution for matrix chain multiplication using
python done and executed successfully.