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!
scala> a.transpose.map(_.sum)
res1: Array[Double] = Array(1.0, 3.0, 3.0, 5.0, 5.0, 7.0, 7.0)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With