Skip to main content

Find out normal and trace in square matrix

The problem involves finding the normal and trace of a square matrix. In linear algebra, the normal of a matrix corresponds to its Frobenius norm, which is the square root of the sum of the squared absolute values of all its elements. The trace of a matrix is the sum of its diagonal elements.

Example

Consider the following 3x3 matrix:

1  2  3
4  5  6
7  8  3

The normal (Frobenius norm) of this matrix is calculated as the square root of the sum of the squared absolute values of all its elements:

normal = sqrt(1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + 7^2 + 8^2 + 3^2)
	= sqrt(213)
	≈ 14.594519519326 int(14)

The trace of this matrix is the sum of its diagonal elements:

trace = 1 + 5 + 3
          = 9

Idea to Solve the Problem

To find the normal, iterate through the matrix, calculate the sum of the squared absolute values of its elements, and then take the square root of that sum.

To find the trace, sum up the diagonal elements of the matrix.

Algorithm

  1. Initialize variables normal and trace to 0.
  2. Loop through the matrix:
    • For each element (i, j), add matrix[i][j]^2 to normal.
    • If i == j, add matrix[i][j] to trace.
  3. Calculate the square root of normal to get the normal of the matrix.
  4. Output the calculated normal and trace.

Pseudocode

find_normal_trace(matrix):
    normal = 0
    trace = 0
    for i from 0 to SIZE:
        for j from 0 to SIZE:
            normal += matrix[i][j]^2
            if i is equal to j:
                trace += matrix[i][j]
    normal = sqrt(normal)
    output "Normal: ", normal
    output "Trace: ", trace

main:
    matrix = ...  // Define the matrix
    find_normal_trace(matrix)

Code Solution

/*
  C Program 
+ Find normal and trace of a matrix
*/
#include <stdio.h>
#include <math.h>
#define SIZE 3



void find_normal_trace(int matrix[][SIZE])
{
  if(SIZE <=0 )
  {
    return;
  }
  
  int normal = 0;
  //Calculate Normal
  for (int i = 0; i < SIZE; ++i)
  {
    for (int j = 0; j < SIZE; ++j)
    {
      normal += matrix[i][j] * matrix[i][j];
    }
  }

  printf("  Normal : %d\n",(int)sqrt(normal) );


  //Calculate Trace
  //This is sum of diagonal elements
  int trace = matrix[0][0];


  for (int i = 1; i < SIZE; ++i)
  {
    for (int j = 0; j < SIZE; ++j)
    {
      if(i == j )
      {
        //Calculate sum of diagonal elements
        trace += matrix[i][j];
      }
      
      
    }
  }
  
  printf("  Trace : %d\n",trace );
}
void show_data(int matrix[][SIZE])
{
  for (int i = 0; i < SIZE; ++i)
  {
    for (int j = 0; j < SIZE; ++j)
    {
      printf("%3d",matrix[i][j] );
    }
    printf("\n");
  }
  printf("\n");
}
int main(){

  int matrix[][SIZE] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 3}
  }; 
  show_data(matrix);
  find_normal_trace(matrix);



  return 0;
}

Output

  1  2  3
  4  5  6
  7  8  3

  Normal : 14
  Trace : 9
/*
  C++ Program
  Find normal and trace of a matrix
*/
#include<iostream>
#include <math.h>
#define SIZE 3
using namespace std;

class MyMatrix {
	public:
		int size;
	MyMatrix() {
		//Get matrix size
		//Assume that given matrix size is NXN 
		this->size = SIZE;
	}
	void find_normal_trace(int matrix[][SIZE]) {
		if (this->size <= 0) {
			return;
		}
		int normal = 0;
		//Calculate Normal

		for (int i = 0; i < this->size; ++i) {
			for (int j = 0; j < this->size; ++j) {
				normal += matrix[i][j] *matrix[i][j];
			}
		}
		cout << " Normal : " << (int) sqrt(normal) << "\n";
		//Calculate Trace
		//This is sum of diagonal elements
		int trace = matrix[0][0];
		for (int i = 1; i < this->size; ++i) {
			for (int j = 0; j < this->size; ++j) {
				if (i == j) {
					//Calculate sum of diagonal elements
					trace += matrix[i][j];
				}
			}
		}
		cout << " Trace : " << trace << "\n";
	}
	void show_data(int matrix[][SIZE]) {
		for (int i = 0; i < this->size; ++i) {
			for (int j = 0; j < this->size; ++j) {
				cout << " " << matrix[i][j];
			}
			cout << "\n";
		}
		cout << "\n";
	}
};
int main() {
	int matrix[][SIZE] = {
		{
			1,
			2,
			3
		},
		{
			4,
			5,
			6
		},
		{
			7,
			8,
			3
		}
	};
	MyMatrix obj;
	obj.show_data(matrix);
	obj.find_normal_trace(matrix);
	return 0;
}

Output

 1 2 3
 4 5 6
 7 8 3

 Normal : 14
 Trace : 9
/*
  Java Program
  Find normal and trace of a matrix
*/
public class MyMatrix {

  public int size;

  public MyMatrix(int [][]matrix)
  {
    //Get matrix size
    //Assume that given matrix size is NXN 
    this.size = matrix.length;
  }

  public void find_normal_trace(int [][]matrix)
  {
    if(this.size <=0 )
    {
      return;
    }
    
    int normal = 0;
    //Calculate Normal
    for (int i = 0; i < this.size; ++i)
    {
      for (int j = 0; j < this.size; ++j)
      {
        normal += matrix[i][j] * matrix[i][j];
      }
    }

    System.out.print(" Normal : "+(int)Math.sqrt(normal)+"\n" );


    //Calculate Trace
    //This is sum of diagonal elements
    int trace = matrix[0][0];


    for (int i = 1; i < this.size; ++i)
    {
      for (int j = 0; j < this.size; ++j)
      {
        if(i == j )
        {
          //Calculate sum of diagonal elements
          trace += matrix[i][j];
        }
        
        
      }
    }
    
    System.out.print(" Trace :  "+trace+"\n" );
  }
  public void show_data(int [][]matrix)
  {
    for (int i = 0; i < this.size; ++i)
    {
      for (int j = 0; j < this.size; ++j)
      {
        System.out.print("  "+matrix[i][j] );
      }
      System.out.print("\n");
    }
    System.out.print("\n");
  }
  public static void main(String[] args) 
  {
    //Define matrix element
    int [][]matrix =
    {
      {1, 2, 3},
      {4, 5, 6},
      {7, 8, 3}
    }; 
    MyMatrix obj = new MyMatrix(matrix);

    obj.show_data(matrix);
    obj.find_normal_trace(matrix);
  }
}

Output

 1 2 3
 4 5 6
 7 8 3

 Normal : 14
 Trace : 9
/*
  C# Program
  Find normal and trace of a matrix
*/
using System;
public class MyMatrix {
	int size;
	MyMatrix(int[,] matrix) {
		//Get matrix size
		//Assume that given matrix size is NXN 
		this.size = matrix.GetLength(0);
	}
	public void find_normal_trace(int[,] matrix) {
		if (this.size <= 0) {
			return;
		}
		int normal = 0;
		//Calculate Normal

		for (int i = 0; i < this.size; ++i) {
			for (int j = 0; j < this.size; ++j) {
				normal += matrix[i,j] * matrix[i,j];
			}
		}
		Console.Write(" Normal : " + (int) Math.Sqrt(normal) + "\n");
		//Calculate Trace
		//This is sum of diagonal elements
		int trace = matrix[0,0];
		for (int i = 1; i < this.size; ++i) {
			for (int j = 0; j < this.size; ++j) {
				if (i == j) {
					//Calculate sum of diagonal elements
					trace += matrix[i,j];
				}
			}
		}
		Console.Write(" Trace : " + trace + "\n");
	}
	public void show_data(int[,] matrix) {
		for (int i = 0; i < this.size; ++i) {
			for (int j = 0; j < this.size; ++j) {
				Console.Write(" " + matrix[i,j]);
			}
			Console.Write("\n");
		}
		Console.Write("\n");
	}
	public static void Main(String[] args) {
		int[,]
		//Define matrix element
		matrix = {
			{
				1,
				2,
				3
			},
			{
				4,
				5,
				6
			},
			{
				7,
				8,
				3
			}
		};
		MyMatrix obj = new MyMatrix(matrix);
		obj.show_data(matrix);
		obj.find_normal_trace(matrix);
	}
}

Output

 1 2 3
 4 5 6
 7 8 3

 Normal : 14
 Trace : 9
<?php
/*
  Php Program
  Find normal and trace of a matrix
*/
class MyMatrix {
	public $size;

	function __construct($matrix) {
		//Get matrix size
		//Assume that given matrix size is NXN 
		$this->size = count($matrix);
	}
	public 	function find_normal_trace($matrix) {
		if ($this->size <= 0) {
			return;
		}
		$normal = 0;
		//Calculate Normal

		for ($i = 0; $i < $this->size; ++$i) {
			for ($j = 0; $j < $this->size; ++$j) {
				$normal += $matrix[$i][$j] *$matrix[$i][$j];
			}
		}
		echo(" Normal : ". intval(sqrt($normal)) ."\n");
		//Calculate Trace
		//This is sum of diagonal elements
		$trace = $matrix[0][0];
		for ($i = 1; $i < $this->size; ++$i) {
			for ($j = 0; $j < $this->size; ++$j) {
				if ($i == $j) {
					//Calculate sum of diagonal elements
					$trace += $matrix[$i][$j];
				}
			}
		}
		echo(" Trace : ". $trace ."\n");
	}
	public 	function show_data($matrix) {
		for ($i = 0; $i < $this->size; ++$i) {
			for ($j = 0; $j < $this->size; ++$j) {
				echo(" ". $matrix[$i][$j]);
			}
			echo("\n");
		}
		echo("\n");
	}
}

function main() {
	//Define matrix element
	$matrix = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 3));
	$obj = new MyMatrix($matrix);
	$obj->show_data($matrix);
	$obj->find_normal_trace($matrix);

}
main();

Output

 1 2 3
 4 5 6
 7 8 3

 Normal : 14
 Trace : 9
/*
  Node Js Program
  Find normal and trace of a matrix
*/
class MyMatrix {
	;
	constructor(matrix) {
		//Get matrix size
		//Assume that given matrix size is NXN 
		this.size = matrix.length;
	}
	find_normal_trace(matrix) {
		if (this.size <= 0) {
			return;
		}
		var normal = 0;
		//Calculate Normal

		for (var i = 0; i < this.size; ++i) {
			for (var j = 0; j < this.size; ++j) {
				normal += matrix[i][j] *matrix[i][j];
			}
		}

		process.stdout.write(" Normal : " + parseInt(Math.sqrt(normal)) + "\n");
		//Calculate Trace
		//This is sum of diagonal elements
		var trace = matrix[0][0];
		for (var i = 1; i < this.size; ++i) {
			for (var j = 0; j < this.size; ++j) {
				if (i == j) {
					//Calculate sum of diagonal elements
					trace += matrix[i][j];
				}
			}
		}

		process.stdout.write(" Trace : " + trace + "\n");
	}
	show_data(matrix) {
		for (var i = 0; i < this.size; ++i) {
			for (var j = 0; j < this.size; ++j) {
				process.stdout.write(" " + matrix[i][j]);
			}

			process.stdout.write("\n");
		}

		process.stdout.write("\n");
	}
}

function main(args) {
	//Define matrix element
	var matrix = [
		[1, 2, 3],
		[4, 5, 6],
		[7, 8, 3]
	];
	var obj = new MyMatrix(matrix);
	obj.show_data(matrix);
	obj.find_normal_trace(matrix);
}

main();

Output

 1 2 3
 4 5 6
 7 8 3

 Normal : 14
 Trace : 9
#  Python 3 Program
#  Find normal and trace of a matrix
import math
class MyMatrix :
	
	def __init__(self, matrix) :
		# Get matrix size
		# Assume that given matrix size is NXN 
		self.size = len(matrix)
	
	def find_normal_trace(self, matrix) :
		if (self.size <= 0) :
			return
		
		normal = 0
		# Calculate Normal
		i = 0
		while (i < self.size) :
			j = 0
			while (j < self.size) :
				normal += matrix[i][j] * matrix[i][j]
				j += 1
			
			i += 1
		
		print(" Normal : ", int(math.sqrt(normal)) ,"\n", end = "")
		trace = matrix[0][0]
		i = 1
		while (i < self.size) :
			j = 0
			while (j < self.size) :
				if (i == j) :
					# Calculate sum of diagonal elements
					trace += matrix[i][j]
				
				j += 1
			
			i += 1
		
		print(" Trace : ", trace ,"\n", end = "")
	
	def show_data(self, matrix) :
		i = 0
		while (i < self.size) :
			j = 0
			while (j < self.size) :
				print(" ", matrix[i][j], end = "")
				j += 1
			
			print("\n", end = "")
			i += 1
		
		print("\n", end = "")
	

def main() :
	matrix = [
		[1, 2, 3],
		[4, 5, 6],
		[7, 8, 3]
	]
	obj = MyMatrix(matrix)
	obj.show_data(matrix)
	obj.find_normal_trace(matrix)


if __name__ == "__main__":
	main()

Output

  1  2  3
  4  5  6
  7  8  3

 Normal :  14
 Trace :  9
# Ruby Program
# Find normal and trace of a matrix
class MyMatrix 
	# Define the accessor and reader of class MyMatrix
	attr_reader :size
	attr_accessor :size
	def initialize(matrix) 
		# Get matrix size
		# Assume that given matrix size is NXN 
		self.size = matrix.length
	end
	def find_normal_trace(matrix) 
		if (self.size <= 0) 
			return
		end
		normal = 0
		# Calculate Normal
		i = 0
		while (i < self.size) 
			j = 0
			while (j < self.size) 
				normal += matrix[i][j] * matrix[i][j]
				j += 1
			end
			i += 1
		end
		print(" Normal  :", (Math.sqrt(normal)).to_i ,"\n")
		trace = matrix[0][0]
		i = 1
		while (i < self.size) 
			j = 0
			while (j < self.size) 
				if (i == j) 
					# Calculate sum of diagonal elements
					trace += matrix[i][j]
				end
				j += 1
			end
			i += 1
		end
		print(" Trace  :", trace ,"\n")
	end
	def show_data(matrix) 
		i = 0
		while (i < self.size) 
			j = 0
			while (j < self.size) 
				print(" ", matrix[i][j])
				j += 1
			end
			print("\n")
			i += 1
		end
		print("\n")
	end
end
def main() 
	matrix = [
		[1, 2, 3],
		[4, 5, 6],
		[7, 8, 3]
	]
	obj = MyMatrix.new(matrix)
	obj.show_data(matrix)
	obj.find_normal_trace(matrix)
end


main()

Output

 1 2 3
 4 5 6
 7 8 3

 Normal  :14
 Trace  :9
/*
  Scala Program
  Find normal and trace of a matrix
*/
class MyMatrix(var size: Int) {
	;

	def this(matrix: Array[Array[Int]]) {
		//Get matrix size
		//Assume that given matrix size is NXN 
		this(matrix.length);
	}
	def find_normal_trace(matrix: Array[Array[Int]]): Unit = {
		if (this.size <= 0) {
			return;
		}
		var normal: Int = 0;

		//Calculate Normal
		var i: Int = 0;
      	var j: Int = 0;
		while (i < this.size) {
			j = 0;
			while (j < this.size) {
				normal += matrix(i)(j) * matrix(i)(j);
				j += 1;
			}
			i += 1;
		}
		print(" Normal : " + (Math.sqrt(normal)).toInt + "\n");
		var trace: Int = matrix(0)(0);
		i = 1;
		while (i < this.size) {
			j = 0;
			while (j < this.size) {
				if (i == j) {
					//Calculate sum of diagonal elements
					trace += matrix(i)(j);
				}
				j += 1;
			}
			i += 1;
		}
		print(" Trace : " + trace + "\n");
	}
	def show_data(matrix: Array[Array[Int]]): Unit = {
		var i: Int = 0;
		while (i < this.size) {
			var j: Int = 0;
			while (j < this.size) {
				print(" " + matrix(i)(j));
				j += 1;
			}
			print("\n");
			i += 1;
		}
		print("\n");
	}
}
object Main {
	def main(args: Array[String]): Unit = {
		val matrix: Array[Array[Int]] = Array(
			Array(1, 2, 3),
			Array(4, 5, 6),
			Array(7, 8, 3));
		val obj: MyMatrix = new MyMatrix(matrix);
		obj.show_data(matrix);
		obj.find_normal_trace(matrix);
	}
}

Output

 1 2 3
 4 5 6
 7 8 3

 Normal : 14
 Trace : 9
/*
  Swift Program
  Find normal and trace of a matrix
*/
import Foundation
class MyMatrix {
	var size: Int;
	init(_ matrix: [
		[Int]
	]) {
		//Get matrix size
		//Assume that given matrix size is NXN 
		self.size = matrix.count;
	}
	func find_normal_trace(_ matrix: [
		[Int]
	]) {
		if (self.size <= 0) {
			return;
		}
		var normal: Int = 0;
		//Calculate Normal
		var i: Int = 0;
      	var j: Int = 0;
		while (i < self.size) {
			j = 0;
			while (j < self.size) {
				normal += matrix[i][j] * matrix[i][j];
				j += 1;
			}
			i += 1;
		}
		print(" Normal : ", Int(sqrt(Double(normal))) ,"\n", terminator: "");
		var trace: Int = matrix[0][0];
		i = 1;
		while (i < self.size) {
			j = 0;
			while (j < self.size) {
				if (i == j) {
					//Calculate sum of diagonal elements
					trace += matrix[i][j];
				}
				j += 1;
			}
			i += 1;
		}
		print(" Trace : ", trace ,"\n", terminator: "");
	}
	func show_data(_ matrix: [
		[Int]
	]) {
		var i: Int = 0;
		while (i < self.size) {
			var j: Int = 0;
			while (j < self.size) {
				print(" ", matrix[i][j], terminator: "");
				j += 1;
			}
			print("\n", terminator: "");
			i += 1;
		}
		print("\n", terminator: "");
	}
}
func main() {
	let matrix: [
		[Int]
	] = [
		[1, 2, 3],
		[4, 5, 6],
		[7, 8, 3]
	];
	let obj: MyMatrix = MyMatrix(matrix);
	obj.show_data(matrix);
	obj.find_normal_trace(matrix);
}
main();

Output

  1  2  3
  4  5  6
  7  8  3

 Normal :  14
 Trace :  9

Output Explanation

The provided C code implements the above algorithm to find the normal and trace of a given matrix. It iterates through the matrix, calculates the sum of the squared absolute values of its elements to find the normal, and sums up the diagonal elements to find the trace.

Time Complexity

The time complexity of the algorithm is O(SIZE^2), where SIZE is the number of rows (or columns) in the matrix. This is because the algorithm iterates through each element of the matrix to calculate the normal and trace.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment