Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic approach to perform elementwise addition to an Array of Arrays in Scala

I have an Array[Array[Float]] for which it is guaranteed that all inner arrays are of the same length. I want to perform elementwise addition on all inner arrays.

Let me illustate this with a concrete example. Let's say my Array contains three Arrays consisting of seven Floats, with the following values:

Array[Array[Float]] = Array(
                          Array(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0), 
                          Array(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0), 
                          Array(0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0)
                      )

Now I want to transform this into an Array of size 7, of which the n-th element is the sum of n-th elements in my input Array. For my example input the output would be:

Array[Float] = Array(1.0, 3.0, 3.0, 5.0, 5.0, 7.0, 7.0)

For performing this operation on two Array[Float]'s I know I can zip them and then add the elements with a map. I still struggle however to find a more generic solution that is able to sum any number of Array[Float]'s elementwise.

Any help would be much appreciated!

like image 393
Niek Tax Avatar asked Jul 23 '14 09:07

Niek Tax


2 Answers

scala> a.transpose.map(_.sum)
res1: Array[Double] = Array(1.0, 3.0, 3.0, 5.0, 5.0, 7.0, 7.0)
like image 143
Marth Avatar answered Oct 27 '22 01:10

Marth


Another approach,

(0 until a(0).size).map (i => a.map(_(i)).sum)
res: Vector(1.0, 3.0, 3.0, 5.0, 5.0, 7.0, 7.0)

And a version that relies on parallel collection ParSeq, which may prove more efficient for a (very) large number of input rows,

(0 until a(0).size).par.map (i => a.map(_(i)).sum)
res: ParVector(1.0, 3.0, 3.0, 5.0, 5.0, 7.0, 7.0)
like image 43
elm Avatar answered Oct 27 '22 00:10

elm