Create a Diagonal Matrix with specified number of rows and columns in Scala

本秂侑毒 提交于 2019-12-13 04:11:29

问题


I have an input mllib Block matrix named matrix like,

matrix : org.apache.spark.mllib.linalg.Matrix =
0.0  2.0  1.0  2.0
2.0  0.0  2.0  4.0
1.0  2.0  0.0  3.0
2.0  4.0  3.0  0.0

As per my Scala code, diagonals will be zero for sure. I need the diagonals of the matrix to be 1. If I have a diagonal matrix with diagonal values as 1 like,

diagonalMatrix: org.apache.spark.mllib.linalg.Matrix =
1.0  0.0  0.0  0.0
0.0  1.0  0.0  0.0
0.0  0.0  1.0  0.0
0.0  0.0  0.0  1.0

I can add those matrices, So the diagonals of matrix will be changed to 1.

matrix : org.apache.spark.mllib.linalg.Matrix =
    1.0  2.0  1.0  2.0
    2.0  1.0  2.0  4.0
    1.0  2.0  1.0  3.0
    2.0  4.0  3.0  1.0

We can create a diagonal matrix with specified number of rows and columns and diagonals as 1 based on the answer given below. But as the number of rows and columns were too big, I need an optimized solution. Or is there any better solution to make diagonals of matrix to 1 ?


回答1:


val nR = 5
val nC = 5

val seq = for {
  i <- 0 until nC
  j <- 0 until nR
  v = if (i == j) 1d else 0d
} yield v

val matrix = DenseMatrix(nR, nC, seq.toArray)


来源:https://stackoverflow.com/questions/51242763/create-a-diagonal-matrix-with-specified-number-of-rows-and-columns-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!