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 }
3
  • 1
    What went wrong? How are we supposed to know when you don't tell us and don't post the code you tried? Commented May 2, 2016 at 15:10
  • Sorry, I posted my code Commented May 2, 2016 at 16:06
  • 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 1 Commented May 2, 2016 at 16:07

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I finally used for loop to do

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.