Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Program to check if matrix is lower triangular
Next article icon

JavaScript Program to Find the Normal and Trace of a Matrix

Last Updated : 15 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  • 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.
  • Trace: In a square matrix, the trace is the sum of the elements on the main diagonal. It provides insights into the matrix's "linearity."

Table of Content

  • Using Loops
  • Using Array Methods

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.

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 

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.

JavaScript
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 

Next Article
JavaScript Program to check if matrix is lower triangular

H

heysaiyad
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Program

Similar Reads

  • JavaScript Program to Find the Rank of a Matrix
    Given a matrix of size M x N, your task is to find the rank of a matrix using JavaScript. Example: Input: mat[][] = [[10, 20, 10], [20, 40, 20], [30, 50, 0]]Output: Rank is 2Explanation: Ist and 2nd rows are linearly dependent. But Ist and 3rd or 2nd and 3rd are independent. Input: mat[][] = [[10, 2
    5 min read
  • 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 ContentUsing Loop in JavaScriptUsing the map method in Jav
    5 min read
  • Javascript Program to check if matrix is upper triangular
    Given a square matrix and the task is to check the matrix is in upper triangular form or not. A square matrix is called upper triangular if all the entries below the main diagonal are zero. Examples: Input : mat[4][4] = {{1, 3, 5, 3}, {0, 4, 6, 2}, {0, 0, 2, 5}, {0, 0, 0, 6}};Output : Matrix is in U
    2 min read
  • JavaScript Program to check if matrix is lower triangular
    Given a square matrix and the task is to check the matrix is in lower triangular form or not. A square matrix is called lower triangular if all the entries above the main diagonal are zero. Examples: Input : mat[4][4] = {{1, 0, 0, 0}, {1, 4, 0, 0}, {4, 6, 2, 0}, {0, 4, 7, 6}};Output : Matrix is in l
    2 min read
  • JavaScript Program to Print all Palindromic Paths from Top Left to Bottom Right in a Matrix
    We are given a matrix containing only lower-case alphabetical characters. The task is to print all the palindromic paths present in the given matrix. A path is a sequence of cells starting from the top-left cell and ending at the bottom-right cell. We are allowed to move only to the right and down f
    4 min read
  • Javascript Program for Markov matrix
    Given a m x n 2D matrix, check if it is a Markov Matrix. Markov Matrix : The matrix in which the sum of each row is equal to 1. Examples: Input :1 0 00.5 0 0.50 0 1Output : yesExplanation :Sum of each row results to 1, therefore it is a Markov Matrix.Input :1 0 00 0 21 0 0Output :noApproach: Initial
    2 min read
  • C Program To Find Normal and Trace of Matrix
    Here, we will see how to write a C program to find the normal and trace of a matrix. Below are the examples: Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};Output: Normal = 16Trace = 15 Explanation: Normal = sqrt(1*1+ 2*2 + 3*3 + 4*4 + 5*5 + 6*6 + 7*7 + 8*8 + 9*9) = 16Trace = 1+5+9 = 15 Input: m
    2 min read
  • Javascript Program to check if a matrix is symmetric
    A square matrix is said to be symmetric matrix if the transpose of the matrix is same as the given matrix. Symmetric matrix can be obtain by changing row to column and column to row. Examples: Input : 1 2 3 2 1 4 3 4 3 Output : Yes Input : 3 5 8 3 4 7 8 5 3 Output : NoA Simple solution is to do foll
    2 min read
  • Javascript Program to Print matrix in snake pattern
    Given n x n matrix In the given matrix, you have to print the elements of the matrix in the snake pattern. Examples: Input :mat[][] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}}; Output : 10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32 Input :mat[][] = { {1, 2, 3}, {4,
    2 min read
  • JavaScript Program to Print Given Matrix in Spiral Form
    Write a JavaScript program to print a given 2D matrix in spiral form. You are given a two-dimensional matrix of integers. Write a program to traverse the matrix starting from the top-left corner which moves right, bottom, left, and up in a spiral pattern until all the elements are visited. Let us un
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences