在Scala中创建具有指定行数和列数的对角矩阵 [英] Create a Diagonal Matrix with specified number of rows and columns in Scala
问题描述
我有一个名为matrix
的输入mllib
块矩阵,
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
按照我的Scala代码,对角线肯定是zero
.我需要matrix
的对角线为1.如果我有一个diagonal matrix
且对角线值为1
,
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
我可以添加这些矩阵,因此matrix
的diagonals
将更改为1.
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
基于下面给出的答案,我们可以创建具有指定数量的rows
和columns
和diagonals
作为1
的diagonal matrix
.但是由于rows
和columns
的数量太大,我需要一个optimized solution
.还是有更好的解决方案将对角线matrix
设置为1
?
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
?
推荐答案
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)
这篇关于在Scala中创建具有指定行数和列数的对角矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!