JavaScript - Adding Two Matrices

In many branches of mathematics and computer science, including machine learning and graphics programming, matrices are essential. We'll look at utilizing JavaScript to combine two matrices in this blog post. We'll walk through each step, offer a basic implementation, and talk about some things to keep in mind when handling matrices in JavaScript.

What is Matrix Addition?

Let's take a moment to quickly study matrix addition before getting into the code. When two matrices are added:

The row and column sizes of the matrices must match.

The corresponding elements are added to each slot.

For example, if we have two 2x2 matrices:

A = [1 2]   B = [5 6]
    [3 4]       [7 8]

The result of A + B would be:

C = [1+5 2+6] = [6  8 ]
    [3+7 4+8]   [10 12]

 

Now, let's implement this in JavaScript:

function add_Mat(mat1, mat2) {

    // Check if matrices have the same dimensions

    if (mat1.length !== mat2.length || mat1[0].length !== mat2[0].length) {

        throw new Error("Matrices must have the same dimensions");

    }

       // Create a new matrix to store the result

    const res = [];

     // Iterate through each row

    for (let i = 0; i < mat1.length; i++) {

        const row = [];

        // Iterate through each column

        for (let j = 0; j < mat1[0].length; j++) {

            // Add corresponding elements

            row.push(mat1[i][j] + mat2[i][j]);

        }

        res.push(row);

    }

    return res;

}

// Example usage

const matA = [

    [1, 2],

    [3, 4]

];

const matB = [

    [5, 6],

    [7, 8]

];

const sum = add_Mat(matA, matB);

console.log(sum);

 

Breaking Down the Code

  1. Two matrices are the input for the function addMatrices, which we define.
  2. First, we determine whether the matrices are of the same size. If not, an error is thrown.
  3. To save the total, we generate a new matrix result.
  4. We run through each element in both matrices using nested loops.
  5. We add the matching elements to each slot and push the outcome into our newly created matrix.
  6. We finally give back the resultant matrix.