CS141 Lab 5

Matrix-chain multiplication


Problem

We are using Dynamic Programming to solve the problem of matrix-chain multiplication.

The matrix-chain multiplication problem can be stated as follows: given a chain <A1, A2, ..., An> of n matrices, where for i = 1,2,...,n, matrix Ai has dimensiion pi-1 x pi, fully parenthesize the product A1A2...An in a way that minimizes the number of scalar multiplications.

e.g.
    matrix     dimensiion
    ------------------------------
        A1         10 x 100
        A2       100 x 5
        A3           5 x 50

Then,
((A1A2)A3) = 10 x 100 x 5 + 10 x 5 x 50 = 7500 (scalar multiplications)
(A1(A2A3)) = 100 x 5 x 50 + 10 x 100 x 50 = 75000 (scalar multiplications)

Thus, computing the product according to the first parenthesization is 10 times faster.



Dynamic Programing

Let m[i,j] be the minimum number of scalar multiplications needed to compute the matrix Ai..j; the cost of a cheapest way to compute A1..n would thus be m[1,n].

func


s[i,j] is a parallel array in which we will store the value of k providing the optimal split position. For example, suppose that s[i,j] = k. This tells us that the best way to multiply the subchain Ai..j is to first multiply the subchain Ai..k and then multiply the subchain AK+1..Aj, and finally multiply these together.


Psudocode:

array m[n+1, n+1]
array s[n+1, n+1]

Matrix-Chain(array p[n+1], int n) {  
    for i = 1 to n do m[i,i] = 0

    for L = 2 to n do {
       for i = 1 to n - L + 1 do {
            j = i + L - 1
            m[i,j] = INFINITY    //give a very big integer
            for k = i to j-1 do {
                q = m[i,k] + m[k+1,j] + p[i-1]*p[k]*p[j]
                if (q < m[i,j]) {
                    m[i,j] = q
                    s[i,j] = k
                }
            }
        }
    }
}



Assigment

  1. Implement the algorithm to solve Matrix-Chain problem using dynamic programming
  2. Run the above algorithm on the following matrix dimensions: (compute the matrix m[i,j] and s[i,j])

        matrix     dimensiion
        ----------------------------
            A1         30 x 35
            A2         35 x 15
            A3         15 x 5
            A4           5 x 10
            A5         10 x 20
            A6         20 x 25

    3. Output the matrix m[i,j] and s[i,j]. Report the minimum number of scalar multiplications needed and the way of the chain of matrices is computed using parenthesis. e.g. (A1((A2A3)A4))






m[1,6] = 15,125
s[1,6] = 3