Sum of diagonal elements in a matrix

后端 未结 11 1933
轻奢々
轻奢々 2021-02-12 11:42

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

11条回答
  •  你的背包
    2021-02-12 12:08

    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
    

提交回复
热议问题