how do i multiply two nested array buffers in scala?

You can use, instead Spark matrices, Breeze because it is the most used linear algebra library in Scala. If you are used to work with Numpy or Scipy working with Breeze is similar. You can check all the available operations in https://github.com/scalanlp/breeze/wiki/Linear-Algebra-Cheat-Sheet.

You can build a dense matrix inline:

import breeze.linalg._

val dense1 = DenseMatrix((2,2), (2,2))
val dense2 = DenseMatrix((4,4), (4,4))

And apply the element-wise product:

println(dense1 *:* dense2)

/* 8  8  
   8  8 */

If you have an array representation:

val arr1 = Array(Array(2,2), Array(2,2)).flatten
val arr2 = Array(Array(4,4), Array(4,4)).flatten

val dense3 = new DenseMatrix(2,2, arr1)
val dense4 = new DenseMatrix(2,2, arr2)

println(dense3 *:* dense4)

/* 8  8  
   8  8 */

You need to know that, unlike Numpy/Pyhton, Breeze checks the matrix type at compile time, so the matrices must have the same numerical representation. It doesn´t check the matrices dimensions at compile time.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top