Matrix multiplication in Scala

2019-09-20 21:12发布

问题:

I am trying to transpose a matrix of size 3*2 by defining a empty matrix of size 2*3, how can i create an empty matrix?? I am missing something in the commented piece of code!!

type Row = List[Int]
type Matrix = List[Row]

val m:Matrix = List(1 :: 2 :: Nil, 3 :: 4 :: Nil, 5 :: 6 :: Nil)

def transpose(m:Matrix):Matrix = {

  val rows = m.size
  val cols = m.head.size
  val trans= List(List())(rows(cols)) // Int doesn't take parameter

  for (i <- 0 until  cols) {
    for (j <- 0 until  rows) {
      trans(i)(j) = this (j)(i)
    }
  }
  return trans
}

回答1:

When it is necessary to access elements by index, Vector or Array is more efficient than Lists. Here is the Vector version of solution.

type Row = Vector[Int]
type Matrix = Vector[Row]
val m:Matrix = Vector(Vector(1,2), Vector(3,4), Vector(5,6))

def transpose(mat:Matrix) = {
  def size[A](v: Vector[A]): Int = { var x =0; for(i<-v) x+=1; x}
  for (i <-Range(0,size(mat(0)))) yield for(j <-Range(0,size(mat))) yield mat(j)(i)
}

Test in REPL:

scala> transpose(m)
res12: scala.collection.immutable.IndexedSeq[scala.collection.immutable.IndexedSeq[Int]] = Vector(Vector(1, 3, 5), Vector(2,
 4, 6))


标签: scala