How to use the Array.from() method In Javascript
In this approach, we are using the Array.from() method in JavaScript. By using this function, we create a new matrix by iterating over each row and column of all the input matrices.
Syntax:
Array.from(object, mapFunction, thisValue)
Example: In this example, we will be performing the subtraction of matrices in JavaScript by using Array.from().
Javascript
function subtractMatricesUsingFrom( inputMat) { if (inputMat.length < 2) { // Checking length of matrix return null ; } let resultMatrix = inputMat[0]; for ( let i = 1; i < inputMat.length; i++) { let currMat = inputMat[i]; // Checking the dimensions here if ( resultMatrix.length !== currMat.length || resultMatrix[0].length !== currMat[0].length) { console.log( "Not Possible" ); return null ; } // Using from METHOD to iterate // over each row and column resultMatrix = Array.from( { length: resultMatrix.length, }, (_, i) => Array.from( { length: resultMatrix[i].length, }, (_, j) => resultMatrix[i][j] - currMat[i][j] )); } return resultMatrix; } // All the input is defined here. // multiple matrices let inputMatrix1 = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], ]; let inputMatrix2 = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], ]; let inputMatrix3 = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], ]; // Result is stored in this varibale let resultMatrix = subtractMatricesUsingFrom([ inputMatrix1, inputMatrix2, inputMatrix3, ]); // Printing the results resultMatrix.forEach((row) => { console.log(row.join( " " )); }); |
Output
-1 -1 -1 -1 -2 -2 -2 -2 -3 -3 -3 -3 -4 -4 -4 -4
JavaScript Program for Subtraction of Matrices
Subtraction of two matrices is a basic mathematical operation that is used to find the difference between the two matrices. In this article, we will see how we can perform the subtraction of input matrices using JavaScript.
Example:
Table of Content
- Using Loop in JavaScript
- Using the map method in JavaScript
- Using the Array.from() method