4 # $Release Version: 1.0$
6 # $Date: 1999/10/06 11:01:53 $
7 # Original Version from Smalltalk-80 version
8 # on July 23, 1985 at 8:37:17 am
14 # An implementation of Matrix and Vector classes.
16 # Author:: Keiju ISHITSUKA
17 # Documentation:: Gavin Sinclair (sourced from <i>Ruby in a Nutshell</i> (Matsumoto, O'Reilly))
19 # See classes Matrix and Vector for documentation.
25 module ExceptionForMatrix # :nodoc:
26 extend Exception2MessageMapper
27 def_e2message(TypeError, "wrong argument type %s (expected %s)")
28 def_e2message(ArgumentError, "Wrong # of arguments(%d for %d)")
30 def_exception("ErrDimensionMismatch", "\#{self.name} dimension mismatch")
31 def_exception("ErrNotRegular", "Not Regular Matrix")
32 def_exception("ErrOperationNotDefined", "This operation(%s) can\\'t defined")
36 # The +Matrix+ class represents a mathematical matrix, and provides methods for creating
37 # special-case matrices (zero, identity, diagonal, singular, vector), operating on them
38 # arithmetically and algebraically, and determining their mathematical properties (trace, rank,
39 # inverse, determinant).
41 # Note that although matrices should theoretically be rectangular, this is not
42 # enforced by the class.
44 # Also note that the determinant of integer matrices may be incorrectly calculated unless you
45 # also <tt>require 'mathn'</tt>. This may be fixed in the future.
50 # * <tt> Matrix[*rows] </tt>
51 # * <tt> Matrix.[](*rows) </tt>
52 # * <tt> Matrix.rows(rows, copy = true) </tt>
53 # * <tt> Matrix.columns(columns) </tt>
54 # * <tt> Matrix.diagonal(*values) </tt>
55 # * <tt> Matrix.scalar(n, value) </tt>
56 # * <tt> Matrix.scalar(n, value) </tt>
57 # * <tt> Matrix.identity(n) </tt>
58 # * <tt> Matrix.unit(n) </tt>
59 # * <tt> Matrix.I(n) </tt>
60 # * <tt> Matrix.zero(n) </tt>
61 # * <tt> Matrix.row_vector(row) </tt>
62 # * <tt> Matrix.column_vector(column) </tt>
64 # To access Matrix elements/columns/rows/submatrices/properties:
65 # * <tt> [](i, j) </tt>
66 # * <tt> #row_size </tt>
67 # * <tt> #column_size </tt>
68 # * <tt> #row(i) </tt>
69 # * <tt> #column(j) </tt>
70 # * <tt> #collect </tt>
72 # * <tt> #minor(*param) </tt>
74 # Properties of a matrix:
75 # * <tt> #regular? </tt>
76 # * <tt> #singular? </tt>
77 # * <tt> #square? </tt>
84 # * <tt> #inverse </tt>
89 # * <tt> #determinant </tt>
94 # * <tt> #transpose </tt>
97 # Conversion to other data types:
98 # * <tt> #coerce(other) </tt>
99 # * <tt> #row_vectors </tt>
100 # * <tt> #column_vectors </tt>
103 # String representations:
105 # * <tt> #inspect </tt>
109 # extend Exception2MessageMapper
110 include ExceptionForMatrix
113 private_class_method :new
116 # Creates a matrix where each argument is a row.
117 # Matrix[ [25, 93], [-1, 66] ]
122 new(:init_rows, rows, false)
126 # Creates a matrix where +rows+ is an array of arrays, each of which is a row
127 # to the matrix. If the optional argument +copy+ is false, use the given
128 # arrays as the internal structure of the matrix without copying.
129 # Matrix.rows([[25, 93], [-1, 66]])
132 def Matrix.rows(rows, copy = true)
133 new(:init_rows, rows, copy)
137 # Creates a matrix using +columns+ as an array of column vectors.
138 # Matrix.columns([[25, 93], [-1, 66]])
143 def Matrix.columns(columns)
144 rows = (0 .. columns[0].size - 1).collect {
146 (0 .. columns.size - 1).collect {
151 Matrix.rows(rows, false)
155 # Creates a matrix where the diagonal elements are composed of +values+.
156 # Matrix.diagonal(9, 5, -3)
161 def Matrix.diagonal(*values)
163 rows = (0 .. size - 1).collect {
165 row = Array.new(size).fill(0, 0, size)
173 # Creates an +n+ by +n+ diagonal matrix where each diagonal element is
175 # Matrix.scalar(2, 5)
179 def Matrix.scalar(n, value)
180 Matrix.diagonal(*Array.new(n).fill(value, 0, n))
184 # Creates an +n+ by +n+ identity matrix.
189 def Matrix.identity(n)
198 # Creates an +n+ by +n+ zero matrix.
208 # Creates a single-row matrix where the values of that row are as given in
210 # Matrix.row_vector([4,5,6])
213 def Matrix.row_vector(row)
217 Matrix.rows([row.to_a], false)
219 Matrix.rows([row.dup], false)
221 Matrix.rows([[row]], false)
226 # Creates a single-column matrix where the values of that column are as given
228 # Matrix.column_vector([4,5,6])
233 def Matrix.column_vector(column)
236 Matrix.columns([column.to_a])
238 Matrix.columns([column])
240 Matrix.columns([[column]])
245 # This method is used by the other methods that create matrices, and is of no
246 # use to general users.
248 def initialize(init_method, *argv)
249 self.send(init_method, *argv)
252 def init_rows(rows, copy)
254 @rows = rows.collect{|row| row.dup}
263 # Returns element (+i+,+j+) of the matrix. That is: row +i+, column +j+.
270 # Returns the number of rows.
277 # Returns the number of columns. Note that it is possible to construct a
278 # matrix with uneven columns (e.g. Matrix[ [1,2,3], [4,5] ]), but this is
279 # mathematically unsound. This method uses the first row to determine the
287 # Returns row vector number +i+ of the matrix as a Vector (starting at 0 like
288 # an array). When a block is given, the elements of that vector are iterated.
290 def row(i) # :yield: e
296 Vector.elements(@rows[i])
301 # Returns column vector number +j+ of the matrix as a Vector (starting at 0
302 # like an array). When a block is given, the elements of that vector are
305 def column(j) # :yield: e
307 0.upto(row_size - 1) do
312 col = (0 .. row_size - 1).collect {
316 Vector.elements(col, false)
321 # Returns a matrix that is the result of iteration of the given block over all
322 # elements of the matrix.
323 # Matrix[ [1,2], [3,4] ].collect { |i| i**2 }
327 def collect # :yield: e
328 rows = @rows.collect{|row| row.collect{|e| yield e}}
329 Matrix.rows(rows, false)
334 # Returns a section of the matrix. The parameters are either:
335 # * start_row, nrows, start_col, ncols; OR
336 # * col_range, row_range
338 # Matrix.diagonal(9, 5, -3).minor(0..1, 0..2)
345 from_row = param[0].first
346 size_row = param[0].end - from_row
347 size_row += 1 unless param[0].exclude_end?
348 from_col = param[1].first
349 size_col = param[1].end - from_col
350 size_col += 1 unless param[1].exclude_end?
357 Matrix.Raise ArgumentError, param.inspect
360 rows = @rows[from_row, size_row].collect{
362 row[from_col, size_col]
364 Matrix.rows(rows, false)
368 # TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
372 # Returns +true+ if this is a regular matrix.
375 square? and rank == column_size
379 # Returns +true+ is this is a singular (i.e. non-regular) matrix.
386 # Returns +true+ is this is a square matrix. See note in column_size about this
387 # being unreliable, though.
390 column_size == row_size
394 # OBJECT METHODS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
398 # Returns +true+ if and only if the two matrices contain equal elements.
401 return false unless Matrix === other
403 other.compare_by_row_vectors(@rows)
408 # Not really intended for general consumption.
410 def compare_by_row_vectors(rows)
411 return false unless @rows.size == rows.size
413 0.upto(@rows.size - 1) do
415 return false unless @rows[i] == rows[i]
421 # Returns a clone of the matrix, so that the contents of each do not reference
429 # Returns a hash-code for the matrix.
442 # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
446 # Matrix multiplication.
447 # Matrix[[2,4], [6,8]] * Matrix.identity(2)
451 def *(m) # m is matrix or vector or number
454 rows = @rows.collect {
461 return Matrix.rows(rows, false)
463 m = Matrix.column_vector(m)
467 Matrix.Raise ErrDimensionMismatch if column_size != m.row_size
469 rows = (0 .. row_size - 1).collect {
471 (0 .. m.column_size - 1).collect {
474 0.upto(column_size - 1) do
476 vij += self[i, k] * m[k, j]
481 return Matrix.rows(rows, false)
483 x, y = m.coerce(self)
490 # Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]]
497 Matrix.Raise ErrOperationNotDefined, "+"
499 m = Matrix.column_vector(m)
502 x, y = m.coerce(self)
506 Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size
508 rows = (0 .. row_size - 1).collect {
510 (0 .. column_size - 1).collect {
515 Matrix.rows(rows, false)
519 # Matrix subtraction.
520 # Matrix[[1,5], [4,2]] - Matrix[[9,3], [-4,1]]
527 Matrix.Raise ErrOperationNotDefined, "-"
529 m = Matrix.column_vector(m)
532 x, y = m.coerce(self)
536 Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size
538 rows = (0 .. row_size - 1).collect {
540 (0 .. column_size - 1).collect {
545 Matrix.rows(rows, false)
549 # Matrix division (multiplication by the inverse).
550 # Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]]
557 rows = @rows.collect {
564 return Matrix.rows(rows, false)
566 return self * other.inverse
568 x, y = other.coerce(self)
574 # Returns the inverse of the matrix.
575 # Matrix[[1, 2], [2, 1]].inverse
580 Matrix.Raise ErrDimensionMismatch unless square?
581 Matrix.I(row_size).inverse_from(self)
586 # Not for public consumption?
588 def inverse_from(src)
593 if (akk = a[k][k]) == 0
596 Matrix.Raise ErrNotRegular if (i += 1) > size
597 end while a[i][k] == 0
598 a[i], a[k] = a[k], a[i]
599 @rows[i], @rows[k] = @rows[k], @rows[i]
608 (k + 1).upto(size) do
610 a[i][j] -= a[k][j] * q
614 @rows[i][j] -= @rows[k][j] * q
618 (k + 1).upto(size) do
629 #alias reciprocal inverse
632 # Matrix exponentiation. Defined for integer powers only. Equivalent to
633 # multiplying the matrix by itself N times.
634 # Matrix[[7,6], [3,9]] ** 2
639 if other.kind_of?(Integer)
643 return Matrix.identity(self.column_size) if other == 0
649 while (div, mod = n.divmod(2)
658 elsif other.kind_of?(Float) || defined?(Rational) && other.kind_of?(Rational)
659 Matrix.Raise ErrOperationNotDefined, "**"
661 Matrix.Raise ErrOperationNotDefined, "**"
666 # MATRIX FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
670 # Returns the determinant of the matrix. If the matrix is not square, the
672 # Matrix[[7,6], [3,9]].determinant
676 return 0 unless square?
684 if (akk = a[k][k]) == 0
687 return 0 if (i += 1) > size
688 end while a[i][k] == 0
689 a[i], a[k] = a[k], a[i]
693 (k + 1).upto(size) do
696 (k + 1).upto(size) do
698 a[i][j] -= a[k][j] * q
702 end while (k += 1) <= size
705 alias det determinant
708 # Returns the rank of the matrix. Beware that using Float values, with their
709 # usual lack of precision, can affect the value returned by this method. Use
710 # Rational values instead if this is important to you.
711 # Matrix[[7,6], [3,9]].rank
715 if column_size > row_size
717 a_column_size = row_size
718 a_row_size = column_size
721 a_column_size = column_size
722 a_row_size = row_size
727 if (akk = a[k][k]) == 0
731 if (i += 1) > a_column_size - 1
735 end while a[i][k] == 0
737 a[i], a[k] = a[k], a[i]
743 if (i += 1) > a_row_size - 1
747 end while a[k][i] == 0
749 k.upto(a_column_size - 1) do
751 a[j][k], a[j][i] = a[j][i], a[j][k]
759 (k + 1).upto(a_row_size - 1) do
762 (k + 1).upto(a_column_size - 1) do
764 a[i][j] -= a[k][j] * q
768 end while (k += 1) <= a_column_size - 1
773 # Returns the trace (sum of diagonal elements) of the matrix.
774 # Matrix[[7,6], [3,9]].trace
779 0.upto(column_size - 1) do
788 # Returns the transpose of the matrix.
789 # Matrix[[1,2], [3,4], [5,6]]
793 # Matrix[[1,2], [3,4], [5,6]].transpose
798 Matrix.columns(@rows)
803 # CONVERTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
807 # FIXME: describe #coerce.
812 return Scalar.new(other), self
814 raise TypeError, "#{self.class} can't be coerced into #{other.class}"
819 # Returns an array of the row vectors of the matrix. See Vector.
822 rows = (0 .. row_size - 1).collect {
830 # Returns an array of the column vectors of the matrix. See Vector.
833 columns = (0 .. column_size - 1).collect {
841 # Returns an array of arrays that describe the rows of the matrix.
844 @rows.collect{|row| row.collect{|e| e}}
848 # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
852 # Overrides Object#to_s
855 "Matrix[" + @rows.collect{
857 "[" + row.collect{|e| e.to_s}.join(", ") + "]"
862 # Overrides Object#inspect
865 "Matrix"+@rows.inspect
870 class Scalar < Numeric # :nodoc:
871 include ExceptionForMatrix
873 def initialize(value)
881 Scalar.new(@value + other)
883 Scalar.Raise WrongArgType, other.class, "Numeric or Scalar"
885 Scalar.new(@value + other.value)
887 x, y = other.coerce(self)
895 Scalar.new(@value - other)
897 Scalar.Raise WrongArgType, other.class, "Numeric or Scalar"
899 Scalar.new(@value - other.value)
901 x, y = other.coerce(self)
909 Scalar.new(@value * other)
911 other.collect{|e| @value * e}
913 x, y = other.coerce(self)
921 Scalar.new(@value / other)
923 Scalar.Raise WrongArgType, other.class, "Numeric or Scalar or Matrix"
927 x, y = other.coerce(self)
935 Scalar.new(@value ** other)
937 Scalar.Raise WrongArgType, other.class, "Numeric or Scalar or Matrix"
939 other.powered_by(self)
941 x, y = other.coerce(self)
950 # The +Vector+ class represents a mathematical vector, which is useful in its own right, and
951 # also constitutes a row or column of a Matrix.
953 # == Method Catalogue
955 # To create a Vector:
956 # * <tt> Vector.[](*array) </tt>
957 # * <tt> Vector.elements(array, copy = true) </tt>
959 # To access elements:
962 # To enumerate the elements:
963 # * <tt> #each2(v) </tt>
964 # * <tt> #collect2(v) </tt>
967 # * <tt> *(x) "is matrix or number" </tt>
972 # * <tt> #inner_product(v) </tt>
973 # * <tt> #collect </tt>
975 # * <tt> #map2(v) </tt>
979 # Conversion to other data types:
980 # * <tt> #covector </tt>
982 # * <tt> #coerce(other) </tt>
984 # String representations:
986 # * <tt> #inspect </tt>
989 include ExceptionForMatrix
993 private_class_method :new
996 # Creates a Vector from a list of elements.
999 def Vector.[](*array)
1000 new(:init_elements, array, copy = false)
1004 # Creates a vector from an Array. The optional second argument specifies
1005 # whether the array itself or a copy is used internally.
1007 def Vector.elements(array, copy = true)
1008 new(:init_elements, array, copy)
1014 def initialize(method, array, copy)
1015 self.send(method, array, copy)
1021 def init_elements(array, copy)
1023 @elements = array.dup
1032 # Returns element number +i+ (starting at zero) of the vector.
1039 # Returns the number of elements in the vector.
1046 # ENUMERATIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
1050 # Iterate over the elements of this vector and +v+ in conjunction.
1052 def each2(v) # :yield: e1, e2
1053 Vector.Raise ErrDimensionMismatch if size != v.size
1056 yield @elements[i], v[i]
1061 # Collects (as in Enumerable#collect) over the elements of this vector and +v+
1064 def collect2(v) # :yield: e1, e2
1065 Vector.Raise ErrDimensionMismatch if size != v.size
1066 (0 .. size - 1).collect do
1068 yield @elements[i], v[i]
1073 # COMPARING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
1077 # Returns +true+ iff the two vectors have the same elements in the same order.
1080 return false unless Vector === other
1082 other.compare_by(@elements)
1089 def compare_by(elements)
1090 @elements == elements
1094 # Return a copy of the vector.
1097 Vector.elements(@elements)
1101 # Return a hash-code for the vector.
1108 # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
1112 # Multiplies the vector by +x+, where +x+ is a number or another vector.
1117 els = @elements.collect{|e| e * x}
1118 Vector.elements(els, false)
1120 Matrix.column_vector(self) * x
1122 s, x = x.coerce(self)
1133 Vector.Raise ErrDimensionMismatch if size != v.size
1138 Vector.elements(els, false)
1140 Matrix.column_vector(self) + v
1142 s, x = v.coerce(self)
1148 # Vector subtraction.
1153 Vector.Raise ErrDimensionMismatch if size != v.size
1158 Vector.elements(els, false)
1160 Matrix.column_vector(self) - v
1162 s, x = v.coerce(self)
1168 # VECTOR FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
1172 # Returns the inner product of this vector with the other.
1173 # Vector[4,7].inner_product Vector[10,1] => 47
1175 def inner_product(v)
1176 Vector.Raise ErrDimensionMismatch if size != v.size
1187 # Like Array#collect.
1189 def collect # :yield: e
1190 els = @elements.collect {
1194 Vector.elements(els, false)
1199 # Like Vector#collect2, but returns a Vector instead of an Array.
1201 def map2(v) # :yield: e1, e2
1206 Vector.elements(els, false)
1210 # Returns the modulus (Pythagorean distance) of the vector.
1211 # Vector[5,8,2].r => 9.643650761
1226 # Creates a single-row matrix from this vector.
1229 Matrix.row_vector(self)
1233 # Returns the elements of the vector in an array.
1240 # FIXME: describe Vector#coerce.
1245 return Scalar.new(other), self
1247 raise TypeError, "#{self.class} can't be coerced into #{other.class}"
1252 # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
1256 # Overrides Object#to_s
1259 "Vector[" + @elements.join(", ") + "]"
1263 # Overrides Object#inspect
1266 str = "Vector"+@elements.inspect
1271 # Documentation comments:
1272 # - Matrix#coerce and Vector#coerce need to be documented