Sum of diagonal elements in a matrix

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

    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]
    
    0 讨论(0)
  • 2021-02-12 12:16

    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
    
    0 讨论(0)
  • 2021-02-12 12:18

    Try this for summing your second diagonal:

    sum(a[i][n-i-1] for i in range(n))
    

    The inner loop accesses these entries:

    >>> n = 3
    >>> [(i, n-i-1) for i in range(n)]
    [(0, 2), (1, 1), (2, 0)]
    

    And the summed value of this diagonal for your sample matrix is:

    >>> n = 3
    >>> sum(a[i][n-i-1] for i in range(n))
    19
    

    The mistake in your code is to use the same expression for both dimensions:

    a[n-i-1][n-i-1]
    

    which will process the first diagonal again in reverse order [(2, 2), (1, 1), (0, 0)] giving you the same sum twice.

    0 讨论(0)
  • 2021-02-12 12:21

    I don't understand why no one posted any good solution. Here is as descent solution:

    length = len(arr)
    r1 = 0
    r2 = 0
    for i in range(length):
        r1 += arr[i][length - i - 1]
        r2 += arr[i][i]
    print(r1 + r2)
    # If you want sum of there absolute values
    print(abs(r1) + abs(r2))
    

    Here arr is a 2d list.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-02-12 12:23
    def sum_up_diagonals(li):
    index = len(li)
    first_dia =  sum(li[i][i]for i in range(index))
    second_dia = sum(li[i][index-i-1]for i in range(index))
    return (first_dia,second_dia)
    

    Pass in your list. This should work for you :)

    0 讨论(0)
提交回复
热议问题