Sum of diagonal elements in a matrix

2020-06-08 13:29发布

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 happening here.

n = 3
a = [[11,2,4],[4,5,6],[10,8,-12]]
sum_first_diagonal = sum(a[i][i] for i in range(n))
sum_second_diagonal = sum(a[n-i-1][n-i-1] for i in range(n))
print(str(sum_first_diagonal)+" "+str(sum_first_diagonal))

标签: python matrix
9条回答
冷血范
2楼-- · 2020-06-08 13:51

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
查看更多
Emotional °昔
3楼-- · 2020-06-08 13:54

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.

查看更多
祖国的老花朵
4楼-- · 2020-06-08 13:56
def sum_diagnol():
    import random
    sum=0
    r1=int(input("row"))
    c1=int(input("col"))
    a=[[random.random()for col in range(c1)]for row in range(r1)]
    print("enter elements")
    for i in range(r1):
        for j in range(c1):
            a[i][j]=int(input("enter elements"))
    r2=int(input("row"))
    c2=int(input("col"))
    b=[[random.random()for col in range(c2)]for row in range(r2)]
    print("enter elements")
    for i in range(r2):
        for j in range(c2):
            b[i][j]=int(input("enter elements"))
    c=[[random.random()for col in range(c2)]for row in range(r1)]
    if(c1==r2):
        for i in range(r1):
            for j in range(c2):
                c[i][j]=0
                for k in range(c2):
                    c[i][j]=a[j][k]*b[k][j]
    else:
        print("multiplication not possible")
    for i in range(r1):
        for j in range(c2):
            print(c[i][j],end=" ")
        print()
sum_diagnol()
查看更多
登录 后发表回答