Mastering Matrix Operations in JavaScript​: A Simple Approach for Beginners

Mastering Matrix Operations in JavaScript: A Simple Approach for Beginners

Mastering Matrix Operations in JavaScript: A Simple Approach for Beginners

In this article, we’ll explore how to perform basic matrix operations (addition and subtraction) using JavaScript. If you're a beginner looking to understand how to handle multidimensional arrays (also known as matrices) in JavaScript, this guide will walk you through the process with a practical example.

What Are Matrices in Programming?

A matrix is a two-dimensional array, often used in mathematical computations, where values are stored in rows and columns. Each element in the matrix is identified by a pair of indices: the row and the column number.

In JavaScript, a matrix is simply an array of arrays. Here's an example of a simple 3x3 matrix:

let matrix = [
  [1, 2, 3],
 [4, 5, 6],
  [7, 8, 9]
];        

Our Goal: Matrix Operations (Sum & Subtraction)

In this example, we'll create a small web app that takes two 3x3 matrices as input from the user, then adds or subtracts them based on the user's choice. The result will be displayed in a new matrix format.

Let’s break down how we can implement this functionality step by step.

HTML Structure: Building the User Interface

We'll need an input form for the user to enter values for two matrices. We'll also need buttons to trigger the addition or subtraction operation, as well as a result section to display the output.

Here's a simple layout:

<div class="main">
  <form class="matrixInput" onsubmit="processMatrix(event); return false">
    <div>
      <label for="">Matrix 1</label>
      <input name="m1" type="number" id="m100">
      <input name="m1" type="number" id="m101">
      <input name="m1" type="number" id="m102">
      <input name="m1" type="number" id="m110">
      <input name="m1" type="number" id="m111">
      <input name="m1" type="number" id="m112">
      <input name="m1" type="number" id="m120">
      <input name="m1" type="number" id="m121">
      <input name="m1" type="number" id="m122">
    </div>
    <div>
      <label for="">Matrix 2</label>
      <input name="m2" type="number" id="m200">
      <input name="m2" type="number" id="m201">
      <input name="m2" type="number" id="m202">
      <input name="m2" type="number" id="m210">
      <input name="m2" type="number" id="m211">
      <input name="m2" type="number" id="m212">
      <input name="m2" type="number" id="m220">
      <input name="m2" type="number" id="m221">
      <input name="m2" type="number" id="m222">
    </div>
    <div>
      <button type="submit">Sum</button>
      <button type="submit">Subtract</button>
    </div>
  </form>

  <div class="result">
    <label for="">Result</label>
    <input name="mr" type="number" disabled id="r00">
    <input name="mr" type="number" disabled id="r01">
    <input name="mr" type="number" disabled id="r02">
    <input name="mr" type="number" disabled id="r10">
    <input name="mr" type="number" disabled id="r11">
    <input name="mr" type="number" disabled id="r12">
    <input name="mr" type="number" disabled id="r20">
    <input name="mr" type="number" disabled id="r21">
    <input name="mr" type="number" disabled id="r22">
  </div>
</div>        

JavaScript: Performing Matrix Operations

Now that we have the HTML structure in place, let’s dive into the JavaScript. The goal is to add or subtract the values of two matrices.

  1. Handling the Form Submit: When the user clicks either the Sum or Subtract button, the processMatrix function is triggered. Inside this function, we access the values of both matrices and perform the chosen operation.
  2. Looping through the Matrices: We'll use nested loops to access each cell in both matrices and then perform either addition or subtraction depending on which button was clicked. The result is then displayed in a third matrix.

Here’s the core of the JavaScript logic:


function processMatrix(e) {
  for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
      if (e.submitter.innerText.toLowerCase() === "sum") {
        document.querySelector(`#r${i}${j}`).value = 
          Number(document.querySelector(`#m1${i}${j}`).value) + 
          Number(document.querySelector(`#m2${i}${j}`).value);
      } else {
        document.querySelector(`#r${i}${j}`).value = 
          Number(document.querySelector(`#m1${i}${j}`).value) - 
          Number(document.querySelector(`#m2${i}${j}`).value);
      }
    }
  }
}
        

In this snippet: We’re using e.submitter.innerText.toLowerCase() to check which button was pressed. If it’s the Sum button, we add corresponding values from both matrices; if it’s the Subtract button, we subtract them. We then use document.querySelector to target each cell in the result matrix and display the calculated value.

Key Takeaways:

  • Matrix Operations Made Simple: Using basic loops and DOM manipulation, we've created a simple web app that performs matrix operations.
  • Dynamic Updates: The app dynamically updates the result based on user input, providing immediate feedback.
  • Practical Use: This approach can be extended to handle larger matrices, and the logic can be adapted to perform other operations like multiplication or even transpose.


Conclusion

Mastering matrix operations in JavaScript is a great way to enhance your understanding of arrays and loops. Whether you’re working with 3x3 matrices or larger datasets, this example can serve as a foundation for more complex mathematical applications.

Feel free to tweak the code to suit your needs, and don't hesitate to share any improvements you come up with in the comments. Happy coding! 😄

#JavaScript #WebDevelopment #MatrixOperations #Programming #Coding #ES6

To view or add a comment, sign in

More articles by Muhammad Abubakar_Dev

Insights from the community

Others also viewed

Explore topics