Open In App

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.

Understanding the Concepts

Table of Content



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.

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






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

Using Array Methods

Using JavaScript’s built-in array operations, such as map and reduce, this method efficiently calculates a matrix’s normal and trace. It gives a straightforward solution by utilizing the concepts of functional programming, improving maintainability and performance—especially for larger matrices.

Example: This code snippet shows the use of array methods by showing how to effectively compute the normal and trace of a matrix in JavaScript using the `reduce` and `map` functions, improving readability and efficiency.




function calculateNormalAndTrace(matrix) {
    const normalSum = matrix.flat().reduce((acc, value) => {
        return acc + Math.pow(value, 2), 0
    });
    const traceSum = matrix.map((row, i) => row[i])
        .reduce((acc, value) => acc + value, 0);
    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: 0
Trace: 15

Article Tags :