Sum of diagonal elements in a matrix

后端 未结 11 2477
有刺的猬
有刺的猬 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:23

    Use numpy library which is powerful for any matrix calculations. For your specific case:

    import numpy as np
    a = [[11,2,4],[4,5,6],[10,8,-12]]
    b = np.asarray(a)
    print 'Diagonal (sum): ', np.trace(b)
    print 'Diagonal (elements): ', np.diagonal(b)
    

    You can easily install numpy with pip or other ways that you will find on many webs.

    If you want all the diagonals, and not just the main diagonal, check this that also uses numpy.

    EDIT

    mhawke, if you want to calculate antidiagonal (secondary diagonal), as explained in wikipedia, you can flip the matrix in numpy

    import numpy as np
    a = [[11,2,4],[4,5,6],[10,8,-12]]
    b = np.asarray(a)
    b = np.fliplr(b)
    print 'Antidiagonal (sum): ', np.trace(b)
    print 'Antidiagonal (elements): ', np.diagonal(b)
    

提交回复
热议问题