0

I have two 2d-array and I want to multiply such as

val x = Array(Array(2.0, 5.0))
val y = Array(Array(1.0, -1.0), Array(-1.0, 1.0), Array(2.0, -2.0))

I want to get 1d-Array like

Array(2.0 * 1.0 + 5.0 * -1.0, 2.0 * -1.0 + 5.0 * 1.0, 2.0 * 2.0 + 5.0 * -2.0)

I used x.zip(y) map (_.zipped map (_ * _)) map (_.sum)

But I only get Array(-3.0)

What am I supposed to do?

Thanks for your time.

Sorry, my mean is that x array's size will always be 1 item like Array(Array(2.0, 5.0))

4
  • Will there be only 1 item in x ? Commented Apr 25, 2016 at 18:21
  • @ccheneson If I assign x.zip(y) map (.zipped map ( * )) map (.sum) to z val z = x.zip(y) map (.zipped map ( * )) map (.sum) I will get z = Array[Double](-3.0) Commented Apr 25, 2016 at 18:24
  • What I mean is if x could be for example Array(Array(2.0, 5.0), Array(6.0, 2.0)) or there will always be 1 item like Array(Array(2.0, 5.0)) ? Commented Apr 25, 2016 at 18:45
  • 1
    Please elaborate on your question. What would happen if x size is different than 1? Are nested arrays always of the same size? Commented Apr 25, 2016 at 19:23

1 Answer 1

2

For the x and y defined above, the following should work. However, if x is an Array of Arrays, then the answer would be different.

scala> y map {x.flatten zip _ map {case(a,b) => a*b} reduce (_+_)}
res5: Array[Double] = Array(-3.0, 3.0, -6.0)
Sign up to request clarification or add additional context in comments.

3 Comments

The generic answer, regardless of the size of the sub arrays would be something like val z = y map { y1 => x map{ _ zip y1 map { case(a,b) => a*b } reduce (_ + _ ) } } that you could then flatten if needed.
reduce(_+_) can be replaced by sum
Thanks for helping me

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.