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

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

基于下面给出的答案,我们可以创建具有指定数量的rowscolumnsdiagonals作为1diagonal matrix.但是由于rowscolumns的数量太大,我需要一个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屋!

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