Sum of diagonal elements in a matrix

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

    try this:

    n=3
    sum_second_diagonal=sum([a[i][j] for i in range(n) for j in range(n) if i==j]) #it will add when i==j
    

提交回复
热议问题