作者名:Rajdeep Dua Manpreet Singh Ghotra Nick Pentreath
本章字數:306字
更新時間:2021-07-09 21:07:49
Types of matrices
In Scala, we will use the Breeze library to represent a matrix. A matrix can be represented as a dense or a CSC matrix.
Dense matrix: A dense matrix is created with a constructor method call. Its elements can be accessed and updated. It is a column major, and can be transposed to convert to row major.
val a = DenseMatrix((1,2),(3,4)) println("a : n" + a) val m = DenseMatrix.zeros[Int](5,5)
The columns of a matrix can be accessed as Dense Vectors, and the rows as Dense Matrices.
Transposing a matrix: Transposing a matrix means swapping its rows and columns. The transpose of a P × Q matrix, written MT, is a Q × P matrix such that (MT ) j, I = Mi, j for every I ∈ P, j ∈ Q. Vector transpose to create a matrix row.
m(4,::) := DenseVector(5,5,5,5,5).t println(m)
The output of the preceding program is as follows:
a : 1 2 3 4 Created a 5x5 matrix 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 m.rows :5 m.cols : 5 First Column of m : DenseVector(0, 0, 0, 0, 0) Assigned 5,5,5,5,5 to last row of m.
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 5 5 5 5
CSC matrix: The CSC matrix is known as the Compressed Sparse Columns matrix. Each column within the CSC matrix represents a sparse vector. The CSC matrix supports all matrix operations, and is constructed using Builder.
val builder = new CSCMatrix.Builder[Double](rows=10, cols=10) builder.add(3,4, 1.0) // etc. val myMatrix = builder.result()