Python numpy program to find sum the diagonal elements of the matrix














































Python numpy program to find sum the diagonal elements of the matrix



Python numpy program to find sum the diagonal elements of the matrix

Description: we have to find the sum of diagonal elements in a matrix .
so first we create a matrix using numpy arange() function and then calculate the principal diagonal
elements sum using trace() function and diagonal element using diagonal() function.

1: trace(): trace of an n by n square matrix A is defined to be the sum of the elements on the main diagonal
(the diagonal from the upper left to the lower right) of matrix A.
Example:
import numpy as np
a=np.arange(9).reshape(3,3)
print("original matrix is :\n",a)
m=np.trace(a)
print("trace of matrix :", m)

output:
original matrix is :
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8 ]]
trace of matrix : 12
2: diagonal(): diagonal function in numpy returns upper left o right diagonal elements.
If a is 2-D and not a matrix, a 1-D array of the same type as a containing the diagonal is
returned.
If a is a matrix, a 1-D array containing the diagonal is returned in order to maintain backward
compatibility.
If the dimension of a is greater than two, then an array of diagonals is returned, packed from
left-most dimension to right-most (e.g.,
if a is 3-D, then the diagonals are packed along rows).
Example: for 3-D matrix example code is here for 3-D matrix example code is here .

import numpy as np import numpy as np
a=np.arange(9).reshape(3,3) a=np.arange(9).reshape(2,3,3)
print("original matrix is :\n",a) print("original matrix is :\n",a)
m=a.diagonal() m=a.diagonal()
print("diagonal elements \n:", m) print("diagonal elements \n:", m)

output: output:
original matrix is : original matrix is :
[[[ 0 1 2] [[[ 0 1 2]
[ 3 4 5] [ 3 4 5]
[ 6 7 8]] [ 6 7 8]]
diagonal elements : [0,4,8]
[[
9 10 11]
[
12 13 14]
[
15 16 17]]]
diagonal elements
[[ 0 12]
[
1 13]
[
2 14]]

code:

#import numpy library
import numpy as np
# create a class
class diagnoal_sum:
# create function
def sum_diagonal( self,a, r,c):
# check whether a given a row and column is valid or not.
if c==0 and r==0:
return print("Enter valid matrix ,Matrix should be (n x n) format")

# we use diagonal() function used to return specified diagonal elements.
print(
"diagonal elements are :",a.diagonal())
# we use trace() function used to Sum along diagonals.
result = np.trace(a)
print(
"sum of diagonals Elements :",result)


# define main() function.
def main():
digsum=diagnoal_sum()
#taking input from console.
row,col=input(
"enter row and column :").split()
r=int(row)
c=int(col)
# create matrix using numpy function arange() in sequential order.
a=np.arange(r*c).reshape(r,c)
print(
"Original matrix :\n", a)
#call function to execute .
digsum.sum_diagonal(a,r,c)
if __name__ == "__main__":
main()

output:
case1: when row and column are equal .
enter row and column :3 3
Original matrix :
[[
0 1 2]
[
3 4 5]
[
6 7 8]]
diagonal elements are : [
0 4 8]
sum of diagonals Elements :
12

case2: when row and column are not equal
enter row and column :3 2
Original matrix :
[[
0 1]
[
2 3]
[
4 5]]
diagonal elements are : [
0 3]
sum of diagonals Elements :
3

case3: when row and column are both 0.
enter row and column :0 0
Original matrix :
[]
Enter valid matrix ,Matrix should be (n x n) format.


keep coding happy coding :)

More Articles of Akrati Sharma:

Name Views Likes
Python numpy program to generate random number 833 0
Program to construct BST from level order traversal 642 2
Python numpy program to find sum the diagonal elements of the matrix 8456 1
Python find sum the diagonal elements of the matrix 1605 0
python numpy find the transpose of a matrix 393 0
Python numpy convert a csv file date to a matrix 492 1
Python program to read configuration file 382 1
Python program to convert doc file into pdf file. 997 19
Python program to add new page at the end of a pdf file 310 18
Python Program to find sink odd nodes in binary tree. 436 14
creating project in pythons scrapy library 405 16
Python program to check given array of size n can represent binary search tree of n levels or not. 298 16
Python program to find out greater sum tree elements of binary search tree 306 17
Selectors of scrapy library 396 24
Introduction to python scrapy library 314 16
Python Program to find an element in tuple by value using in and not in 288 18
Find an element in tuple by value using in and not in : 93 25
Python program to count Half Nodes in Binary Tree recursion 443 20
Python Program to find top three elements in binary tree. 262 20
Python program to count half nodes in binary tree without recursion 374 14
Python program to find deepest right leaf node in a binary tree using recursion. 350 18
Python program to convert a given tree to its Sumtree 489 26
Python program to convert a tree into its sum tree 84 21
Python Program to Convert Binary tree into Binary Search Tree 379 17
Python Program to check if each internal node of a BST has exactly one child 334 18
Python Program to find median of binary search tree 637 11
Python Program to find an Element into a Binary tree. 261 18
Python program to replace every element with the least greater element on its right 326 18
Python Program to delete an element at specific index in tuple. 20 13
Python program to insert an element to specific position in tuple 361 20
Python program to insert an element at specific position in tuple. 13 11
Python Program to append an element in tuple at the end. 313 20
Python Program to count subtree that sum up to a given value x 558 20
Python program to print all root to leaf paths with there relative positions 312 16
Python program to check given tree is Sumtree or not 412 16
Python program to find sum of nodes at maximum depth of a binary tree 505 21
Python Program to replace an element at specific index in tuple. 354 24
Python program to find given key x in binary tree 289 14
Python program to find vertical width of binary tree 352 15
Python program to find mirror of a given node in binary tree 369 19
Python program to find largest subtree sum in a tree 260 18
Python Program to calculate the size of tree without recursion 328 19
Python Program to find tilt of binary tree 452 18
Python Program to find maximum node in left subtree in binay tree. 240 16
Python program to convert a List to Dictionary with same Value. 278 19
Python program to count minimum swap require to construct Binary Search Tree from Binary tree 461 18
Program to construct BST from level order traversal 353 24
Python Program to delete an element at specific index in tuple. 571 21
Python Program to print all the elements in Binary Search tree. 1323 14

Comments