array transpose in scala
Asked Answered
A

1

5

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 }
Aweinspiring answered 2/5, 2016 at 14:13 Comment(3)
What went wrong? How are we supposed to know when you don't tell us and don't post the code you tried?Kerrill
Sorry, I posted my codeAweinspiring
We need a little more info since you are not trying to do traditional matrix multiplication I.e. Traditional Matrix multiplication takes an m x n matrix and a n x o matrix and creates a m x o matrix. Here you have a 11 x 2 and a 3 x 1Owlish
I
14
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))
Inboard answered 2/5, 2016 at 16:36 Comment(1)
Thanks. I finally used for loop to doAweinspiring

© 2022 - 2024 — McMap. All rights reserved.