Scala matrix multiplication

Chintu Source

Eg Matrix A =

1 2 3
4 5 6

Matrix B =

7 8
9 10
11 12

Matrix AB =

58 64
139 154

I was able to achieve the above using the inbuilt map and dot, but is there a way that it can programmed without any use of those inbuilt scala functions. I am new to functional programming .

scala

Answers

answered 4 days ago jwvh #1

After figuring out how to transpose a matrix via recursion (class assignment?), it's just a matter of translating nested map() calls into nested recursive methods.

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

def transpose(m:Matrix):Matrix = {
  def loop(data :List[Int], result :Matrix, reserve :Matrix) :Matrix = {
    if (data.isEmpty) result
    else result match {
      case hd::Nil => loop(data.tail, ((data.head::hd)::reserve).reverse, Nil)
      case hd::tl  => loop(data.tail, tl, (data.head::hd)::reserve)
      case _ => Nil
    }
  }
  loop(m.reverse.flatten, List.fill(m.head.length)(Nil), Nil)
}

def multMatrix(ma :Matrix, mb :Matrix) :Matrix = {
  def multRows(ra :Row, rb :Row, acc :Int = 0) :Int =
    if (ra.isEmpty || rb.isEmpty) acc
    else multRows(ra.tail, rb.tail, acc + ra.head * rb.head)

  def mkRow(r :Row, m :Matrix, acc :Row = Nil) :Row =
    if (m.isEmpty) acc.reverse
    else mkRow(r, m.tail, multRows(r, m.head) :: acc)

  def mkMtrx(ma :Matrix, mb :Matrix, acc :Matrix = Nil) :Matrix =
    if (ma.isEmpty) acc.reverse
    else mkMtrx(ma.tail, mb, mkRow(ma.head, mb) :: acc)

  mkMtrx(ma, transpose(mb))
}

Note: this code doesn't do any safety checks so it will fail if either Matrix is poorly formed.

comments powered by Disqus