Class

The Matrix class represents a mathematical matrix. It provides methods for creating matrices, operating on them arithmetically and algebraically, and determining their mathematical properties (trace, rank, inverse, determinant).

Method Catalogue

To create a matrix:

To access Matrix elements/columns/rows/submatrices/properties:

Properties of a matrix:

Matrix arithmetic:

Matrix functions:

Matrix decompositions:

Complex arithmetic:

  • conj

  • conjugate

  • imag

  • imaginary

  • real

  • rect

  • rectangular

Conversion to other data types:

String representations:

Constants
No documentation available
Attributes
Read

instance creations

Returns the number of columns.

Returns the number of columns.

Class Methods
An alias for identity

Creates a matrix where each argument is a row.

Matrix[ [25, 93], [-1, 66] ]
   =>  25 93
       -1 66

Creates a matrix of size row_count x column_count. It fills the values by calling the given block, passing the current row and column. Returns an enumerator if no block is given.

m = Matrix.build(2, 4) {|row, col| col - row }
  => Matrix[[0, 1, 2, 3], [-1, 0, 1, 2]]
m = Matrix.build(3) { rand }
  => a 3x3 matrix with random elements

Creates a single-column matrix where the values of that column are as given in column.

Matrix.column_vector([4,5,6])
  => 4
     5
     6

Creates a matrix using columns as an array of column vectors.

Matrix.columns([[25, 93], [-1, 66]])
   =>  25 -1
       93 66

Creates a matrix where the diagonal elements are composed of values.

Matrix.diagonal(9, 5, -3)
  =>  9  0  0
      0  5  0
      0  0 -3

Creates a empty matrix of row_count x column_count. At least one of row_count or column_count must be 0.

m = Matrix.empty(2, 0)
m == Matrix[ [], [] ]
  => true
n = Matrix.empty(0, 3)
n == Matrix.columns([ [], [], [] ])
  => true
m * n
  => Matrix[[0, 0, 0], [0, 0, 0]]

Create a matrix by stacking matrices horizontally

x = Matrix[[1, 2], [3, 4]]
y = Matrix[[5, 6], [7, 8]]
Matrix.hstack(x, y) # => Matrix[[1, 2, 5, 6], [3, 4, 7, 8]]

Creates an n by n identity matrix.

Matrix.identity(2)
  => 1 0
     0 1

Matrix.new is private; use Matrix.rows, columns, [], etc… to create.

Creates a single-row matrix where the values of that row are as given in row.

Matrix.row_vector([4,5,6])
  => 4 5 6

Creates a matrix where rows is an array of arrays, each of which is a row of 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]])
   =>  25 93
       -1 66

Creates an n by n diagonal matrix where each diagonal element is value.

Matrix.scalar(2, 5)
  => 5 0
     0 5
An alias for identity

Create a matrix by stacking matrices vertically

x = Matrix[[1, 2], [3, 4]]
y = Matrix[[5, 6], [7, 8]]
Matrix.vstack(x, y) # => Matrix[[1, 2], [3, 4], [5, 6], [7, 8]]

Creates a zero matrix.

Matrix.zero(2)
  => 0 0
     0 0
Instance Methods

Matrix multiplication.

Matrix[[2,4], [6,8]] * Matrix.identity(2)
  => 2 4
     6 8

Matrix exponentiation. Equivalent to multiplying the matrix by itself N times. Non integer exponents will be handled by diagonalizing the matrix.

Matrix[[7,6], [3,9]] ** 2
  => 67 96
     48 99

Matrix addition.

Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]]
  =>  6  0
     -4 12
No documentation available

Matrix subtraction.

Matrix[[1,5], [4,2]] - Matrix[[9,3], [-4,1]]
  => -8  2
      8  1
No documentation available

Matrix division (multiplication by the inverse).

Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]]
  => -7  1
     -3 -6

Returns true if and only if the two matrices contain equal elements.

Returns element (i,j) of the matrix. That is: row i, column j.

No documentation available

Returns the adjugate of the matrix.

Matrix[ [7,6],[3,9] ].adjugate
  => 9 -6
     -3 7

Returns a clone of the matrix, so that the contents of each do not reference identical objects. There should be no good reason to do this since Matrices are immutable.

The coerce method provides support for Ruby type coercion. This coercion mechanism is used by Ruby to handle mixed-type numeric operations: it is intended to find a compatible common type between the two operands of the operator. See also Numeric#coerce.

Returns the (row, column) cofactor which is obtained by multiplying the first minor by (-1)**(row + column).

Matrix.diagonal(9, 5, -3, 4).cofactor(1, 1)
  => -108

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 { |e| e**2 }
  => 1  4
     9 16

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 iterated.

Returns an array of the column vectors of the matrix. See Vector.

An alias for []
An alias for conjugate

Returns the conjugate of the matrix.

Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
  => 1+2i   i  0
        1   2  3
Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].conjugate
  => 1-2i  -i  0
        1   2  3
An alias for determinant
An alias for determinant_e

Returns the determinant of the matrix.

Beware that using Float values can yield erroneous results because of their lack of precision. Consider using exact types like Rational or BigDecimal instead.

Matrix[[7,6], [3,9]].determinant
  => 45

Private. Use Matrix#determinant

Returns the determinant of the matrix, using Bareiss’ multistep integer-preserving gaussian elimination. It has the same computational cost order O(n^3) as standard Gaussian elimination. Intermediate results are fraction free and of lower complexity. A matrix of Integers will have thus intermediate results that are also Integers, with smaller bignums (if any), while a matrix of Float will usually have intermediate results with better precision.

deprecated; use Matrix#determinant

Returns true if this is a diagonal matrix. Raises an error if matrix is not square.

Yields all elements of the matrix, starting with those of the first row, or returns an Enumerator if no block given. Elements can be restricted by passing an argument:

  • :all (default): yields all elements

  • :diagonal: yields only elements on the diagonal

  • :off_diagonal: yields all elements except on the diagonal

  • :lower: yields only elements on or below the diagonal

  • :strict_lower: yields only elements below the diagonal

  • :strict_upper: yields only elements above the diagonal

  • :upper: yields only elements on or above the diagonal

    Matrix[ [1,2], [3,4] ].each { |e| puts e }

    # => prints the numbers 1 to 4
    

    Matrix[ [1,2], [3,4] ].each(:strict_lower).to_a # => [3]

Same as each, but the row index and column index in addition to the element

Matrix[ [1,2], [3,4] ].each_with_index do |e, row, col|
  puts "#{e} at #{row}, #{col}"
end
  # => Prints:
  #    1 at 0, 0
  #    2 at 0, 1
  #    3 at 1, 0
  #    4 at 1, 1
An alias for eigensystem

Returns the Eigensystem of the matrix; see EigenvalueDecomposition.

m = Matrix[[1, 2], [3, 4]]
v, d, v_inv = m.eigensystem
d.diagonal? # => true
v.inv == v_inv # => true
(v * d * v_inv).round(5) == m # => true
An alias for []
No documentation available
No documentation available
No documentation available

Returns true if this is an empty matrix, i.e. if the number of rows or the number of columns is 0.

No documentation available
An alias for index

Returns the submatrix obtained by deleting the specified row and column.

Matrix.diagonal(9, 5, -3, 4).first_minor(1, 2)
  => 9 0 0
     0 0 0
     0 0 4

Returns a hash-code for the matrix.

Returns true if this is an hermitian matrix. Raises an error if matrix is not square.

Returns a new matrix resulting by stacking horizontally the receiver with the given matrices

x = Matrix[[1, 2], [3, 4]]
y = Matrix[[5, 6], [7, 8]]
x.hstack(y) # => Matrix[[1, 2, 5, 6], [3, 4, 7, 8]]
An alias for imaginary

Returns the imaginary part of the matrix.

Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
  => 1+2i  i  0
        1  2  3
Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].imaginary
  =>   2i  i  0
        0  0  0

The index method is specialized to return the index as [row, column] It also accepts an optional selector argument, see each for details.

Matrix[ [1,2], [3,4] ].index(&:even?) # => [0, 1]
Matrix[ [1,1], [1,1] ].index(1, :strict_lower) # => [1, 0]

Overrides Object#inspect

An alias for inverse

Returns the inverse of the matrix.

Matrix[[-1, -1], [0, -1]].inverse
  => -1  1
      0 -1

Returns the Laplace expansion along given row or column.

Matrix[[7,6], [3,9]].laplace_expansion(column: 1)
 => 45

Matrix[[Vector[1, 0], Vector[0, 1]], [2, 3]].laplace_expansion(row: 0)
 => Vector[3, -2]

Returns true if this is a lower triangular matrix.

Returns the LUP decomposition of the matrix; see LUPDecomposition.

a = Matrix[[1, 2], [3, 4]]
l, u, p = a.lup
l.lower_triangular? # => true
u.upper_triangular? # => true
p.permutation?      # => true
l * u == p * a      # => true
a.lup.solve([2, 5]) # => Vector[(1/1), (1/2)]
An alias for lup
An alias for collect

Returns a section of the matrix. The parameters are either:

  • start_row, nrows, start_col, ncols; OR

  • row_range, col_range

Matrix.diagonal(9, 5, -3).minor(0..1, 0..2)
  => 9 0 0
     0 5 0

Like Array#[], negative indices count backward from the end of the row or column (-1 is the last element). Returns nil if the starting row or column is greater than row_count or column_count respectively.

Returns true if this is a normal matrix. Raises an error if matrix is not square.

Returns true if this is an orthogonal matrix Raises an error if matrix is not square.

Returns true if this is a permutation matrix Raises an error if matrix is not square.

Returns the rank of the matrix. Beware that using Float values can yield erroneous results because of their lack of precision. Consider using exact types like Rational or BigDecimal instead.

Matrix[[7,6], [3,9]].rank
  => 2

deprecated; use Matrix#rank

Returns the real part of the matrix.

Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
  => 1+2i  i  0
        1  2  3
Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].real
  =>    1  0  0
        1  2  3

Returns true if all entries of the matrix are real.

Returns an array containing matrices corresponding to the real and imaginary parts of the matrix

m.rect == [m.real, m.imag] # ==> true for all matrices m

An alias for rect

Returns true if this is a regular (i.e. non-singular) matrix.

Returns a matrix with entries rounded to the given precision (see Float#round)

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.

Returns the number of rows.

An alias for row_count

Returns an array of the row vectors of the matrix. See Vector.

An alias for []=
An alias for []=

Returns true if this is a singular matrix.

Returns true if this is a square matrix.

Returns true if this is a symmetric matrix. Raises an error if matrix is not square.

#
An alias for transpose

Returns an array of arrays that describe the rows of the matrix.

Overrides Object#to_s

An alias for trace

Returns the trace (sum of diagonal elements) of the matrix.

Matrix[[7,6], [3,9]].trace
  => 16

Returns the transpose of the matrix.

Matrix[[1,2], [3,4], [5,6]]
  => 1 2
     3 4
     5 6
Matrix[[1,2], [3,4], [5,6]].transpose
  => 1 3 5
     2 4 6

Returns true if this is a unitary matrix Raises an error if matrix is not square.

Returns true if this is an upper triangular matrix.

Returns a new matrix resulting by stacking vertically the receiver with the given matrices

x = Matrix[[1, 2], [3, 4]]
y = Matrix[[5, 6], [7, 8]]
x.vstack(y) # => Matrix[[1, 2], [3, 4], [5, 6], [7, 8]]

Returns true if this is a matrix with only zero elements