How to use Loop In Javascript
In this approach, we are using for loops to iterate over every individual element of the input matrices. This approach can perform the subtraction of any of the number of matrices, and then we are performing the subtraction of the response element and saving the result of the subtraction in the result matrix.
Syntax:
for (statement 1 ; statement 2 ; statement 3){
code here...
}
Example: In this example, we will be performing the Subtraction of Matrices in JavaScript by using Loops.
Javascript
function MatSubUSingForLoop(inputMat) { if (inputMat.length < 2) { // We are checking if length of // matrices are less than 2, as // We need atleat 2 matrices to // Perform substraction return null ; } let outputMat = inputMat[0]; // Loop fr Substraction of Matrices for ( let i = 1; i < inputMat.length; i++) { let currMat = inputMat[i]; if ( outputMat.length !== currMat.length || outputMat[0].length !== currMat[0].length) { console.log( "Not Possible" ); return -1; } for ( let j = 0; j < outputMat.length; j++) { for ( let k = 0; k < outputMat[j].length; k++) { outputMat[j][k] -= currMat[j][k]; }}} return outputMat; } // Multiple Matrix Inputs let inputMatrix1 = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5], ]; 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], ]; // Output Matrix let resultMatrix = MatSubUSingForLoop([ inputMatrix1, inputMatrix2, inputMatrix3, ]); // Printing the result Matrix for ( let i = 0; i < resultMatrix.length; i++) { console.log( resultMatrix[i].join( " " )); } |
Not Possible
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