Sum of diagonal elements in a matrix

后端 未结 11 2496
有刺的猬
有刺的猬 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-12 12:31

    '''

    a = [[],[],[]] #your matrix
    s = 0
    for i in range(len(a)):
        for j in range(len(a[0])):
               if i == j:
                   s += a[i][j]
    print('sum ='s)
    

    ''' here is a simple approach. Thanks

提交回复
热议问题