



With Ada.Text_IO use Ada.Text_IO with use package body mat_chain is type Result_Matrix is array ( Positive range, Positive range ) of Integer - Chain_Multiplication - procedure Chain_Multiplication ( Dims : Vector ) is n : Natural := Dims ' Length - 1 S : Result_Matrix ( 1. See also Matrix chain multiplication on Wikipedia. This is not optimal because of the many duplicated computations, and this task is a classic application of dynamic programming. To solve the task, it's possible, but not required, to write a function that enumerates all possible ways to parenthesize the product. Try this function on the following two lists: Hence, a product of n matrices is represented by a list of n+1 dimensions. The input list does not duplicate shared dimensions: for the previous example of matrices A,B,C, one will only pass the list (and not ) to mean the matrix dimensions are respectively (5,6), (6,3) and (3,1). Any sensible way to describe the optimal solution is accepted. An, of arbitrary length, returns the optimal way to compute the matrix product, and the total cost. Write a function which, given a list of the successive dimensions of matrices A1, A2.

The difference can be much more dramatic in real cases. In this case, computing (AB)C requires more than twice as many operations as A(BC). BC costs 6*3*1=18 and produces a matrix of dimensions (6,1), then A(BC) costs 5*6*1=30.AB costs 5*6*3=90 and produces a matrix of dimensions (5,3), then (AB)C costs 5*3*1=15.Here is an example of computation of the total cost, for matrices A(5,6), B(6,3), C(3,1): The number of different ways to put the parens is a Catalan number, and grows exponentially with the number of factors. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved.įor instance, with four matrices, one can compute A(B(CD)), A((BC)D), (AB)(CD), (A(BC))D, (AB)C)D. An depends on the order of matrix multiplications, hence on where parens are put. The number of operations required to compute the product of matrices A1, A2. Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. You are encouraged to solve this task according to the task description, using any language you may know.
