Reputation: 13
I am trying to do operation on array in Scala.
x is a 2d-array and y is a 1d-array. For example
val x = Array(Array(1.0,2.0,3.0),Array(4.0,5.0,6.0),Array(7.0,8.0,9.0),Array(10.0,11.0,12.0).....Array(..))
val y = Array(2.0,3.0,4.0,5.0,.....n)
Assume that x.length = y.length
I wish to get a Array[Double](3)
like
Array(1.0*2.0 + 4.0*3.0 + 7.0 * 4.0 + 10.0 * 5.0 ...., 2.0*2.0 + 5.0*3.0 + 8.0*4.0 + 11.0 * 5.0 ....., 3.0*2.0 + 6.0 * 3.0 + 9.0 * 4.0 + 12.0 * 5.0....)
I don't know how to do.
I used x.map(x => (x zip y).map{case(a, b) => a * b})
Obviously wrong, what's the ideal way to do that?
Thanks
Upvotes: 1
Views: 91
Reputation: 37822
Using transpose
turns x
's columns into rows, which makes this easier - each column can then be zipped with y
, and then the values can be multiplied and summed:
val x = Array(Array(1.0,2.0,3.0),Array(4.0,5.0,6.0),Array(7.0,8.0,9.0),Array(10.0,11.0,12.0))
val y = Array(2.0,3.0,4.0,5.0)
val result = x.transpose.map(_.zip(y).map { case (a, b) => a*b }.sum )
print(result.mkString(",")) // prints 92.0,106.0,120.0
Upvotes: 2