Search code examples
scalaapache-sparkscala-breeze

How to replace elements of a breeze matrix in Scala based on some condition?


I am working with 2 dimensional Breeze matrices in Scala. At some point I have to do element-wise division of two matrices. Some elements in the denominator matrix can be zero, resulting into NaNs in the result.

I can loop through the matrix dimensions and replace the 0.0s with something >0.

But is there a simpler or Scala idiomatic solution for this?


Solution

  • Step-by-step:

    • With example matrix:

      val dm = DenseMatrix((1.0, 0.0, 3.0), (0.0, 5.0, 6.0))
      
    • Find out which elements are equal to 0.0:

      dm :== 0.0
      
      breeze.linalg.DenseMatrix[Boolean] =
      false  true   false
      true   false  false
      
    • Slice the matrix:

      dm(dm :== 0.0)
      
      breeze.linalg.SliceVector[(Int, Int),Double] = breeze.linalg.SliceVector@2b
      
    • Use sliced matrix for replacement:

      dm(dm :== 0.0) := 42.0
      
      breeze.linalg.Vector[Double] = breeze.linalg.SliceVector@2b
      
    • Check the matrix:

      dm
      
      breeze.linalg.DenseMatrix[Double] =
      1.0   42.0  3.0
      42.0  5.0   6.0