Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum up every column of a Scala array?

Tags:

arrays

scala

If I have an array of array (similar to a matrix) in Scala, what's the efficient way to sum up each column of the matrix? For example, if my array of array is like below:

val arr =  Array(Array(1, 100, ...), Array(2, 200, ...), Array(3, 300, ...))

and I want to sum up each column (e.g., sum up the first element of all sub-arrays, sum up the second element of all sub-arrays, etc.) and get a new array like below:

newArr = Array(6, 600, ...)

How can I do this efficiently in Spark Scala?

like image 952
Carter Avatar asked Oct 01 '15 03:10

Carter


1 Answers

There is a suitable .transpose method on List that can help here, although I can't say what its efficiency is like:

arr.toList.transpose.map(_.sum)

(then call .toArray if you specifically need the result as an array).

like image 146
Shadowlands Avatar answered Sep 22 '22 16:09

Shadowlands