rubymatrixmultidimensional-arraysketchup

How to sum two dimensional arrays


I have a two dimensional array = [[12,34,35,21],[10,14,23,17],...] infinity.

I would like to do this in ruby;

arr1 = [array[0][0]+array[1][0]+array[n+1][0]...,
array[0][1]+array[1][1]+array[n+1][1]...,
array[0][2]+array[1][2]+array[n+1][2]...,
array[0][3]+array[1][3]+array[n+1][3]...] 

result (4x4)

arr1 = [[12+10+..],[34+14+..],[35+23..],[21+17+..]]

Any idea?


Solution

  • You can use Array#transpose, and then sum each individual Array

    array = [[12,34,35,21],[10,14,23,17]]
    
    array.transpose.map {|a| a.inject(:+) }
    # => [22, 48, 58, 38]
    

    If you are using Ruby 2.4 or greater, you can use the Array#sum method

    array.transpose.map(&:sum)
    # => [22, 48, 58, 38] 
    

    For the output to be an Array or Arrays,

    array.transpose.map {|a| [a.sum] }
    # => [[22], [48], [58], [38]]