Skip to main content

Multiplication of two matrix in scala

matrix multiplication formula

Scala program for Multiplication of two matrix. Here more solutions.

/*
  Scala program for
  Two matrix multiplication
*/
class Multiply()
{
	// Display the element of given 2d matrix
	def printRecord(matrix: Array[Array[Int]]): Unit = {
		println("  --------------");
		// Assume  N x N Matrix size
		var row: Int = matrix.length;
		var col: Int = matrix(0).length;
		var i: Int = 0;
		// Iterate the row element
		while (i < row)
		{
			var j: Int = 0;
			// Iterate the column element
			while (j < col)
			{
				// Display element value
				print("  " + matrix(i)(j));
				j += 1;
			}
			// Add new line
			println();
			i += 1;
		}
		println();
	}
	def multiplication(a: Array[Array[Int]], 
      b: Array[Array[Int]]): Unit = {
		// Get the size
		var row: Int = a.length;
		var col: Int = a(0).length;
		// This matrix are store the result of multiplication 
		var result: Array[Array[Int]] = Array.fill[Int](row, col)(0);
		var i: Int = 0;
		while (i < row)
		{
			var j: Int = 0;
			while (j < col)
			{
				// Set the initial value of new matrix element
				result(i)(j) = 0;
				var k: Int = 0;
				while (k < row)
				{
					// Multiply matrix A [i] row and [k] columns to 
					// the Matrix B [k] columns and [j] rows.
					result(i)(j) += a(i)(k) * b(k)(j);
					k += 1;
				}
				j += 1;
			}
			i += 1;
		}
		println("  Matrix A");
		// Print element of matrix x
		printRecord(a);
		println("  Matrix B");
		// Print element of matrix y
		printRecord(b);
		println("  Matrix [(A) x (B)]");
		// Display resultant matrix
		printRecord(result);
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
      	var task = new Multiply();
		// Define matrix A
		var a: Array[Array[Int]] = Array(
          Array(1, 2, 3), 
          Array(6, 1, 2), 
          Array(5, 4, 3)
        );
		// Define matrix B
		var b: Array[Array[Int]] = Array(
          Array(3, 1, 3), 
          Array(1, 1, 2), 
          Array(2, 2, 3)
        );
		task.multiplication(a, b);
	}
}

Output

  Matrix A
  --------------
  1  2  3
  6  1  2
  5  4  3

  Matrix B
  --------------
  3  1  3
  1  1  2
  2  2  3

  Matrix [(A) x (B)]
  --------------
  11  9  16
  23  11  26
  25  15  32




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment