1.0 - Matrix Multiplication

🌱 We want to find an order in which to multiply the chain of matrices that has the least cost

M1β‹…M2β‹…M3β‹―Mn M_1\cdot M_2\cdot M_3 \cdots M_n

which has the least cost (i.e. will be the fastest). Assume that the matrices may have different dimensions, but that the multiplication is well defined (e.g. #colsΒ ofΒ M1=#rowsΒ ofΒ Mi+1\#\text{cols of } M_1=\#\text{rows of }M_{i+1}

1.1 - Mechanics of Matrix Multiplication


1.2 - Multiplying Matrices


1.3 - Example - Importance of Order

1.4 - Task

🌱 We want to find an order in which to multiply the chain of matrices that has the least cost

M1β‹…M2β‹…M3β‹―Mn M_1\cdot M_2\cdot M_3 \cdots M_n

which has the least cost (i.e. will be the fastest), assuming that each matrix MiM_i has dimensions piβˆ’1Γ—pip_{i-1}\times p_i so that by definition, each pair of adjacent matrices is compatible.

Additionally, the cost of Miβ‹…Mi+1=piβˆ’1β‹…piβ‹…pi+1M_i\cdot M_{i+1}=p_{i-1}\cdot p_i\cdot p_{i+1}, in which the resulting matrix Miβ‹…Mi+1M_i\cdot M_{i+1} is of dimension piβˆ’1Γ—pi+1p_{i-1}\times p_{i+1}

1.4.1 - Naive Solution

We know that the recurrence N(n)∈Ω(2n)N(n)\in \Omega(2^n) where

N(1)=1N(1)=1

N(n)=βˆ‘i=1nβˆ’1N(i)Γ—N(nβˆ’i)=N(1)Γ—N(nβˆ’1)+β‹―+N(nβˆ’1)Γ—N(1)Β forΒ n>2≀N(1)Γ—N(nβˆ’1)+N(nβˆ’1)Γ—N(1)=2N(nβˆ’1)\begin{aligned}N(n)&=\sum^{n-1}_{i=1} N(i)\times N(n-i)\\ &=N(1)\times N(n-1)+\cdots+N(n-1)\times N(1) &\text{ for } n > 2\\ &\le N(1)\times N(n-1) + N(n-1)\times N(1)\\ &=2N(n-1) \end{aligned}

1.4.2 - Recursive Solution

1.4.3 - Dynamic Solution

matrix_chain_order(p, n) m = new int[n, n] s = new int[n, n] for i = 1 to n m[i, i] = 0 s[i, i] = i for L = 2 to n for i = 1 to n - L + 1 j + i + L -1 assert i <= k assert k < j m[i, j] = min m[i, k] + m[k + 1, j] + (p_{i-1} * p_k * p_j) s[i, j] = k