Objective

Implement two functions in JavaScript to return the sum and product of two given matrices.

Difficulty

Easy

Description

A matrix is a rectangular block of nubmers comprised of rows and columns. A matrix with ::m:: rows and ::n:: columns is said to be an ::m \times n:: matrix.

Shown below are a couple of matrices, along with their dimensions:

::\begin{bmatrix} 1 & 5 \\ 10 & -2 \end{bmatrix}::
::2 \times 2::
::\begin{bmatrix} 1 & 3 \\ 0 & 0 \\ 6 & 15 \end{bmatrix}::
::3 \times 2::
::\begin{bmatrix} 1 & 9 & 0 & -8 & 10 & 0 \end{bmatrix}::
::1 \times 6::

In JavaScript, a matrix can be represented using a 2D array as follows:

var matrix = [
   [1, 5],
   [10, -2]
];

matrix = [
   [1, 3],
   [0, 0],
   [6, 15]
];

matrix = [
   [1, 9, 0, -8, 10, 0]
];

Each row is represented as an array in the main array. In this inner array, each element represents an entry of the given row.

Matrices can be added, subtracted, and multiplied together.

The addition is represented as ::\text{A} + \text{B}:: and is defined if and only if ::\text{A}:: is ::m \times n:: and ::\text{B}:: is also ::m \times n::. The addition is computed by adding corresponding items in ::\text{A}:: and ::\text{B}:: together.

Following is an illustration:

::\begin{bmatrix} 1 & 3 \\ 0 & 0 \end{bmatrix} + \begin{bmatrix} 5 & -3 \\ 6 & 10 \end{bmatrix} = \begin{bmatrix} 1 + 5 & 3 + (-3) \\ 0 + 6 & 0 + 10 \end{bmatrix} = \begin{bmatrix} 6 & 0 \\ 6 & 10 \end{bmatrix}::

The case for multiplication is quite different.

The multiplication of ::\text{A}:: and ::\text{B}:: is denoted as ::\text{AB}::, and is defined if the number of columns of ::\text{A}:: is the same as the number of rows of ::\text{B}::. In other terms, ::\text{AB}:: is defined if and only if ::\text{A}:: is ::m \times n:: and ::\text{B}:: is ::n \times p::.

It is computed as follows. The ::(i, j)^{th}:: element of ::\text{AB}:: is computed by multiplying corresponding elements in the ::i^{th}:: row of ::\text{A}:: and the ::j^{th}:: column of ::\text{B}:: and then adding them together.

An example is shown below:

::\begin{bmatrix} 1 & 2 \end{bmatrix} \times \begin{bmatrix} 0 & 3 \\ 1 & 5 \end{bmatrix} = \begin{bmatrix} (1 \times 0 + 2 \times 1) & (1 \times 3 + 2 \times 5) \end{bmatrix}::

In this exercise, you have to create two functions multiply and add() that work as follows:

  1. add() takes in two matrices a and b as argument and returns their sum.
  2. multiply() takes in two matrices a and b as argument and returns their product.