What's the efficient way to multiply two arrays and get sum of multiplied values in Ruby?

前端 未结 9 901
猫巷女王i
猫巷女王i 2021-02-09 12:54

What\'s the efficient way to multiply two arrays and get sum of multiply values in Ruby? I have two arrays in Ruby:

array_A = [1, 2, 1, 4, 5, 3, 2, 6, 5, 8, 9]
a         


        
相关标签:
9条回答
  • 2021-02-09 13:26

    Try the NMatrix gem. It is a numerical computation library. I think it uses the same C and C++ libraries that Octave and Matlab uses.

    You would be able to do the matrix multiplication like this:

    require 'nmatrix'
    
    array_A = [1, 2, 1, 4, 5, 3, 2, 6, 5, 8, 9]
    array_B = [3, 2, 4, 2, 5, 1, 3, 3, 7, 5, 4]
    
    vec_a = array_A.to_nm([1,array_A.length])    # create an NMatrix
    vec_b = array_B.to_nm([1,array_B.length])
    
    sum = vec_a.dot(vec_b.transpose)
    

    I am not sure how the speed will compare using pure Ruby but I imagine it to be faster, especially for large and sparse vectors.

    0 讨论(0)
  • 2021-02-09 13:26
    array1.zip(array2).map{|x| x.inject(&:*)}.sum
    
    0 讨论(0)
  • 2021-02-09 13:27

    I would start simple and use the Ruby matrix class:

    require 'matrix'
    
    a = Matrix.row_vector( [1, 2, 1, 4, 5, 3, 2, 6, 5, 8, 9])
    b = Matrix.column_vector([3, 2, 4, 2, 5, 1, 3, 3, 7, 5, 4])
    
    result= a * b
    puts result.element(0,0)
    

    If this turns out to be too slow, then do the exact same method but with an external math library.

    0 讨论(0)
提交回复
热议问题