Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array transpose in scala

I have 2 scala array and I would like to multiply them.

val x = Array(Array(1,2),Array(3,4),Array(5,6),Array(7,8),Array(9,10),Array(11,12),Array(13,14),Array(15,16),Array(17,18),Array(19,20),Array(21,22))

val y = Array(2, 5, 9)

I wish to get a Array.ofDim[Int](3, 2) like

val z = Array(Array(1*2 + 3 *2 + 5*2 + 7*2... 2*2 + 4*2 + 6*2 + 8*2...,),Array(1*5 + 3*5 + 5*5 + 7*5... 2*5 + 4*5 + 6*5 + 8*5...,),Array(1*9 + 3 *9 + 5*9 + 7*9... 2*9 + 4*9 + 6*9 + 8*9...,)

I tried to use x.transpose, then zip y to do.

But it was something wrong.

How can I do that?

Sorry, my code is

x.transpose.map(_.sum) zip y map {case(a, b) => a * b }
like image 617
Joey Kim Avatar asked May 02 '16 14:05

Joey Kim


1 Answers

scala> val z = x.transpose
z: Array[Array[Int]] = Array(Array(1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21), Array(2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22))

scala> z map (arr => y map (k => arr.foldLeft(0)((acc, i) => acc + (i*k)))) 
res15: Array[Array[Int]] = Array(Array(242, 605, 1089), Array(264, 660, 1188))

scala> res15.transpose
res16: Array[Array[Int]] = Array(Array(242, 264), Array(605, 660), Array(1089, 1188))
like image 183
saheb Avatar answered Oct 11 '22 18:10

saheb