Search code examples
scala-breeze

How to slice on arbitrary indices with breeze?


In Python's numpy, I can do this:

>>> import numpy as np
>>> m = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
>>> indices = [1,3]
>>> m[:,indices]
array([[ 2,  4],
       [ 6,  8],
       [10, 12]])

In other words, I can slice based on an arbitrary (not necessarily contiguous) list of indices. How can I do something similar in Breeze? I'm looking for something efficient and preferably elegant.


Solution

  • More or less identically to numpy:

    scala> import breeze.linalg._
    import breeze.linalg._
    
    scala> val m = DenseMatrix((1,2,3,4),(5,6,7,8),(9,10,11,12))
    m: breeze.linalg.DenseMatrix[Int] =
    1  2   3   4
    5  6   7   8
    9  10  11  12
    
    scala> val indices = IndexedSeq(1,3)
    indices: IndexedSeq[Int] = Vector(1, 3)
    
    scala> m(::, indices)
    res0: breeze.linalg.SliceMatrix[Int,Int,Int] =
    2   4
    6   8
    10  12