Skip to main content

Multiplication of two matrix in typescript

matrix multiplication formula

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

/*
  Java program for
  Two matrix multiplication
*/
class Multiply
{
	// Display the element of given 2d matrix
	static printRecord(matrix)
	{
		console.log("  --------------");
		
		console.log(" ",matrix);
	}
	static multiplication(a, b)
	{
		// Get the size
		var row = a.length;
		var col = a[0].length;
		// This matrix are store the result of multiplication 
		var result = Array(row).fill(
          0).map(() => new Array(col).fill(0));
		for (var i = 0; i < row; ++i)
		{
			for (var j = 0; j < col; ++j)
			{
				// Set the initial value of new matrix element
				result[i][j] = 0;
				for (var k = 0; k < row; ++k)
				{
					// 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];
				}
			}
		}
		console.log("  Matrix A");
		// Print element of matrix x
		Multiply.printRecord(a);
		console.log("  Matrix B");
		// Print element of matrix y
		Multiply.printRecord(b);
		console.log("  Matrix [(A) x (B)]");
		// Display resultant matrix
		Multiply.printRecord(result);
	}
	static main()
	{
		// Define matrix A
		var a = [
			[1, 2, 3],
			[6, 1, 2],
			[5, 4, 3]
		];
		// Define matrix B
		var b = [
			[3, 1, 3],
			[1, 1, 2],
			[2, 2, 3]
		];
		Multiply.multiplication(a, b);
	}
}
Multiply.main();

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