Search code examples
scalamatrixlinear-algebrascala-breeze

Create an new DenseMatrix from an submatrix in Breeze using Scala


I've a DenseMatrix (original). I slice it to remove the last column (subset). After that I want to access the data in the subset. However, subset.data still points to the data in the old DenseMatrix (original). Any idea what I'm missing here and how to fix this ?

original: breeze.linalg.DenseMatrix[Int] = 
1    200  3  0    
10   201  4  0    
111  200  0  100  
150  195  0  160  
200  190  0  150  

scala> val numcols = original.cols
numcols: Int = 4

scala> val subset = original(::, 0 to numcols - 2)
subset: breeze.linalg.DenseMatrix[Int] = 
1    200  3  
10   201  4  
111  200  0  
150  195  0  
200  190  0  

scala> subset.data
res0: Array[Int] = Array(1, 10, 111, 150, 200, 200, 201, 200, 195, 190, 3, 4, 0, 0, 0, 0, 0, 100, 160, 150)

scala> subset.data.size
res1: Int = 20

Solution

  • Never mind I figured out one way of doing it.

    by using the following

    scala> subset.toDenseMatrix.data
    res10: Array[Int] = Array(1, 10, 111, 150, 200, 200, 201, 200, 195, 190, 3, 4, 0, 0, 0)
    
    scala> subset.toDenseMatrix.data.size
    res11: Int = 15