4 # $Release Version: 1.0$
6 # Original Version from Smalltalk-80 version
7 # on July 23, 1985 at 8:37:17 am
13 # An implementation of Matrix and Vector classes.
15 # Author:: Keiju ISHITSUKA
16 # Documentation:: Gavin Sinclair (sourced from <i>Ruby in a Nutshell</i> (Matsumoto, O'Reilly))
18 # See classes Matrix and Vector for documentation.
24 module ExceptionForMatrix # :nodoc:
25 extend Exception2MessageMapper
26 def_e2message(TypeError, "wrong argument type %s (expected %s)")
27 def_e2message(ArgumentError, "Wrong # of arguments(%d for %d)")
29 def_exception("ErrDimensionMismatch", "\#{self.name} dimension mismatch")
30 def_exception("ErrNotRegular", "Not Regular Matrix")
31 def_exception("ErrOperationNotDefined", "This operation(%s) can\\'t defined")
35 # The +Matrix+ class represents a mathematical matrix, and provides methods for creating
36 # special-case matrices (zero, identity, diagonal, singular, vector), operating on them
37 # arithmetically and algebraically, and determining their mathematical properties (trace, rank,
38 # inverse, determinant).
40 # Note that although matrices should theoretically be rectangular, this is not
41 # enforced by the class.
43 # Also note that the determinant of integer matrices may be incorrectly calculated unless you
44 # also <tt>require 'mathn'</tt>. This may be fixed in the future.
49 # * <tt> Matrix[*rows] </tt>
50 # * <tt> Matrix.[](*rows) </tt>
51 # * <tt> Matrix.rows(rows, copy = true) </tt>
52 # * <tt> Matrix.columns(columns) </tt>
53 # * <tt> Matrix.diagonal(*values) </tt>
54 # * <tt> Matrix.scalar(n, value) </tt>
55 # * <tt> Matrix.scalar(n, value) </tt>
56 # * <tt> Matrix.identity(n) </tt>
57 # * <tt> Matrix.unit(n) </tt>
58 # * <tt> Matrix.I(n) </tt>
59 # * <tt> Matrix.zero(n) </tt>
60 # * <tt> Matrix.row_vector(row) </tt>
61 # * <tt> Matrix.column_vector(column) </tt>
63 # To access Matrix elements/columns/rows/submatrices/properties:
64 # * <tt> [](i, j) </tt>
65 # * <tt> #row_size </tt>
66 # * <tt> #column_size </tt>
67 # * <tt> #row(i) </tt>
68 # * <tt> #column(j) </tt>
69 # * <tt> #collect </tt>
71 # * <tt> #minor(*param) </tt>
73 # Properties of a matrix:
74 # * <tt> #regular? </tt>
75 # * <tt> #singular? </tt>
76 # * <tt> #square? </tt>
83 # * <tt> #inverse </tt>
88 # * <tt> #determinant </tt>
93 # * <tt> #transpose </tt>
96 # Conversion to other data types:
97 # * <tt> #coerce(other) </tt>
98 # * <tt> #row_vectors </tt>
99 # * <tt> #column_vectors </tt>
102 # String representations:
104 # * <tt> #inspect </tt>
107 @RCS_ID='-$Id: matrix.rb,v 1.13 2001/12/09 14:22:23 keiju Exp keiju $-'
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)
216 Matrix.rows([row.to_a], false)
218 Matrix.rows([row.dup], false)
220 Matrix.rows([[row]], false)
225 # Creates a single-column matrix where the values of that column are as given
227 # Matrix.column_vector([4,5,6])
232 def Matrix.column_vector(column)
235 Matrix.columns([column.to_a])
237 Matrix.columns([column])
239 Matrix.columns([[column]])
244 # This method is used by the other methods that create matrices, and is of no
245 # use to general users.
247 def initialize(init_method, *argv)
248 self.send(init_method, *argv)
251 def init_rows(rows, copy)
253 @rows = rows.collect{|row| row.dup}
262 # Returns element (+i+,+j+) of the matrix. That is: row +i+, column +j+.
273 alias set_element []=
274 alias set_component []=
275 private :[]=, :set_element, :set_component
278 # Returns the number of rows.
285 # Returns the number of columns. Note that it is possible to construct a
286 # matrix with uneven columns (e.g. Matrix[ [1,2,3], [4,5] ]), but this is
287 # mathematically unsound. This method uses the first row to determine the
295 # Returns row vector number +i+ of the matrix as a Vector (starting at 0 like
296 # an array). When a block is given, the elements of that vector are iterated.
298 def row(i) # :yield: e
304 Vector.elements(@rows[i])
309 # Returns column vector number +j+ of the matrix as a Vector (starting at 0
310 # like an array). When a block is given, the elements of that vector are
313 def column(j) # :yield: e
315 0.upto(row_size - 1) do
320 col = (0 .. row_size - 1).collect {
324 Vector.elements(col, false)
329 # Returns a matrix that is the result of iteration of the given block over all
330 # elements of the matrix.
331 # Matrix[ [1,2], [3,4] ].collect { |e| e**2 }
335 def collect # :yield: e
336 rows = @rows.collect{|row| row.collect{|e| yield e}}
337 Matrix.rows(rows, false)
342 # Returns a section of the matrix. The parameters are either:
343 # * start_row, nrows, start_col, ncols; OR
344 # * col_range, row_range
346 # Matrix.diagonal(9, 5, -3).minor(0..1, 0..2)
353 from_row = param[0].first
354 size_row = param[0].end - from_row
355 size_row += 1 unless param[0].exclude_end?
356 from_col = param[1].first
357 size_col = param[1].end - from_col
358 size_col += 1 unless param[1].exclude_end?
365 Matrix.Raise ArgumentError, param.inspect
368 rows = @rows[from_row, size_row].collect{
370 row[from_col, size_col]
372 Matrix.rows(rows, false)
376 # TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
380 # Returns +true+ if this is a regular matrix.
383 square? and rank == column_size
387 # Returns +true+ is this is a singular (i.e. non-regular) matrix.
394 # Returns +true+ is this is a square matrix. See note in column_size about this
395 # being unreliable, though.
398 column_size == row_size
402 # OBJECT METHODS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
406 # Returns +true+ if and only if the two matrices contain equal elements.
409 return false unless Matrix === other
411 other.compare_by_row_vectors(@rows)
416 # Not really intended for general consumption.
418 def compare_by_row_vectors(rows)
419 return false unless @rows.size == rows.size
421 0.upto(@rows.size - 1) do
423 return false unless @rows[i] == rows[i]
429 # Returns a clone of the matrix, so that the contents of each do not reference
437 # Returns a hash-code for the matrix.
450 # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
454 # Matrix multiplication.
455 # Matrix[[2,4], [6,8]] * Matrix.identity(2)
459 def *(m) # m is matrix or vector or number
462 rows = @rows.collect {
469 return Matrix.rows(rows, false)
471 m = Matrix.column_vector(m)
475 Matrix.Raise ErrDimensionMismatch if column_size != m.row_size
477 rows = (0 .. row_size - 1).collect {
479 (0 .. m.column_size - 1).collect {
482 0.upto(column_size - 1) do
484 vij += self[i, k] * m[k, j]
489 return Matrix.rows(rows, false)
491 x, y = m.coerce(self)
498 # Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]]
505 Matrix.Raise ErrOperationNotDefined, "+"
507 m = Matrix.column_vector(m)
510 x, y = m.coerce(self)
514 Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size
516 rows = (0 .. row_size - 1).collect {
518 (0 .. column_size - 1).collect {
523 Matrix.rows(rows, false)
527 # Matrix subtraction.
528 # Matrix[[1,5], [4,2]] - Matrix[[9,3], [-4,1]]
535 Matrix.Raise ErrOperationNotDefined, "-"
537 m = Matrix.column_vector(m)
540 x, y = m.coerce(self)
544 Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size
546 rows = (0 .. row_size - 1).collect {
548 (0 .. column_size - 1).collect {
553 Matrix.rows(rows, false)
557 # Matrix division (multiplication by the inverse).
558 # Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]]
565 rows = @rows.collect {
572 return Matrix.rows(rows, false)
574 return self * other.inverse
576 x, y = other.coerce(self)
582 # Returns the inverse of the matrix.
583 # Matrix[[1, 2], [2, 1]].inverse
588 Matrix.Raise ErrDimensionMismatch unless square?
589 Matrix.I(row_size).inverse_from(self)
594 # Not for public consumption?
596 def inverse_from(src)
610 Matrix.Raise ErrNotRegular if akk == 0
612 a[i], a[k] = a[k], a[i]
613 @rows[i], @rows[k] = @rows[k], @rows[i]
622 (k + 1).upto(size) do
624 a[i][j] -= a[k][j] * q
628 @rows[i][j] -= @rows[k][j] * q
632 (k + 1).upto(size) do
634 a[k][j] = a[k][j].quo(akk)
638 @rows[k][j] = @rows[k][j].quo(akk)
643 #alias reciprocal inverse
646 # Matrix exponentiation. Defined for integer powers only. Equivalent to
647 # multiplying the matrix by itself N times.
648 # Matrix[[7,6], [3,9]] ** 2
653 if other.kind_of?(Integer)
657 return Matrix.identity(self.column_size) if other == 0
663 while (div, mod = n.divmod(2)
672 elsif other.kind_of?(Float) || defined?(Rational) && other.kind_of?(Rational)
673 Matrix.Raise ErrOperationNotDefined, "**"
675 Matrix.Raise ErrOperationNotDefined, "**"
680 # MATRIX FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
684 # Returns the determinant of the matrix. If the matrix is not square, the
685 # result is 0. This method's algorism is Gaussian elimination method
686 # and using Numeric#quo(). Beware that using Float values, with their
687 # usual lack of precision, can affect the value returned by this method. Use
688 # Rational values or Matrix#det_e instead if this is important to you.
690 # Matrix[[7,6], [3,9]].determinant
694 return 0 unless square?
702 if (akk = a[k][k]) == 0
705 return 0 if (i += 1) > size
706 end while a[i][k] == 0
707 a[i], a[k] = a[k], a[i]
711 (k + 1).upto(size) do
714 (k + 1).upto(size) do
716 a[i][j] -= a[k][j] * q
720 end while (k += 1) <= size
723 alias det determinant
726 # Returns the determinant of the matrix. If the matrix is not square, the
727 # result is 0. This method's algorism is Gaussian elimination method.
728 # This method uses Euclidean algorism. If all elements are integer,
729 # really exact value. But, if an element is a float, can't return
732 # Matrix[[7,6], [3,9]].determinant
736 return 0 unless square?
747 return 0 if (i += 1) > size
748 end while a[i][k].zero?
749 a[i], a[k] = a[k], a[i]
752 (k + 1).upto(size) do |i|
753 q = a[i][k].quo(a[k][k])
755 a[i][j] -= a[k][j] * q
758 a[i], a[k] = a[k], a[i]
764 end while (k += 1) <= size
767 alias det_e determinant_e
770 # Returns the rank of the matrix. Beware that using Float values,
771 # probably return faild value. Use Rational values or Matrix#rank_e
772 # for getting exact result.
774 # Matrix[[7,6], [3,9]].rank
778 if column_size > row_size
780 a_column_size = row_size
781 a_row_size = column_size
784 a_column_size = column_size
785 a_row_size = row_size
790 if (akk = a[k][k]) == 0
794 if (i += 1) > a_column_size - 1
798 end while a[i][k] == 0
800 a[i], a[k] = a[k], a[i]
806 if (i += 1) > a_row_size - 1
810 end while a[k][i] == 0
812 k.upto(a_column_size - 1) do
814 a[j][k], a[j][i] = a[j][i], a[j][k]
822 (k + 1).upto(a_row_size - 1) do
825 (k + 1).upto(a_column_size - 1) do
827 a[i][j] -= a[k][j] * q
831 end while (k += 1) <= a_column_size - 1
836 # Returns the rank of the matrix. This method uses Euclidean
837 # algorism. If all elements are integer, really exact value. But, if
838 # an element is a float, can't return exact value.
840 # Matrix[[7,6], [3,9]].rank
845 a_column_size = column_size
846 a_row_size = row_size
848 (0 ... a_column_size).each do |j|
849 if i = (pi ... a_row_size).find{|i0| !a[i0][j].zero?}
851 a[pi], a[i] = a[i], a[pi]
853 (pi + 1 ... a_row_size).each do |k|
854 q = a[k][j].quo(a[pi][j])
855 (pi ... a_column_size).each do |j0|
856 a[k][j0] -= q * a[pi][j0]
858 if k > pi && !a[k][j].zero?
859 a[k], a[pi] = a[pi], a[k]
871 # Returns the trace (sum of diagonal elements) of the matrix.
872 # Matrix[[7,6], [3,9]].trace
877 0.upto(column_size - 1) do
886 # Returns the transpose of the matrix.
887 # Matrix[[1,2], [3,4], [5,6]]
891 # Matrix[[1,2], [3,4], [5,6]].transpose
896 Matrix.columns(@rows)
901 # CONVERTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
905 # FIXME: describe #coerce.
910 return Scalar.new(other), self
912 raise TypeError, "#{self.class} can't be coerced into #{other.class}"
917 # Returns an array of the row vectors of the matrix. See Vector.
920 rows = (0 .. row_size - 1).collect {
928 # Returns an array of the column vectors of the matrix. See Vector.
931 columns = (0 .. column_size - 1).collect {
939 # Returns an array of arrays that describe the rows of the matrix.
942 @rows.collect{|row| row.collect{|e| e}}
958 # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
962 # Overrides Object#to_s
965 "Matrix[" + @rows.collect{
967 "[" + row.collect{|e| e.to_s}.join(", ") + "]"
972 # Overrides Object#inspect
975 "Matrix"+@rows.inspect
980 class Scalar < Numeric # :nodoc:
981 include ExceptionForMatrix
983 def initialize(value)
991 Scalar.new(@value + other)
993 Scalar.Raise WrongArgType, other.class, "Numeric or Scalar"
995 Scalar.new(@value + other.value)
997 x, y = other.coerce(self)
1005 Scalar.new(@value - other)
1007 Scalar.Raise WrongArgType, other.class, "Numeric or Scalar"
1009 Scalar.new(@value - other.value)
1011 x, y = other.coerce(self)
1019 Scalar.new(@value * other)
1021 other.collect{|e| @value * e}
1023 x, y = other.coerce(self)
1031 Scalar.new(@value / other)
1033 Scalar.Raise WrongArgType, other.class, "Numeric or Scalar or Matrix"
1035 self * other.inverse
1037 x, y = other.coerce(self)
1045 Scalar.new(@value ** other)
1047 Scalar.Raise WrongArgType, other.class, "Numeric or Scalar or Matrix"
1049 other.powered_by(self)
1051 x, y = other.coerce(self)
1060 # The +Vector+ class represents a mathematical vector, which is useful in its own right, and
1061 # also constitutes a row or column of a Matrix.
1063 # == Method Catalogue
1065 # To create a Vector:
1066 # * <tt> Vector.[](*array) </tt>
1067 # * <tt> Vector.elements(array, copy = true) </tt>
1069 # To access elements:
1070 # * <tt> [](i) </tt>
1072 # To enumerate the elements:
1073 # * <tt> #each2(v) </tt>
1074 # * <tt> #collect2(v) </tt>
1076 # Vector arithmetic:
1077 # * <tt> *(x) "is matrix or number" </tt>
1082 # * <tt> #inner_product(v) </tt>
1083 # * <tt> #collect </tt>
1085 # * <tt> #map2(v) </tt>
1087 # * <tt> #size </tt>
1089 # Conversion to other data types:
1090 # * <tt> #covector </tt>
1091 # * <tt> #to_a </tt>
1092 # * <tt> #coerce(other) </tt>
1094 # String representations:
1095 # * <tt> #to_s </tt>
1096 # * <tt> #inspect </tt>
1099 include ExceptionForMatrix
1103 private_class_method :new
1106 # Creates a Vector from a list of elements.
1109 def Vector.[](*array)
1110 new(:init_elements, array, copy = false)
1114 # Creates a vector from an Array. The optional second argument specifies
1115 # whether the array itself or a copy is used internally.
1117 def Vector.elements(array, copy = true)
1118 new(:init_elements, array, copy)
1124 def initialize(method, array, copy)
1125 self.send(method, array, copy)
1131 def init_elements(array, copy)
1133 @elements = array.dup
1142 # Returns element number +i+ (starting at zero) of the vector.
1153 alias set_element []=
1154 alias set_component []=
1155 private :[]=, :set_element, :set_component
1158 # Returns the number of elements in the vector.
1165 # ENUMERATIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
1169 # Iterate over the elements of this vector and +v+ in conjunction.
1171 def each2(v) # :yield: e1, e2
1172 Vector.Raise ErrDimensionMismatch if size != v.size
1175 yield @elements[i], v[i]
1180 # Collects (as in Enumerable#collect) over the elements of this vector and +v+
1183 def collect2(v) # :yield: e1, e2
1184 Vector.Raise ErrDimensionMismatch if size != v.size
1185 (0 .. size - 1).collect do
1187 yield @elements[i], v[i]
1192 # COMPARING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
1196 # Returns +true+ iff the two vectors have the same elements in the same order.
1199 return false unless Vector === other
1201 other.compare_by(@elements)
1208 def compare_by(elements)
1209 @elements == elements
1213 # Return a copy of the vector.
1216 Vector.elements(@elements)
1220 # Return a hash-code for the vector.
1227 # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
1231 # Multiplies the vector by +x+, where +x+ is a number or another vector.
1236 els = @elements.collect{|e| e * x}
1237 Vector.elements(els, false)
1239 Matrix.column_vector(self) * x
1241 s, x = x.coerce(self)
1252 Vector.Raise ErrDimensionMismatch if size != v.size
1257 Vector.elements(els, false)
1259 Matrix.column_vector(self) + v
1261 s, x = v.coerce(self)
1267 # Vector subtraction.
1272 Vector.Raise ErrDimensionMismatch if size != v.size
1277 Vector.elements(els, false)
1279 Matrix.column_vector(self) - v
1281 s, x = v.coerce(self)
1287 # VECTOR FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
1291 # Returns the inner product of this vector with the other.
1292 # Vector[4,7].inner_product Vector[10,1] => 47
1294 def inner_product(v)
1295 Vector.Raise ErrDimensionMismatch if size != v.size
1306 # Like Array#collect.
1308 def collect # :yield: e
1309 els = @elements.collect {
1313 Vector.elements(els, false)
1318 # Like Vector#collect2, but returns a Vector instead of an Array.
1320 def map2(v) # :yield: e1, e2
1325 Vector.elements(els, false)
1329 # Returns the modulus (Pythagorean distance) of the vector.
1330 # Vector[5,8,2].r => 9.643650761
1345 # Creates a single-row matrix from this vector.
1348 Matrix.row_vector(self)
1352 # Returns the elements of the vector in an array.
1371 # FIXME: describe Vector#coerce.
1376 return Matrix::Scalar.new(other), self
1378 raise TypeError, "#{self.class} can't be coerced into #{other.class}"
1383 # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
1387 # Overrides Object#to_s
1390 "Vector[" + @elements.join(", ") + "]"
1394 # Overrides Object#inspect
1397 str = "Vector"+@elements.inspect
1402 # Documentation comments:
1403 # - Matrix#coerce and Vector#coerce need to be documented