Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of diagonal elements in a matrix

Tags:

python

matrix

I am trying to find out the sum of the diagonal elements in a matrix. Here, n is the size of the square matrix and a is the matrix. Can someone explain this to me what is happening here.

n = 3
a = [[11,2,4],[4,5,6],[10,8,-12]]
sum_first_diagonal = sum(a[i][i] for i in range(n))
sum_second_diagonal = sum(a[n-i-1][n-i-1] for i in range(n))
print(str(sum_first_diagonal)+" "+str(sum_first_diagonal))
like image 385
Hassan Imam Avatar asked Feb 07 '16 11:02

Hassan Imam


3 Answers

Use numpy library which is powerful for any matrix calculations. For your specific case:

import numpy as np a = [[11,2,4],[4,5,6],[10,8,-12]] b = np.asarray(a) print('Diagonal (sum): ', np.trace(b)) print('Diagonal (elements): ', np.diagonal(b)) 

You can easily install numpy with pip or other ways that you will find on many webs.

If you want all the diagonals, and not just the main diagonal, check this that also uses numpy.

EDIT

mhawke, if you want to calculate antidiagonal (secondary diagonal), as explained in wikipedia, you can flip the matrix in numpy

import numpy as np a = [[11,2,4],[4,5,6],[10,8,-12]] b = np.asarray(a) b = np.fliplr(b) print('Antidiagonal (sum): ', np.trace(b)) print('Antidiagonal (elements): ', np.diagonal(b)) 
like image 74
iblasi Avatar answered Oct 12 '22 20:10

iblasi


Try this for summing your second diagonal:

sum(a[i][n-i-1] for i in range(n)) 

The inner loop accesses these entries:

>>> n = 3 >>> [(i, n-i-1) for i in range(n)] [(0, 2), (1, 1), (2, 0)] 

And the summed value of this diagonal for your sample matrix is:

>>> n = 3 >>> sum(a[i][n-i-1] for i in range(n)) 19 

The mistake in your code is to use the same expression for both dimensions:

a[n-i-1][n-i-1] 

which will process the first diagonal again in reverse order [(2, 2), (1, 1), (0, 0)] giving you the same sum twice.

like image 38
mhawke Avatar answered Oct 12 '22 19:10

mhawke


getting total and diagonal sum from a squared matrix

squared_matrix = [[2,3,4],[4,3,3],[3,3,4]]
s, ds = get_sum(squared_matrix)

def get_sum(diag_mat):
    n = len(diag_mat)
    total = sum([diag_mat[i][j] for i in range(n) for j in range(j)]
    d_sum = sum([diag_mat[i][j] if i==j else 0 for i in range(n) for j in range(j)]
   return d_sum, total
like image 40
Samir Paul Avatar answered Oct 12 '22 20:10

Samir Paul