Search code examples
scalabreeze

breeze Copy lower triangle not working?


Using breeze 0.13, Scala 2.12.3

I would like to create a symmetric matrix by copying the lower triangle to the upper one. Following the instructions in Linear Algebra Cheat Sheet. May be I use the function incorrectly but it seems like the lowerTriangular function is not working correctly. The copy just

val myMtx = breeze.linalg.DenseMatrix((1,-8,-9) , (2,1,-7), (3,5,1))
//myMtx: breeze.linalg.DenseMatrix[Int] = 
//  1  -8  -9
//  2   1  -7
//  3   5   1

Copy lower triangle (seems not working)

breeze.linalg.lowerTriangular(myMtx)
//  1  0  0
//  2  1  0
//  3  5  1

Copy upper triangle (not working either)

breeze.linalg.upperTriangular(myMtx)
//  1  -8  -9
//  0   1  -7
//  0   0   1

Solution

  • In this context, "copy" means returns the matrix in a newly allocated memory. This is contrast with a "view" that indexes into the same backing memory.

    With that in mind, both lowerTriangular and upperTriangular seem to be working properly in that it returns a new matrix that has the same elements copied from the original matrix.

    The task is now to create a new symmetric matrix that is the copy of the lower triangular. One possible way is to compute the element-wise sum of the lower and lower diagonal transpose, and then subtract the extra copy of the diagonal that was computed. The inner diag() returns a view, as described above, as a vector and that vector is then used to create a diagonal matrix with the second diag().

    @ val sym = lowerTriangular(myMtx) + lowerTriangular(myMtx).t - diag(diag(myMtx)) 
    sym: DenseMatrix[Int] = 
    1  2  3  
    2  1  5  
    3  5  1