Search code examples
scalascalalascala-breeze

Using Scala Breeze to do numPy style broadcasting


Is there a generic way using Breeze to achieve what you can do using broadcasting in NumPy?

Specifically, if I have an operator I'd like to apply to two 3x4 matrices, I can apply that operation element-wise. However, what I have is a 3x4 matrix and a 3-element column vector. I'd like a function which produces a 3x4 matrix created from applying the operator to each element of the matrix with the element from the vector for the corresponding row.

So for a division:

2 4 6   /  2 3  = 1 2 3
3 6 9             1 2 3

If this isn't available. I'd be willing to look at implementing it.


Solution

  • You can use mapPairs to achieve what I 'think' you're looking for:

      val adder = DenseVector(1, 2, 3, 4)
    
      val result = DenseMatrix.zeros[Int](3, 4).mapPairs({
        case ((row, col), value) => {
          value + adder(col)
        }
      })
    
      println(result)
    
    1  2  3  4  
    1  2  3  4  
    1  2  3  4  
    

    I'm sure you can adapt what you want from simple 'adder' above.