Search code examples
scalamatrixvectorbreeze

Need workaround for scala breeze matrix slicing and vector indexing


Because of the odd behaviour in method foo I cannot write methods like bar, which I need:

import breeze.linalg.DenseMatrix
import breeze.linalg.DenseVector

class Test {

    val dim = 3
    val X:DenseMatrix[Double] = DenseMatrix.rand(dim,dim)
    val u:DenseVector[Double] = DenseVector.fill(dim){1.0}

    def foo:Unit = {

        val i=0;
        val row_i:DenseVector[Double] = X(i,::).t  // OK
        val s = u(i)+u(i)                          // OK

        val j:Integer = 0
        val row_j:DenseVector[Double] = X(j,::).t  // does not compile (A)
        val a = u(j)+u(j)                          // does not compile (B)
    }
    def bar(i:Integer):Double = u(i)+u(i)          // does not compile (C)
}

Is there a workaround? Thanks in advance for all replies.

Compilation errors:

(A) could not find implicit value for parameter canSlice: breeze.linalg.support.CanSlice2[breeze.linalg.DenseMatrix[Double],Integer,collection.immutable.::.type,Result] not enough arguments for method apply: (implicit canSlice: breeze.linalg.support.CanSlice2[breeze.linalg.DenseMatrix[Double],Integer,collection.immutable.::.type,Result])

Result in trait TensorLike. Unspecified value parameter canSlice.

(B), (C)

could not find implicit value for parameter canSlice: breeze.linalg.support.CanSlice[breeze.linalg.DenseVector[Double],Integer,Result] not enough arguments for method apply: (implicit canSlice: breeze.linalg.support.CanSlice[breeze.linalg.DenseVector[Double],Integer,Result])Result in trait TensorLike. Unspecified value parameter canSlice.


Solution

  • First off: convert your Integer to Int . That would take care of at least the first compilation error. Following update to your code does compile

    import breeze.linalg.DenseMatrix
    import breeze.linalg.DenseVector
    import breeze.linalg.DenseMatrix
    import breeze.linalg.DenseVector
    
    class Test {
    
        val dim = 3
        val X:DenseMatrix[Double] = DenseMatrix.rand(dim,dim)
        val u:DenseVector[Double] = DenseVector.fill(dim){1.0}
    
        def foo:Unit = {
    
            val i=0;
            val row_i:DenseVector[Double] = X(i,::).t  // OK
            val s = u(i)+u(i)                          // OK
    
            val j:Int = 0
            val row_j:DenseVector[Double] = X(j,::).t  // does not compile (A)
            val a = u(j)+u(j)                          // does not compile (B)
        }
        def bar(i:Int):Double = u(i)+u(i)          // does not compile (C)
    }
    

    From the repl:

    // Exiting paste mode, now interpreting.
    
    import breeze.linalg.DenseMatrix
    import breeze.linalg.DenseVector
    defined class Test
    

    So your other errors also disappear for me (scala 2.11.8). Let me know if you have further issues.