Matrix-chain Multiplications

In calculating the optimal order of multiplying m matrices

M0 × M1 × M2 × ··· × Mm − 1

where matrix Mi has dimension ni × ni + 1, we use a dynamic program which calculates the optimal order of calculating Mi × ··· × Mj where first j = i + 1, then j = i + 2, etc.

In the case when j = i + 1, the cost of multiplying Mi × Mi + 1 is simply ni ni + 1 ni + 2.

In the case where j = i + 2, the cost of multiplying Mi × Mi + 1 × Mi + 2 is the lesser of the cost of multiplying (Mi × Mi + 1) × Mi + 2 and Mi × (Mi + 1 × Mi + 2).

Two source codes are provided: an easier variation of the algorithm which simply calculates the cost involved and one which indicates the order of the multiplications.