Returns element (i,j) of the matrix

I learn matrix of ruby,and I want to extract the elements in the matrix and find that there is a defined function on the Internet, but I can’t find the result using this function operation. Why is this?
Here is my code:

require "Matrix"
def [](i, j)   
@rows.fetch(i){return nil}[j]
p Matrix[[1,2,3],[4,5,6],[7,8,9]](1,2)

You could try something like transformation.to_a[row * 4 + col], if you are refering to SketchUp’s transformation matrix.

1 Like

The square brackets in the matrix class are confusing (and you have only 2 dimensions, not 1000).
You mean:

my_matrix = Matrix[[1,2,3],[4,5,6],[7,8,9]] # This is a shortcut for which is for some reason private
p(my_matrix[1,2]) # The accessor method is []

SketchUp is not written in Ruby but in fast C++, and does not share most data structures with the Ruby standard library. Much of the Ruby standard library is implemented in rather slow Ruby and only parts in faster C. Vector and matrix math is usually computationally expensive! But Ruby’s Matrix multiplication is not only slow due the programming language but also due to the choice of not optimal algorithms.

If you do not require features like determinant or matrix decompositions, consider using SketchUp’s Transformation class which is actually backed by a 4×4 matrix (transformations could also be represented in different ways other than matrix, but knowing it uses a matrix here is an advantage).

def create_3x3_matrix(columns)
  # SketchUp can create a transformation which represents a 4×4 matrix from
  # a flattened array of 4×4 elements. We fill up the unused elements with 
  # zero and fill in the provided elements.
  array = [0] * 16
  columns.each_with_index{ |row, i|
    row.each_with_index{ |v, j|
      array[i * 4 + j] = v

def get_elem_from_matrix(matrix, i, j)
  return matrix.to_a[i * 4 + j]

my_matrix = create_3x3_matrix([[1,2,3],[4,5,6],[7,8,9]])
p(get_elem_from_matrix(my_matrix, 1, 2))

If you just want to learn programming fast matrix math without SketchUp, look at Python with Numpy or Julia (the programming language).

1 Like