Search code examples
scalaoctavescala-breeze

Scala Breeze expansion matrix


In Octave/Matlab I can expand an identity matrix as follows.

>> I = eye(3)
I =
Diagonal Matrix
  1   0   0
  0   1   0
  0   0   1

>> A = [ 3 2 3 2 2 1 3 2 2 1 ]

>> E = I(:, A)
E =
   0   0   0   0   0   1   0   0   0   1
   0   1   0   1   1   0   0   1   1   0
   1   0   1   0   0   0   1   0   0   0

How can I achieve the same thing (i.e. obtain E from A, possibly using I) with Scala/Breeze ?


Solution

  • Got it. Actually very similar to Octave.

    scala> val I = DenseMatrix.eye[Int](3)
    I: breeze.linalg.DenseMatrix[Int] =
    1  0  0
    0  1  0
    0  0  1
    
    scala> val A = DenseMatrix(2, 1, 2, 1, 1, 0, 2, 1, 1, 0) // zero based in breeze
    
    scala> I(::, A.toArray.toSeq)
    res26: breeze.linalg.SliceMatrix[Int,Int,Int] =
    0  0  0  0  0  1  0  0  0  1
    0  1  0  1  1  0  0  1  1  0
    1  0  1  0  0  0  1  0  0  0
    

    The caveats are:

    • the matrices must contain Integers
    • indices are 0 based (as opposed to 1 based in Octave/Matlab)