JavaScript Matrix

In this article, we will explore the concept of matrices in JavaScript. To begin, let's gain a better understanding of arrays and matrices.

While many of us are familiar with the process of creating a single-dimensional array, fewer individuals understand how to establish a 2-dimensional array. In this article, we will explore the method for constructing a 2-dimensional array in JavaScript.

Array

An array is a data structure that is capable of storing multiple values of the same data type. Arrays can exist in various dimensions, including one-dimensional, two-dimensional, three-dimensional, and beyond.

Example:

Example

cricketers = [Sachin Tendulkar,Virat Kohli,MS Dhoni ]

The array referred to as "cricketers" is a one-dimensional array comprising solely the names of cricketers. This indicates that an array is capable of storing values of a uniform data type.

Constructing an array in JavaScript:

In JavaScript, an array can be constructed by using an array literal.

Syntax:

Example

var arrayName = [element1,element2,element3,...]

In the syntax presented above, the keyword "var" is employed to define an array that can be initialized at any point in time. The term "arrayName" refers to the identifier for the array. The elements element1, element2, and element3 are all of the same type and are contained within the array.

Matrix

A matrix is defined as a two-dimensional arrangement organized into rows and columns. It resembles a grid or table format that includes multiple rows and columns.

Dimensions of matrix

Below are examples that illustrate the dimensions of a matrix:

Example-1:

Example

A = [5 2 ]

The matrix presented above consists of a single row and two columns, indicating that its dimensions are (1 x 2).

Example-2:

The matrix presented above consists of two rows and three columns, indicating that it possesses a dimension of (2 x 3).

Matrix in JavaScript

In JavaScript, a matrix is often referred to as an array of arrays or a multidimensional array.

Operations of Matrix

To begin, let us examine the subsequent matrix, which will serve as the basis for all operations we are about to conduct.

Example

var A = [[9, 1, 5], [3, 2, 5], [4, 8, 6]];
var B = matrix(A);

The subsequent actions executed by the matrix include:

  1. Row:

It is utilized to return the row.

B(0);

It returns [9, 1, 5].

  1. Column:

It is utilized to return the column.

B(, 0);

The output is [[9], [3], [4]].

  1. Identity:

The output generated is [[9, 1, 5], [3, 2, 5], [4, 8, 6]].

  1. Range:

B([1,2]);

The output is [[3, 2, 5], [4, 8, 6]].

  1. Set:

B.set(0).to(0);

It yields [[0, 0, 0], [3, 2, 5], [4, 8, 6]].

  1. Size:

It is utilized to find the size of the matrix.

B.size;

It returns [3, 3].

  1. Addition:

It is utilized to add two matrices.

B.add(C);

It performs the addition of matrix B to matrix C.

  1. Subtraction:

This operation is employed to deduct one matrix from another.

C.sub(B);

It removes matrix B from matrix C.

  1. Multiplication:

It is utilized to multiply two matrices.

B.mul(C);

It performs the multiplication of matrices B and C.

  1. Division:

It is utilized to divide one matrix by another.

B.div(C);

It performs the division of matrix B by matrix C.

  1. Product:

It is employed to determine the result of multiplying two matrices.

B.prod(C);

It yields the result of multiplying matrix B by matrix C.

  1. Transpose:

It is utilized to find the transpose of a matrix.

B.trans;

It performs the transposition operation on the matrix B.

  1. Inverse:

It is utilized to inverse a matrix.

C.inv;

It computes the inverse of the matrix C.

  1. Determinant:

It is employed for the purpose of determining the determinant of a matrix.

B.det;

It provides the determinant of matrix B.

  1. Merge:

Two matrices have the capability to be combined in four distinct orientations: top, bottom, left, and right.

Top direction:

Example

A = matrix([2, 4, 6, 8]);
A.merge.top([1, 3, 5, 7]);

It merges the matrix in the top direction.

Bottom direction:

Example

A = matrix([2, 4, 6, 8]);
A.merge.bottom([1, 3, 5, 7]);

It merges the matrix in the bottom direction.

Left direction:

Example

A = matrix([[2, 4], [6, 8]]);
A.merge.left([1, 3], [5, 7]);

It merges the matrix in the left direction.

Right direction:

Example

A = matrix([[2, 4], [6, 8]]);
A.merge.right([1, 3], [5, 7]);

It combines the matrix towards the appropriate direction.

  1. Equals:

It is employed to determine if the two matrices are identical or not.

Example

A.equals(B);

Demonstrations of JavaScript Matrix

Let's explore examples of various matrix operations implemented in JavaScript.

Demonstration-1:

We will develop a program to compute the sum of matrix A and matrix B.

Code:

Example

let A = [ 
	[2, 2, 2, 2], 
	[2, 2, 2, 2], 
	[2, 2, 2, 2], 
	[2, 2, 2, 2], 
]; 

let B = [ 
	[7, 7, 7, 7], 
	[6, 6, 6, 6], 
	[2, 2, 2, 2], 
	[1, 1, 1, 1], 
]; 
let result = []; 
for (let i = 0; i < A.length; i++) { 
	let r = ""; 
	for (let j = 0; j < A[i].length; j++) { 
		r += A[i][j] + B[i][j] + " "; 
	} 
	result.push(r.trim()); 
} 
result.forEach(r => console.log(r));

Output:

We can observe a resultant matrix that is formed by the addition of matrix A and matrix B.

Demonstration-2:

We are going to develop a program that will perform the operation of subtracting matrix B from matrix A.

Code:

Example

function subtract(A, B) {
  const outcome = [];

  for (let i = 0; i < A.length; ++i) {
    const row = [];

    for (let j = 0; j < A[i].length; ++j) {
      row.push(A[i][j] - B[i][j]);
    }

    outcome.push(row);
  }

  return outcome;
}


function display(matrix) {
  for (let i = 0; i < matrix.length; ++i) {
    console.log(matrix[i].join('\t'));
  }
}


const A = [
  [4, 2, 1],
  [8, 2, 3],
  [5, 7, 8]
];

const B = [
  [2, 5, 1],
  [8, 7, 6],
  [2, 1, 9]
];


const outcome = subtract(A, B);


console.log("A:");
display(A);

console.log("\nB:");
display(B);

console.log("\nResultant Matrix (A - B):");
display(outcome);

Output:

We can observe a resulting matrix that is obtained by subtracting matrix B from matrix A.

Demonstration-3:

We are going to develop a program that performs the multiplication of matrix A with matrix B.

Code:

Example

function multiplyMatrices(matrixA, matrixB) {
  const result = [];

  const m = matrixA.length;
  const n = matrixA[0].length;
  const p = matrixB[0].length;

  for (let i = 0; i < m; ++i) {
    result[i] = Array(p).fill(0);
  }

  for (let i = 0; i < m; ++i) {
    for (let j = 0; j < p; ++j) {
      for (let k = 0; k < n; ++k) {
        result[i][j] += matrixA[i][k] * matrixB[k][j];
      }
    }
  }

  return result;
}

function displayMatrix(matrix) {
  for (let i = 0; i < matrix.length; ++i) {
    console.log(matrix[i].join('\t'));
  }
}
const matrixA = [
  [4, 1, 1],
  [2, 3, 5],
  [5, 6, 2]
];

const matrixB = [
  [5, 4, 1],
  [0, 7, 9],
  [6, 1, 0]
];

const resultantMatrix = multiplyMatrices(matrixA, matrixB);

console.log("First Matrix:");
displayMatrix(matrixA);

console.log("\nSecond Matrix:");
displayMatrix(matrixB);

console.log("\nResultant Matrix:");
displayMatrix(resultantMatrix);

Output:

In this result, we observe a resultant matrix that is formed by multiplying matrix A with matrix B.

Demonstration-4:

We will develop a JavaScript application aimed at performing the division of matrix C by matrix D.

Code:

Example

function divide(matrix) {
  for (let i = 0; i < matrix.length; ++i) {
    console.log(matrix[i].map(num => num.toFixed(2)).join("\t"));
  }
}

function matrixDivision(C, D) {
  const outcome = [];

  for (let i = 0; i < C.length; ++i) {
    outcome[i] = [];
    for (let j = 0; j < C[i].length; ++j) {
      outcome[i][j] = C[i][j] / D[i][j];
    }
  }


  console.log("Result of matrix division:");
  divide(outcome);
}


const C = [
  [10.0, 20.0],
  [25.0, 2.0]
];
const D = [
  [5.0, 4.0],
  [2.0, 1.0]
];

matrixDivision(C, D);

Output:

Below is the result that allows us to observe the resultant matrix derived from the division of matrix C by matrix D.

Conclusion:

In this article, we have explored the concept of the JavaScript Matrix. A matrix can be defined as a two-dimensional array organized into rows and columns. Numerous operations can be executed on matrices, and we have examined several of these operations, enhanced by practical demonstrations.

Input Required

This code uses input(). Please provide values below: