Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

sum of two diagonals in matrix

### START FUNCTION
def sum_of_diagonals(matrix):
    diag_1=0
    diag_2=0
    k = matrix.shape[1]-1
    for i in range(matrix.shape[0]):
        diag_1 += matrix[i][i]
        diag_2 += matrix[i][k]
        k -=1
    if matrix.shape[0]%2 != 0:
        mid = int(np.floor(matrix.shape[0]/2))
        sum = diag_1+diag_2-matrix[mid][mid]
    else:
        sum = diag_1+diag_2
    return sum
### END FUNCTION
Source by athena.explore-datascience.net #
 
PREVIOUS NEXT
Tagged: #sum #diagonals #matrix
ADD COMMENT
Topic
Name
8+9 =