The Wayback Machine - https://web.archive.org/web/20240927184207/https://www.geeksforgeeks.org/java-program-to-find-the-normal-and-trace-of-a-matrix/
Open In App

Java Program to Find the Normal and Trace of a Matrix

Last Updated : 23 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

For a given 2D matrix, the purpose is to find the Trace and Normal of the matrix.

Normal of a matrix is defined as the square root of the sum of squares of all the elements of the matrix.

Trace of a given square matrix is defined as the sum of all the elements in the diagonal.

Examples :

Input : matrix[][] = {{1, 4, 4},
                     {2, 3, 7},
                     {0, 5, 1}};
Output : Normal = 11  
         Trace  = 5
Explanation :  
Normal = sqrt(1*1+ 4*4 + 4*4 + 2*2 +
             3*3 + 7*7 + 0*0 + 5*5 + 1*1)    
       = 11
Trace  = 1+3+1 = 5

Input :matrix[][] = {{8, 9, 11},
                    {0, 1, 15},
                    {4, 10, -7}};
Output : Normal = 25  
         Trace  = 2
Explanation :  
Normal = sqrt(8*8 +9*9 + 11*11 + 0*0 + 1*1 +  
            15*15 + 4*4 + 10*10 + -7*-7) = 25   
Trace  = (8+1-7) = 2

Lightbox

Example:

Java




// Java program to find the trace
// and normal of the given matrix
 
import java.io.*;
 
class geeksforgeeks {
 
    // Dimension of the given matrix
    static int max = 50;
 
    // Finds Normal of the given
    // matrix of size N x N
    static int Normal(int matrix[][], int N)
    {
        // Initializing sum
        int s = 0;
        for (int j = 0; j < N; j++)
            for (int k = 0; k < N; k++)
                s += matrix[j][k] * matrix[j][k];
        return (int)Math.sqrt(s);
    }
 
    // Finds trace of the given
    // matrix of size N x N
    static int Trace(int matrix[][], int N)
    {
        int s = 0;
        for (int j = 0; j < N; j++)
            s += matrix[j][j];
        return s;
    }
 
    // The Driver code
    public static void main(String[] args)
    {
 
        int matrix[][] = {
            { 2, 3, 5, 6, 7 },      { 8, 9, 10, 11, 12 },
            { 13, 14, 15, 16, 17 }, { 18, 1, 3, 0, 6 },
            { 7, 8, 11, 8, 11 },
        };
 
        System.out.println("Trace of the Matrix is: "
                           + Trace(matrix, 5));
        System.out.println("Normal of the Matrix is: "
                           + Normal(matrix, 5));
    }
}


Output

Trace of the Matrix is: 37
Normal of the Matrix is: 50

Time Complexity: O(N*N), as we are using nested loops for traversing the matrix.

Auxiliary Space: O(1), as we are not using any extra space.



Previous Article
Next Article

Similar Reads

Program to find Normal and Trace of a matrix
Given a 2D matrix, the task is to find Trace and Normal of matrix.Normal of a matrix is defined as square root of sum of squares of matrix elements.Trace of a n x n square matrix is sum of diagonal elements. Examples : Input : mat[][] = {{7, 8, 9}, {6, 1, 2}, {5, 4, 3}}; Output : Normal = 16 Trace = 11 Explanation : Normal = sqrt(7*7+ 8*8 + 9*9 + 6
6 min read
Java Program to Print Stack Trace
Consider a bookshelf in which books are placed one over another. Now if the person wants to read the book which he placed first, in order to do so all books over the first book are needed to be removed to reach out to the desired book. That is the book that was placed first at the beginning itself. The method by which the computer stores books know
3 min read
Java Program to Convert a Stack Trace to a String
Prerequisite knowledge of the following Java programming topics: Java StringJava Exception HandlingConvert Stack Trace to String In the program below, we've dropped an ArrayIndexOutOfBoundsException to our program by accessing an out-of-bounds element. The Java StringWriter class is a character stream that collects the output from the string buffer
2 min read
Standard Normal Distribution (SND) - Java Program
The standard normal distribution is a special case of the normal distribution. It occurs when a normal random variable has a mean of 0 and a standard deviation of 1. The normal random variable of a standard normal distribution is called a standard score or a z score. A conversion from Normally distributed to Standard Normally distributed value occu
2 min read
Find normal at a given point on the curve
Given a curve [ y = x(A - x) ], the task is to find normal at a given point ( x, y) on that curve, where A is an integer number and x, y also any integer. Examples: Input: A = 2, x = 2, y = 0 Output: 2y = x - 2 Since y = x(2 - x) y = 2x - x^2 differentiate it with respect to x dy/dx = 2 - 2x put x = 2, y = 0 in this equation dy/dx = 2 - 2* 2 = -2 e
6 min read
Find length of longest substring with at most K normal characters
Given a string P consisting of small English letters and a 26-digit bit string Q, where 1 represents the special character and 0 represents a normal character for the 26 English alphabets. The task is to find the length of the longest substring with at most K normal characters. Examples: Input : P = "normal", Q = "00000000000000000000000000", K=1 O
12 min read
Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
15+ min read
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix
Given a matrix B[][] of dimensions N * M, the task is to generate a matrix A[][] of same dimensions that can be formed such that for any element B[i][j] is equal to Bitwise OR of all elements in the ith row and jth column of A[][]. If no such matrix exists, print "Not Possible". Otherwise, print the matrix A[][]. Examples: Input: B[][] = {{1, 1, 1}
11 min read
Java Program to Determine if a given Matrix is a Sparse Matrix
A matrix is a collection of data elements arranged in a two-dimensional array-like structure, consisting of rows and columns. A matrix with a lot of zero values is called a sparse matrix. The program aims to count the number of zero values present in the matrix. If the number of zero values is more than half of the total number of elements in the m
3 min read
Java Program to Check Whether a Given Matrix is Lower Triangular Matrix or Not
In the lower triangular matrix, the elements that are present above the diagonal should be 0. Given a matrix and the task is to check the matrix is in lower triangular form or not. A matrix must be a square matrix. A square matrix is called lower triangular if all the entries above the main diagonal are zero. Example - Input: 1 0 0 1 2 0 1 2 3 Outp
2 min read
Time taken by Loop unrolling vs Normal loop
We have discussed loop unrolling. The idea is to increase performance by grouping loop statements so that there are less number of loop control instruction and loop test instructions C/C++ Code // CPP program to compare normal loops and // loops with unrolling technique #include <iostream> #include <time.h> using namespace std; int main
6 min read
Game Theory (Normal - form game) | Set 1 (Introduction)
Game theory is a mathematical model used for decision making. It has applications in all fields of social science, as well as in logic and computer science. Game theory has come to play an increasingly important role in logic and in computer science. To be fully defined, a game must specify the following elements: the players of the game, the infor
4 min read
Game Theory (Normal form game) | Set 2 (Game with Pure Strategy)
Game Theory (Normal – form game) | Set 1 (Introduction) Please go through the above article before proceeding. Given a payoff matrix. The task is to find the optimum strategies of the players. Solution: Player A is having 3 strategies - 1, 2 and 3, and player B is also having 3 strategies - 1, 2 and 3. Step 1: Find row minimum values for each row a
2 min read
Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)
Consider the following payoff matrix with respect to player A and solve it optimally. Solution: If a game has no saddle point then the game is said to have mixed strategy. Step 1: Find out the row minimum and column maximum. Step 2: Find out the minimax and maximin values. Since minimax and maximin value of this game are not equal, this game has no
4 min read
How to plot a normal distribution with Matplotlib in Python ?
Prerequisites: MatplotlibNumpyScipyStatistics Normal Distribution is a probability function used in statistics that tells about how the data values are distributed. It is the most important probability distribution function used in statistics because of its advantages in real case scenarios. For example, the height of the population, shoe size, IQ
2 min read
Multiple Linear Regression Model with Normal Equation
Prerequisite: NumPy Consider a data set, area (x1)rooms (x2)age (x3)price (y)2338656215274569244968972954756231768234253107485 let us consider, Here area, rooms, age are features / independent variables and price is the target / dependent variable. As we know the hypothesis for multiple linear regression is given by: [Tex]$h_{\theta}(x)=\theta_{0}
3 min read
Equation of a normal to a Circle from a given point
Given three integers a, b, c representing coefficients of the equation x2 + y2 + ax + by + c = 0 of a circle, the task is to find the equation of the normal to the circle from a given point (x1, y1).Note: Normal is a line perpendicular to the tangent at the point of contact between the tangent and the curve. Examples: Input: a = 4, b = 6, c = 5, x1
8 min read
Is Sentinel Linear Search better than normal Linear Search?
What is Sentinel Linear Search? Sentinel Linear search is a type of linear search where the element to be searched is placed in the last position and then all the indices are checked for the presence of the element without checking for the index out of bound case. The number of comparisons is reduced in this search as compared to a traditional line
9 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Game Theory (Normal-form Game) | Set 5 (Dominance Property-Mixed Strategy)
This article discusses how to solve a game by the dominance property with mixed strategy. Consider the below game: Solution: Find out the row minimum and column maximum values. Here Minimax value is not equal to Maximin so this game has no saddle point. Now proceed with dominance property to reduce the rows and the columns. Reducing the row and the
2 min read
Game Theory (Normal-form Game) | Set 7 (Graphical Method [M X 2] Game)
The payoff matrix of an M * 2 game consists of M rows and two columns. This article will discuss how to solve an M * 2 game by graphical method. Also, this article will discuss if more than two lines intersect the same point in the graph then how can a 2 * 2 payoff matrix be formed. Consider the below problem: Solution: First check whether the prob
3 min read
Game Theory (Normal-form Game) | Set 6 (Graphical Method [2 X N] Game)
The payoff matrix of a 2 * N game consists of 2 rows and N columns . This article will discuss how to solve a 2 * N game by graphical method. Consider the below 2 * 5 game: Solution: First check the saddle point of the game. This game has no saddle point. Step 1: Reduce the size of the payoff matrix by applying dominance property, if it exists. Thi
3 min read
POTD Solutions | 15 Oct' 23 | Normal BST to Balanced BST
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Binary Search Trees but will also help you build up problem-solving skills. POTD 15 October: Normal BST t
5 min read
Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)
In some of the games, it is possible to reduce the size of the payoff matrix by eliminating rows (or columns) that are dominated by other rows (or columns) respectively. Dominance property for rows: X ≤ Y i.e. if all the elements of a particular row X are less than or equal to the corresponding elements of another row Y then delete row X (row X is
4 min read
Length of the normal from origin on a straight line whose intercepts are given
Given the intercepts of a straight line on both the axes as m and n. The task is to find the length of the normal on this straight line from the origin.Examples:   Input: m = 5, n = 3 Output: 2.57248Input: m = 13, n = 9 Output: 7.39973     Approach: A normal to a line is a line segment drawn from a point perpendicular to the given line.   Let p be
3 min read
Program to check diagonal matrix and scalar matrix
Diagonal matrixA square matrix is said to be a diagonal matrix if the elements of the matrix except the main diagonal are zero. A square null matrix is also a diagonal matrix whose main diagonal elements are zero. Examples: Input: Mat[4][4] = {{4, 0, 0, 0}, {0, 5, 0, 0}, {0, 0, 2, 0}, {0, 0, 0, 1}}Output: YesInput:Mat[4][4] = {{6, 10, 12, 0}, {0, 5
10 min read
Find the original matrix from the given AND matrix
Given a binary matrix B[][] of size N*M, the task is to find a matrix A[][] of the same size such that B[i][j] is the bitwise AND of all the elements in ith row and jth column of A[][]. Examples: Input: B[][] = { {1, 0, 1}, {0, 0, 0} }Output: { {1, 1, 1}, {1, 0, 1} }Explanation:1 1 1 ? 1 0 11 0 1 0 0 0 Input: B[][] = { {0, 0}, {1, 1} }Output: -1 Ap
10 min read
Java Program to Find the Frequency of Odd & Even Numbers in the Matrix
Matrix is simply a two-dimensional array. Just like in one-dimensional traversal operation is required to figure out. The task is to find the frequencies of odd and even number in the given matrix. The size of matrix is defined as product of numbers of columns and rows. So, the size of the matrix is m × n Here in the matrix M = number of rows in th
3 min read
Java Program to Find Transpose of Matrix
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, the transpose of A[][] is obtained by changing A[i][j] to A[j][i]. Find Transpose of a Matrix in Java There are two shapes in Matrix to find transpose as mentioned below: Square MatrixRectangle Matrix1. Transpose of Square Matrix The below program fin
4 min read
Java Program to Find Laplacian Matrix of an Undirected Graph
The Laplacian matrix, also called the graph Laplacian, admittance matrix, Kirchhoff matrix or discrete Laplacian, is a matrix representation of a graph. To find the Laplacian matrix first, find adjacency matrix and degree matrix of a graph as the formula for the Laplacian matrix is as follows: Laplacian matrix = Degree matrix - Adjacency matrix Exa
4 min read
Article Tags :
Practice Tags :