Slicing a SparseVector to get a SparseVector in Scalala

174 Views Asked by At

I'd like to slice a sparse vector in scalala and get another sparse vector. A normal slice always gives a standard vector. Can I provide an implicit function for doing this while slicing and if so what would it look like?

As an example, I'd like to accomplish the following:

val v:SparseVectorRow[Double] = ...
val v2:SparseVectorRow[Double] = v(List(1,3,5))

Lastly, I'm using Scalala release 1.0.0.RC3-SNAPSHOT.

Thanks in advance.

1

There are 1 best solutions below

0
On

Yes, you can define your own appropriately parametrized CanSliceVector. The following isn't generic or necessarily efficient, but it works:

import scalala.generic.collection.CanSliceVector

implicit object svrSlicer extends
  CanSliceVector[SparseVectorRow[Double], Int, SparseVectorRow[Double]] {
  def apply(from: SparseVectorRow[Double], keys: Seq[Int]) =
    SparseVector.create(from.size)(keys.map(k => (k, from(k))): _*).t
}

val v: SparseVectorRow[Double] = SparseVector.create(10)((0, 1.0), (3, 2.0)).t
val v2: SparseVectorRow[Double] = v(List(1, 3, 5))

You could poke around in the Scalala source to figure out the "right" way to do this.