在 Scala 中创建具有指定行数和列数的对角矩阵 [英] Create a Diagonal Matrix with specified number of rows and columns in Scala

查看:39
本文介绍了在 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

我可以把这些矩阵相加,所以matrixdiagonals会变成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

我们可以创建一个具有指定数量的对角线作为对角矩阵1 基于下面给出的答案.但是由于的数量太大,我需要一个优化的解决方案.或者有什么更好的解决方案可以使 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆