Data Structures and Algorithms with Object-Oriented Design Patterns in Ruby
next up previous index

Canonical Matrix Multiplication

 

Given an tex2html_wrap_inline59721 matrix A and an tex2html_wrap_inline59733 matrix B, the product C=AB is an tex2html_wrap_inline59739 matrix. The elements of the result matrix are given by

  equation3192

Accordingly, in order to compute the produce matrix, C, we need to compute mp summations each of which is the sum of n product terms. An algorithm to compute the matrix product is given in Program gif. The algorithm given is a direct implementation of Equation gif.

   program3202
Program: DenseMatrix class times method.

The algorithm begins by checking to see that the matrices to be multiplied have compatible dimensions. That is, the number of columns of the first matrix must be equal to the number of rows of the second one. This check takes O(1) time in the worst case.

Next a matrix in which the result will be formed is constructed (lines 5-6). The running time for this is O(mp). For each value of i and j, the innermost loop (lines 10-12) does n iterations. Each iteration takes a constant amount of time.

The body of the middle loop (lines 8-14) takes time O(n) for each value of i and j. The middle loop is done for p iterations, giving the running time of O(np) for each value of i. Since, the outer loop (lines 7-15) does m iterations, its overall running time is O(mnp). Finally, the result matrix is returned on line 16. This takes a constant amount of time.

In summary, we have shown that line 4 is O(1); lines 5-6 is O(mp); lines 7-15 are O(mnp); and line 16 is O(1). Therefore, the running time of the canonical matrix multiplication algorithm is O(mnp).


next up previous index

Bruno Copyright © 2004 by Bruno R. Preiss, P.Eng. All rights reserved.