Multiply two matrices in node js

Js program for Two Matrix Multiplication. Here mentioned other language solution.
/*
Node JS program for
Two matrix multiplication
*/
// Display the element of given 2d matrix
function printRecord(matrix)
{
console.log(" ",matrix);
}
function 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
printRecord(a);
console.log(" Matrix B");
// Print element of matrix y
printRecord(b);
console.log(" Matrix [(A) x (B)]");
// Display resultant matrix
printRecord(result);
}
function 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]
];
multiplication(a, b);
}
// Start program execution
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 ] ]
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