JavaScript: Matrix Multiplication

Last update: 04 Dec 23:20
0
Students

To multiply two matrices, A and B, is to calculate the resulting matrix C, where each element C(ij) is equal to the sum of the products of the elements in the corresponding row of the first matrix A(ik), and that of the column of the second matrix B(kj).

Matrix multiplication requires the number of columns in the first matrix to coincide with the number of rows in the second matrix. So the first matrix must necessarily be compatible with the second matrix. Multiplication of a matrix of size M×N by a matrix of size N×K results in a matrix of size M×K.

matrix.js

Write and export as default a function that takes two matrices and returns the result of their multiplication.

Examples

import multiply from './matrix.js';

const matrixA = [[1, 2], [3, 2]];
const matrixB = [[3, 2], [1, 1]];

multiply(matrixA, matrixB);
// [[5, 4], [11, 8]]

const matrixC = [
  [2, 5],
  [6, 7],
  [1, 8],
];
const matrixD = [
  [1, 2, 1],
  [0, 1, 0],
];

multiply(matrixC, matrixD);
// [
//   [2, 9, 2],
//   [6, 19, 6],
//   [1, 10, 1],
// ]

Tips

For full access to the challenge you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests