How to useLoop in JavaScript 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 addition of any of the number of matrices, and then we are performing the addition of the response element and saving the result of the addition in the result matrix.
Syntax:
for (statement 1; statement 2; statement 3) {
code here...
}
Example: In this example, we will be performing the Addition of two Matrices in JavaScript by using Loops.
Javascript
let mat1 = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], ]; let mat2 = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], ]; let resmat = []; for (let i = 0; i < mat1.length; i++) { let r = "" ; for (let j = 0; j < mat1[i].length; j++) { r += mat1[i][j] + mat2[i][j] + " " ; } resmat.push(r.trim()); } resmat.forEach(r => console.log(r)); |
2 2 2 2 4 4 4 4 6 6 6 6 8 8 8 8
JavaScript Program to Add Two Matrices
Given two N x M matrices. Find a N x M matrix as the sum of given matrices each value at the sum of values of corresponding elements of the given two matrices
In this article, we will see how we can perform the addition of two input matrices using JavaScript.
Example:
Table of Content
- Using Loop in JavaScript
- Using map method
- Using the Array.from() method