矩阵生成TestUtils.scala
- // See README.md for license details.
- package gemmini
-
- object TestUtils {
- type Matrix[T] = Seq[Seq[T]]
-
- def rows[T](m: Matrix[T]) = m.length
- def cols[T](m: Matrix[T]) = m.head.length
- def dims[T](m: Matrix[T]) = (rows(m), cols(m))
-
- def mult[A](a: Matrix[A], b: Matrix[A])(implicit n: Numeric[A]): Matrix[A] = {
- import n._
- for (row <- a)
- yield for(col <- b.transpose)
- yield row zip col map Function.tupled(_*_) reduceLeft (_+_)
- }
-
- def add[A](a: Matrix[A], b: Matrix[A])(implicit n: Numeric[A]): Matrix[A] = {
- import n._
- for ((ra, rb) <- a zip b)
- yield for ((elema, elemb) <- ra zip rb)
- yield elema + elemb
- }
-
- def identity(dim: Int): Matrix[Int] = {
- for (i <- 0 until dim)
- yield Seq.fill(i)(0) ++ Seq(1) ++ Seq.fill(dim-i-1)(0)
- }
-
- def consecutive(dim: Int): Matrix[Int] = {
- (1 to dim*dim).grouped(dim).toSeq
- }
-
- def zero(dim: Int): Matrix[Int] = Seq.fill(dim, dim)(0)
-
- def rand(dim: Int, max: Int = 32): Matrix[Int] = Seq.fill(dim, dim)(scala.util.Random.nextInt(max))
-
- def print2DArray[A](a: Matrix[A]): Unit = {
- a.foreach {
- line => println(line.map(_.toString).reduce(_ + "\t" + _))
- }
- }
- }
- // See README.md for license details.
- package gemmini
-
- object TestUtils {
- //定义二维矩阵
- type Matrix[T] = Seq[Seq[T]]
- //获取矩阵的行数、列数和维度的函数。rows函数返回矩阵的行数,cols函数返回矩阵的列数,dims函数返回矩阵的维度
- def rows[T](m: Matrix[T]) = m.length
- def cols[T](m: Matrix[T]) = m.head.length
- def dims[T](m: Matrix[T]) = (rows(m), cols(m))
- //用于矩阵乘法
- def mult[A](a: Matrix[A], b: Matrix[A])(implicit n: Numeric[A]): Matrix[A] = {
- //函数使用嵌套的for推导式来遍历矩阵a的每一行和矩阵b的每一列
- //在每个元素位置上,它使用row zip col将两个对应位置的元素组成一个元组,然后对该元组应用乘法操
- //使用Function.tupled将乘法操作应用到每个元素上
- //最后,使用reduceLeft和+_将每一行中的乘积相加,得到最终的结果矩阵。
- import n._
- for (row <- a)
- yield for(col <- b.transpose)
- yield row zip col map Function.tupled(_*_) reduceLeft (_+_)
- }
- //矩阵加法
- def add[A](a: Matrix[A], b: Matrix[A])(implicit n: Numeric[A]): Matrix[A] = {
- import n._
- for ((ra, rb) <- a zip b)
- yield for ((elema, elemb) <- ra zip rb)
- yield elema + elemb
- }
- //生成单位矩阵
- def identity(dim: Int): Matrix[Int] = {
- for (i <- 0 until dim)
- yield Seq.fill(i)(0) ++ Seq(1) ++ Seq.fill(dim-i-1)(0)
- }
- //生成连续数字矩阵
- def consecutive(dim: Int): Matrix[Int] = {
- (1 to dim*dim).grouped(dim).toSeq
- }
- //生成全零矩阵
- def zero(dim: Int): Matrix[Int] = Seq.fill(dim, dim)(0)
- //生成随机整数矩阵
- def rand(dim: Int, max: Int = 32): Matrix[Int] = Seq.fill(dim, dim)(scala.util.Random.nextInt(max))
- //打印
- def print2DArray[A](a: Matrix[A]): Unit = {
- a.foreach {
- line => println(line.map(_.toString).reduce(_ + "\t" + _))
- }
- }
- }