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 happen
def sum_up_diagonals(li):
index = len(li)
first_dia = sum(li[i][i]for i in range(index))
second_dia = sum(li[i][index-i-1]for i in range(index))
return (first_dia,second_dia)
Pass in your list. This should work for you :)
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
'''
a = [[],[],[]] #your matrix
s = 0
for i in range(len(a)):
for j in range(len(a[0])):
if i == j:
s += a[i][j]
print('sum ='s)
''' here is a simple approach. Thanks
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)
O(n) time solution to find the diagonal difference of given multidimensional array.
def diagonalDifference(arr):
# arr[0][0], arr[1][1], arr[2][2]
# arr[0][2], arr[1][1], arr[2][0]
sumOfDiagonalFromLeft = 0
sumOfDiagonalFromRight = 0
pointIndexFromLeft = 0
pointIndexFromLast = len(arr)-1
for i in range(len(arr)):
sumOfDiagonalFromLeft += arr[i][pointIndexFromLeft]
# print(arr[i][pointIndexFromLeft])
pointIndexFromLeft += 1
for i in range(len(arr)):
sumOfDiagonalFromRight += arr[i][pointIndexFromLast]
# print(arr[i][pointIndexFromLast])
if pointIndexFromLast < 0:
break
else:
pointIndexFromLast -= 1
diagonalDifference = abs(sumOfDiagonalFromLeft - sumOfDiagonalFromRight)
return diagonalDifference
arr = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]
print(diagonalDifference(arr))
I don't understand why no one posted any good solution. Here is as descent solution:
length = len(arr)
r1 = 0
r2 = 0
for i in range(length):
r1 += arr[i][length - i - 1]
r2 += arr[i][i]
print(r1 + r2)
# If you want sum of there absolute values
print(abs(r1) + abs(r2))
Here arr is a 2d list.