Skip to content

Matrix Constructors

Sergey Duyunov edited this page Nov 3, 2019 · 2 revisions

initialize(rows_count, columns_count)

Creates a new matrix with a given number of rows and columns.

The fastest way to create a matrix, but the matrix is filled with unpredictable values!!

[](*rows)

Creates a matrix where each argument is a row.

m = Matrix[[1, 2, 3], [4, 5, 6]]
# =>  1 2 3
#     4 5 6

build(row_count, column_count)

Creates a new matrix with a given number of rows and columns. 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

zero(row_count, column_count)

Creates a zero matrix.

m = Matrix.zero(2, 2)
# => Matrix[[0, 0], [0, 0]]

identity(n)

Creates an n by n identity matrix.

m = Matrix.identity(3)
# => Matrix[[1, 0, 0], [0, 1, 0], [0, 0, 1]]

I(n)

Alias for: identity.

diagonal(*values)

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

m = Matrix.diagonal(7, 8, 1)
# => Matrix[[7, 0, 0], [0, 8, 0], [0, 0, 1]]

vstack(*matrices)

Create a matrix by stacking matrices vertically.

m1 = Matrix[[1, 2], [3, 4]]
m2 = Matrix[[5, 6], [7, 8], [9, 0]]
Matrix.vstack(m1, m2)
# => Matrix[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]

hstack(*matrices)

Create a matrix by stacking matrices horizontally.

m1 = Matrix[[1, 2], [3, 4]]
m2 = Matrix[[5, 6, 7], [8, 9, 0]]
Matrix.hstack(m1, m2)
# => Matrix[[1, 2, 5, 6, 7], [3, 4, 8, 9, 0]]