Scala Breeze 中的条件切片

Conditional slicing in Scala Breeze

我尝试根据另一个 DenseVector 上的元素布尔条件对 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

有了Python/Numpy,我就写y[x>1.5]

使用 Breeze,您必须使用 comprehensions 进行过滤 DenseVectors

val y = DenseVector(10.0,20,0,30.0)

val newY = for {
  v <- y
  if v > 1.5
} yield v

// or to write it in one line
val newY = for (v <- y if v > 1.5) yield v

y(x:>1.5) 生成的 SliceVector 只是原始 DenseVector 的一个视图。要创建新的 DenseVector,请使用

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