Search code examples
scalabreeze

Conditional slicing in Scala Breeze


I try to slice a DenseVector based on a elementwise boolean condition on another DenseVector:

  import breeze.linalg.DenseVector
  val x = DenseVector(1.0,2.0,3.0)
  val y = DenseVector(10.0,20,0,30.0)

  // I want a new DenseVector containing all elements of y where x > 1.5
  // i.e. I want DenseVector(20,0,30.0)
  val newy = y(x:>1.5) // does not give a DenseVector but a SliceVector

With Python/Numpy, I would just write y[x>1.5]


Solution

  • The SliceVector resulting from y(x:>1.5) is just a view on the original DenseVector. To create a new DenseVector, use

    val newy = y(x:>1.5).toDenseVector