How to use Loops In Javascript

The sum of squares for the normal and the sum of diagonal elements for the trace are calculated iteratively using for loop via the matrix elements.

Example: To demonstrate the use of the function to computer the normal and trace of a given matrix using JavaScript’s nested loops.

Javascript




function calculateNormalAndTrace(matrix) {
    let normalSum = 0;
    let traceSum = 0;
   
    for (let i = 0; i < matrix.length; i++) {
      for (let j = 0; j < matrix[i].length; j++) {
        normalSum += Math.pow(matrix[i][j], 2);
        if (i === j) {
          traceSum += matrix[i][j];
        }
      }
    }
 
    const normal = Math.sqrt(normalSum);
   
    return { normal, trace: traceSum };
  }
  const matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ];
  const { normal, trace } = calculateNormalAndTrace(matrix);
  console.log("Normal:", normal);
  console.log("Trace:", trace);


Output

Normal: 16.881943016134134
Trace: 15

JavaScript Program to Find the Normal and Trace of a Matrix

JavaScript provides us with ways to find a square matrix’s normal and trace. In linear algebra, the total number of entries on the principal diagonal is indicated by the trace, while the normal represents the size of the matrix overall. It is critical to understand these concepts in a variety of computational and mathematical applications.

Similar Reads

Understanding the Concepts

Normal: The normal of a matrix represents its overall “magnitude” or size. It is calculated as the square root of the sum of the squares of each element in the matrix....

Using Loops

The sum of squares for the normal and the sum of diagonal elements for the trace are calculated iteratively using for loop via the matrix elements....

Using Array Methods

...