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

Dense Matrices

The simplest way to implement a matrix is to use a multi-dimensional array with two dimensions as shown in Program gif. The DenseMatrix class extends the Matrix class discussed in the preceding section. The DenseMatrix class adds a instance attribute called @array which is a multi-dimensional array. The initialize method of the DenseMatrix class takes two arguments, tex2html_wrap_inline59717 and tex2html_wrap_inline59719, and constructs the corresponding tex2html_wrap_inline59721 multi-dimensional array. Clearly, the running time of the initialize method is O(mn).

   program3173
Program: DenseMatrix class initialize, [] and []= methods.

Program gif also defines the [] and []= methods for the DenseMatrix class. These methods each take an ordered pair, (i,j), as the index expression and use the pair as the index into the multi-dimensional array. Because the number of dimensions is fixed at two, the running time for each of these methods is O(1).


next up previous index

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