Question

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.

Was it helpful?

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.

OTHER TIPS

Breeze now supports broadcasting of this sort:

scala> val dm = DenseMatrix( (2, 4, 6), (3, 6, 9) )
dm: breeze.linalg.DenseMatrix[Int] = 
2  4  6  
3  6  9  

scala> val dv = DenseVector(2,3)
dv: breeze.linalg.DenseVector[Int] = DenseVector(2, 3)

scala> dm(::, *) :/ dv
res4: breeze.linalg.DenseMatrix[Int] = 
1  2  3  
1  2  3  

The * operator says which axis to broadcast along. Breeze doesn't allow implicit broadcasting, except for scalar types.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top