# $Date: 1999/10/06 11:01:53 $
# Original Version from Smalltalk-80 version
# on July 23, 1985 at 8:37:17 am
# An implementation of Matrix and Vector classes.
# Author:: Keiju ISHITSUKA
# Documentation:: Gavin Sinclair (sourced from <i>Ruby in a Nutshell</i> (Matsumoto, O'Reilly))
# See classes Matrix and Vector for documentation.
module ExceptionForMatrix # :nodoc:
extend Exception2MessageMapper
def_e2message(TypeError, "wrong argument type %s (expected %s)")
def_e2message(ArgumentError, "Wrong # of arguments(%d for %d)")
def_exception("ErrDimensionMismatch", "\#{self.name} dimension mismatch")
def_exception("ErrNotRegular", "Not Regular Matrix")
def_exception("ErrOperationNotDefined", "This operation(%s) can\\'t defined")
# The +Matrix+ class represents a mathematical matrix, and provides methods for creating
# special-case matrices (zero, identity, diagonal, singular, vector), operating on them
# arithmetically and algebraically, and determining their mathematical properties (trace, rank,
# Note that although matrices should theoretically be rectangular, this is not
# Also note that the determinant of integer matrices may be incorrectly calculated unless you
# also <tt>require 'mathn'</tt>. This may be fixed in the future.
# * <tt> Matrix[*rows] </tt>
# * <tt> Matrix.[](*rows) </tt>
# * <tt> Matrix.rows(rows, copy = true) </tt>
# * <tt> Matrix.columns(columns) </tt>
# * <tt> Matrix.diagonal(*values) </tt>
# * <tt> Matrix.scalar(n, value) </tt>
# * <tt> Matrix.scalar(n, value) </tt>
# * <tt> Matrix.identity(n) </tt>
# * <tt> Matrix.unit(n) </tt>
# * <tt> Matrix.I(n) </tt>
# * <tt> Matrix.zero(n) </tt>
# * <tt> Matrix.row_vector(row) </tt>
# * <tt> Matrix.column_vector(column) </tt>
# To access Matrix elements/columns/rows/submatrices/properties:
# * <tt> #column_size </tt>
# * <tt> #column(j) </tt>
# * <tt> #minor(*param) </tt>
# Properties of a matrix:
# * <tt> #singular? </tt>
# * <tt> #determinant </tt>
# * <tt> #transpose </tt>
# Conversion to other data types:
# * <tt> #coerce(other) </tt>
# * <tt> #row_vectors </tt>
# * <tt> #column_vectors </tt>
# String representations:
@RCS_ID='-$Id: matrix.rb,v 1.11 1999/10/06 11:01:53 keiju Exp keiju $-'
# extend Exception2MessageMapper
include ExceptionForMatrix
private_class_method :new
# Creates a matrix where each argument is a row.
# Matrix[ [25, 93], [-1, 66] ]
new(:init_rows, rows, false)
# Creates a matrix where +rows+ is an array of arrays, each of which is a row
# to the matrix. If the optional argument +copy+ is false, use the given
# arrays as the internal structure of the matrix without copying.
# Matrix.rows([[25, 93], [-1, 66]])
def Matrix.rows(rows, copy = true)
new(:init_rows, rows, copy)
# Creates a matrix using +columns+ as an array of column vectors.
# Matrix.columns([[25, 93], [-1, 66]])
def Matrix.columns(columns)
rows = (0 .. columns[0].size - 1).collect {
(0 .. columns.size - 1).collect {
# Creates a matrix where the diagonal elements are composed of +values+.
# Matrix.diagonal(9, 5, -3)
def Matrix.diagonal(*values)
rows = (0 .. size - 1).collect {
row = Array.new(size).fill(0, 0, size)
# Creates an +n+ by +n+ diagonal matrix where each diagonal element is
def Matrix.scalar(n, value)
Matrix.diagonal(*Array.new(n).fill(value, 0, n))
# Creates an +n+ by +n+ identity matrix.
# Creates an +n+ by +n+ zero matrix.
# Creates a single-row matrix where the values of that row are as given in
# Matrix.row_vector([4,5,6])
def Matrix.row_vector(row)
Matrix.rows([row.to_a], false)
Matrix.rows([row.dup], false)
Matrix.rows([[row]], false)
# Creates a single-column matrix where the values of that column are as given
# Matrix.column_vector([4,5,6])
def Matrix.column_vector(column)
Matrix.columns([column.to_a])
Matrix.columns([[column]])
# This method is used by the other methods that create matrices, and is of no
def initialize(init_method, *argv)
self.send(init_method, *argv)
def init_rows(rows, copy)
@rows = rows.collect{|row| row.dup}
# Returns element (+i+,+j+) of the matrix. That is: row +i+, column +j+.
# Returns the number of rows.
# Returns the number of columns. Note that it is possible to construct a
# matrix with uneven columns (e.g. Matrix[ [1,2,3], [4,5] ]), but this is
# mathematically unsound. This method uses the first row to determine the
# Returns row vector number +i+ of the matrix as a Vector (starting at 0 like
# an array). When a block is given, the elements of that vector are iterated.
Vector.elements(@rows[i])
# Returns column vector number +j+ of the matrix as a Vector (starting at 0
# like an array). When a block is given, the elements of that vector are
def column(j) # :yield: e
col = (0 .. row_size - 1).collect {
Vector.elements(col, false)
# Returns a matrix that is the result of iteration of the given block over all
# elements of the matrix.
# Matrix[ [1,2], [3,4] ].collect { |i| i**2 }
rows = @rows.collect{|row| row.collect{|e| yield e}}
# Returns a section of the matrix. The parameters are either:
# * start_row, nrows, start_col, ncols; OR
# Matrix.diagonal(9, 5, -3).minor(0..1, 0..2)
from_row = param[0].first
size_row = param[0].end - from_row
size_row += 1 unless param[0].exclude_end?
from_col = param[1].first
size_col = param[1].end - from_col
size_col += 1 unless param[1].exclude_end?
Matrix.Raise ArgumentError, param.inspect
rows = @rows[from_row, size_row].collect{
# TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# Returns +true+ if this is a regular matrix.
square? and rank == column_size
# Returns +true+ is this is a singular (i.e. non-regular) matrix.
# Returns +true+ is this is a square matrix. See note in column_size about this
# being unreliable, though.
# OBJECT METHODS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# Returns +true+ if and only if the two matrices contain equal elements.
return false unless Matrix === other
other.compare_by_row_vectors(@rows)
# Not really intended for general consumption.
def compare_by_row_vectors(rows)
return false unless @rows.size == rows.size
0.upto(@rows.size - 1) do
return false unless @rows[i] == rows[i]
# Returns a clone of the matrix, so that the contents of each do not reference
# Returns a hash-code for the matrix.
# ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# Matrix[[2,4], [6,8]] * Matrix.identity(2)
def *(m) # m is matrix or vector or number
return Matrix.rows(rows, false)
m = Matrix.column_vector(m)
Matrix.Raise ErrDimensionMismatch if column_size != m.row_size
rows = (0 .. row_size - 1).collect {
(0 .. m.column_size - 1).collect {
0.upto(column_size - 1) do
vij += self[i, k] * m[k, j]
return Matrix.rows(rows, false)
# Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]]
Matrix.Raise ErrOperationNotDefined, "+"
m = Matrix.column_vector(m)