-
Notifications
You must be signed in to change notification settings - Fork 2
Matrix Constructors
Sergey Duyunov edited this page Nov 3, 2019
·
2 revisions
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!!
Creates a matrix where each argument is a row.
m = Matrix[[1, 2, 3], [4, 5, 6]]
# => 1 2 3
# 4 5 6
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
Creates a zero matrix.
m = Matrix.zero(2, 2)
# => Matrix[[0, 0], [0, 0]]
Creates an n by n identity matrix.
m = Matrix.identity(3)
# => Matrix[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
Alias for: identity.
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]]
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]]
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]]