create a matrix in ruby

To create a matrix in Ruby, you can use the built-in Matrix class from the 'matrix' library.

The simplest way to create a matrix is to provide a two-dimensional array of numbers as an argument to the Matrix class constructor:

main.rb
require "matrix"

# creating a 2x3 matrix
my_matrix = Matrix[[1, 2, 3], [4, 5, 6]]

puts my_matrix
# Output:
# 1  2  3
# 4  5  6
129 chars
10 lines

You can also create a matrix from a one-dimensional array or a nested array using the rows or columns methods respectively:

main.rb
require "matrix"

# creating a 2x3 matrix from a one-dimensional array
one_dim_array = [1, 2, 3, 4, 5, 6]
my_matrix = Matrix.rows(one_dim_array.each_slice(3).to_a)

puts my_matrix
# Output:
# 1  2  3
# 4  5  6

# creating a 2x3 matrix from a nested array
nested_array = [[1, 2, 3], [4, 5, 6]]
my_matrix = Matrix.columns(nested_array)

puts my_matrix
# Output:
# 1  4
# 2  5
# 3  6
381 chars
21 lines

You can perform various mathematical operations on matrices, such as addition, subtraction, and multiplication using the methods provided by the Matrix class.

gistlibby LogSnag