Python 矩阵中对角线元素的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35252993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:11:47  来源:igfitidea点击:

Sum of diagonal elements in a matrix

pythonmatrix

提问by Hassan Imam

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 是方阵的大小,a 是矩阵。有人可以向我解释这里发生了什么。

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

采纳答案by mhawke

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.

它将以相反的顺序再次处理第一个对角线,[(2, 2), (1, 1), (0, 0)]两次得到相同的总和。

回答by iblasi

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

使用 numpy 库,它对任何矩阵计算都很强大。对于您的具体情况:

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.

您可以使用 pip 或在许多网站上可以找到的其他方式轻松安装 numpy。

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

如果您想要所有对角线,而不仅仅是主对角线,请检查这个也使用 numpy.

EDIT

编辑

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

mhawke,如果你想计算 antidiagonal (secondary diagonal),如维基百科中所述,你可以在 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)

回答by Binyamin Even

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

回答by xtofl

Since you know the positions of the diagonal elements for row i, you can write it quite densely like:

由于您知道 row 对角线元素的位置i,您可以将其写得很密集,如下所示:

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]

回答by Sathvik Andela

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

回答by Deepeshkumar

I found a simple algorithm to accomplish this task.

我找到了一个简单的算法来完成这个任务。

  1. Store the square matrix in a single one dimensional array.

  2. Let 'n' be the order of square matrix.

  3. There are two diagonals , one that starts from the leftmost element in top row and another that starts from nth element of the top row.

  4. To get the indexes of numbers on the diagonal that starts from left most element in top row ,from the array containing all the numbers in the matrix; just add (n+1) recursively starting from index 1. That is, indexes of elements in left to right diagonal in the array are, 1, 1+(n+1) , (n+2)+(n+1) , (2n+3)+(n+1) till the last index of array.

  5. To get the indexes of another diagonal's numbers from the array containing all the numbers in the matrix ; just add (n-1) recursively to the indexes starting from index equals to the 'n', which is the order of the square matrix. That is, indexes of elements in right to left diagonal in the array are, n, n+(n-1), (2n-1)+(n-1) and so on till the index equals to 'length of the array - (n-1)'.

  6. If the order is odd then subtract the middle number in the array from the final sum.

The example 'c++' code is as follows:

  1. 将方阵存储在单个一维数组中。

  2. 让 'n' 是方阵的阶数。

  3. 有两条对角线,一条从顶行最左边的元素开始,另一个从顶行的第 n 个元素开始。

  4. 从包含矩阵中所有数字的数组中获取从顶行最左侧元素开始的对角线上数字的索引;只需从索引 1 开始递归地添加 (n+1)。 也就是说,数组中从左到右对角线的元素的索引是, 1, 1+(n+1) , (n+2)+(n+1) , (2n+3)+(n+1) 直到数组的最后一个索引。

  5. 从包含矩阵中所有数字的数组中获取另一个对角线数字的索引;只需将 (n-1) 递归添加到从 index 开始的索引等于 'n',这是方阵的顺序。也就是说,数组中从右到左对角线的元素的索引是,n、n+(n-1)、(2n-1)+(n-1) 等等,直到索引等于'数组的长度- (n-1)'。

  6. 如果顺序是奇数,则从最终总和中减去数组中的中间数。

示例“c++”代码如下:

 #include<iostream>
 using namespace std;

int sumOfDiagonalNumbersInSquareMatrix(int numberArray[],int order){
int sumOfLeftToRightDiagonal = 0;
int sumOfRightToLeftDiagonal = 0;
int length = order*order;
for(int i=0; i<length;i+=(order+1)){
    //cout<<numberArray[i]<<"\t";
    sumOfLeftToRightDiagonal = sumOfLeftToRightDiagonal + numberArray[i];

}
for(int i=(order-1);i<=length-order;i+=(order-1)){
    //cout<<numberArray[i]<<"\t";
    sumOfRightToLeftDiagonal = sumOfRightToLeftDiagonal + numberArray[i];
}
if(order % 2 != 0){
    return (sumOfLeftToRightDiagonal + sumOfRightToLeftDiagonal) - numberArray[(length/2)];
}
return (sumOfLeftToRightDiagonal + sumOfRightToLeftDiagonal);
}

 int main(){
 int nums[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
 cout<<sumOfDiagonalNumbersInSquareMatrix(nums,4);
 return 0;
 }

You can run it here: http://cpp.sh/6cmdp

你可以在这里运行它:http: //cpp.sh/6cmdp

回答by Akshat Tamrakar

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.

这里 arr 是一个二维列表。

回答by Samir Paul

getting total and diagonal sum from a squared matrix

从平方矩阵中获取总和和对角线总和

squared_matrix = [[2,3,4],[4,3,3],[3,3,4]]
s, ds = get_sum(squared_matrix)

def get_sum(diag_mat):
    n = len(diag_mat)
    total = sum([diag_mat[i][j] for i in range(n) for j in range(j)]
    d_sum = sum([diag_mat[i][j] if i==j else 0 for i in range(n) for j in range(j)]
   return d_sum, total