Sum of diagonal elements in a matrix

后端 未结 11 2478
有刺的猬
有刺的猬 2021-02-12 11:35

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:25

    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
    

提交回复
热议问题