Sum of diagonal elements in a matrix

后端 未结 11 1935
轻奢々
轻奢々 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:25

    Since you know the positions of the diagonal elements for row i, you can write it quite densely like:

    d = sum(row[i] + row[-1-i] for i, row in a)
    

    And, for odd sized matrices, you shouldn't add the center element twice:

    if len(a)%2:
        centre = len(a)//2
        d -= a[centre][centre]
    

提交回复
热议问题