Class | Matrix |
In: |
lib/matrix.rb
|
Parent: | Object |
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, inverse, determinant).
Note that although matrices should theoretically be rectangular, this is not enforced by the class.
Also note that the determinant of integer matrices may be incorrectly calculated unless you also require ‘mathn’. This may be fixed in the future.
To create a matrix:
To access Matrix elements/columns/rows/submatrices/properties:
Properties of a matrix:
Matrix arithmetic:
Matrix functions:
Conversion to other data types:
String representations:
identity | -> | unit |
identity | -> | I |
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 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 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]]) => 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
Matrix exponentiation. Defined for integer powers only. Equivalent to multiplying the matrix by itself N times.
Matrix[[7,6], [3,9]] ** 2 => 67 96 48 99
Matrix division (multiplication by the inverse).
Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]] => -7 1 -3 -6
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 } => 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 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 result.
Returns the determinant of the matrix. If the matrix is not square, the result is 0.
Matrix[[7,6], [3,9]].determinant => 63
Returns a section of the matrix. The parameters are either:
Matrix.diagonal(9, 5, -3).minor(0..1, 0..2) => 9 0 0 0 5 0
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 true is this is a square matrix. See note in column_size about this being unreliable, though.