矩阵中对角元素的总和 [英] Sum of diagonal elements in a matrix

查看:117
本文介绍了矩阵中对角元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出矩阵中对角线元素的总和.在此,n是方矩阵的大小,a是矩阵.有人可以向我解释一下这是怎么回事.

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))

推荐答案

尝试使用此方法求和第二对角线:

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]

这将再次以相反的顺序处理第一个对角线[(2, 2), (1, 1), (0, 0)],使您两次获得相同的总和.

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

这篇关于矩阵中对角元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆