简体   繁体   English

矩阵中对角线元素的总和

[英]Sum of diagonal elements in a matrix

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.这里,n 是方阵的大小,a 是矩阵。 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))

Use numpy library which is powerful for any matrix calculations.使用对任何矩阵计算都非常强大的 numpy 库。 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.您可以使用 pip 或您在许多网站上找到的其他方式轻松安装 numpy。

If you want all the diagonals, and not just the main diagonal, check this that 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,如果要计算对角线(次对角线),如wikipedia中所述,您可以在 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))

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)]给你两次相同的总和。

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

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

You can follow below code to get sum of first diagonal and sum of second diagonal in a metrix. 您可以按照以下代码获取矩阵中第一对角线和第二对角线之和的总和。 I think this will be the most understand way. 我认为这将是最明白的方式。

Get sum of first diagonal, 得到第一对角线的总和,

n = 3
a = [[11,2,4],[4,5,6],[10,8,-12]]
sum_1_diagonal = 0
for x in range(0, n):
    for y in range(0, n):
       if x == y:
          sum_1_diagonal = sum_1_diagonal + a[x][y]

Get sum of second diagonal, 得到第二对角线的总和,

n = 3
a = [[11,2,4],[4,5,6],[10,8,-12]]
sum_2_diagonal = 0
for x in range(0, n):
    for y in range(0, n):
       if x + y == n - 1:
          sum_2_diagonal = sum_2_diagonal + a[x][y]
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 :)这应该适合你:)

O(n) time solution to find the diagonal difference of given multidimensional array. O(n) 时间解来找到给定多维数组的对角线差。

def diagonalDifference(arr):
        # arr[0][0], arr[1][1], arr[2][2]
        # arr[0][2], arr[1][1], arr[2][0]
        sumOfDiagonalFromLeft = 0
        sumOfDiagonalFromRight = 0
        pointIndexFromLeft = 0
        pointIndexFromLast = len(arr)-1
        for i in range(len(arr)):
            sumOfDiagonalFromLeft += arr[i][pointIndexFromLeft]
            # print(arr[i][pointIndexFromLeft])
            pointIndexFromLeft += 1
        
        for i in range(len(arr)):
            sumOfDiagonalFromRight += arr[i][pointIndexFromLast]
            # print(arr[i][pointIndexFromLast])
            if pointIndexFromLast < 0:
                break
            else:
                pointIndexFromLast -= 1
    
        diagonalDifference = abs(sumOfDiagonalFromLeft - sumOfDiagonalFromRight)
        return diagonalDifference
    
arr = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]
print(diagonalDifference(arr))
//we simply swap  corner elements of matrix

def diagonalDifference(arr):

    c=0;d=0
    for i in range(len(arr)):
        for j in range(len(arr)):
            if i==j :
                c = c+ arr[i][j]
        for k in range(len(arr)):
            arr[i][k-1],arr[i][k-2] = arr[i][k-2],arr[i][k-1]
        

        for j in range(len(arr)):
            if i==j :
                d = d + arr[i][j]
        for k in range(len(arr)):
            arr[i][k-1],arr[i][k-2] = arr[i][k-2],arr[i][k-1]
            
    
    
    print(c,d)  
    result = abs(c-d)
    print(result)

Python 3 Solution with dynamic inputs of matrix as list inputs将矩阵的动态输入作为列表输入的 Python 3 解决方案

#Even matrix size is dynamic in this code as "n".

n=int(input())
s1=0
s2=0
a =[]
for i in range(n):

    # x here take input of size n and as separate lists to act like a matrix.

    x=list(map(int,input().strip().split()))[:n]
    a.append(x)
for i in range(n):
    s1+=a[i][i]
    s2+=a[i][n-i-1]

# If use abs() only if non-negative output is needed!!
print(abs(s1-s2)) 
# First enter the size of matrix then enter the matrix vales with spaces in each line

Assuming a square matrix (nxn), you can compute the sums of both primary and secondary diagonals with only 1 iteration through the rows of the matrix;假设一个方阵 (nxn),您可以计算主对角线和次对角线的总和,只需对矩阵的行进行 1 次迭代; by keeping track of the indices involved in each computation.通过跟踪每次计算中涉及的索引。

mat = [
    [1,2,3],
    [4,5,6],
    [9,8,9]
]

primary = 0
secondary = 0
low = 0 # start index for primary
high = len(mat)-1 # end index for secondary

for row in mat:
    primary += row[low]
    secondary += row[high]
    low += 1
    high -= 1

print(f'Primary Sum = {primary}', f'Secondary Sum = {secondary}', sep='\n')

Let's suppose, you have a matrix A n×m.假设,您有一个矩阵 A n×m。

  A = [[random.rand() for i in range(n+1)] for i in range(m+1)]
  
  d = m+n-1 # that's the overall number of different diagonals
  sumrow = [0]*d # I'd like to create a list of all the sums of those
  for diag in range(d): # iterate by diagonal number
      # A difference of two related spike functions, so that it was a spike without the top
      diaglength = int(max(0,1+d/2-abs(diag+1/2-d/2)) - max(0,1+d/2-n-abs(diag+1/2-d/2)))
      # initial coordinates for further iteration inside sum() function
      x = max(0, diag-m+1)
      y = max(0, m-diag-1)
      # iterating values along the current diagonal
      sumrow[diag]=sum(A[x+i][y+i] for i in range(0,diaglength))

Thus, sumrow[] is a list of every sum of every diagonal, choose and don't get puddled up.因此, sumrow[] 是每个对角线的每个总和的列表,请选择不要弄乱。 I think, it's obvious what to cut off this code to get some specific value immediately.我认为,很明显要切断这段代码以立即获得一些特定的价值。 Technically, this code could be compressed in one line.从技术上讲,这段代码可以压缩成一行。 Really long line.真的很长的线。

But why?但为什么?

mat = [[1 ,2, 3, 4,5],[1,2,1,2,3],[2,3,4,5,2],[1,3,5,1,1],[1,2,1,2,1]] mat = [[1 ,2, 3, 4,5],[1,2,1,2,3],[2,3,4,5,2],[1,3,5,1,1] ,[1,2,1,2,1]]

def isSquare(mat): if len(mat) == 1: return True for i in range(len(mat)): if len(mat[i]) != len(mat): print("Matrix is not Squared") return False return True def isSquare(mat): if len(mat) == 1: return True for i in range(len(mat)): if len(mat[i]) != len(mat): print("Matrix is not Squared ") 返回 False 返回 True

def sumOfLeftDiagonal(mat): d1 = 0 size = len(mat) for i in range(0,size): for j in range(0,size): if i == j: d1 = d1 + mat[i][j] return d1 def sumOfLeftDiagonal(mat): d1 = 0 size = len(mat) for i in range(0,size): for j in range(0,size): if i == j: d1 = d1 + mat[i][ j] 返回 d1

def sumOfRightDiagonal(mat): d2 = 0 size = len(mat) for i in range(0,size): d2 = d2 + mat[i][(size-1)-i] return d2 def sumOfRightDiagonal(mat): d2 = 0 size = len(mat) for i in range(0,size): d2 = d2 + mat[i][(size-1)-i] return d2

if isSquare(mat): if len(mat) == 1: print("Difference: ",mat[0]) else: print("sumOfLeftDiagonal: ",sumOfLeftDiagonal(mat)) print("sumOfRightDiagonal: ",sumOfRightDiagonal(mat)) print("Difference: ",abs(sumOfLeftDiagonal(mat)-sumOfRightDiagonal(mat))) if isSquare(mat): if len(mat) == 1: print("Difference: ",mat[0]) else: print("sumOfLeftDiagonal: ",sumOfLeftDiagonal(mat)) print("sumOfRightDiagonal: ",sumOfRightDiagonal( mat)) print("差异:",abs(sumOfLeftDiagonal(mat)-sumOfRightDiagonal(mat)))

Here is a simpler way to get the full primary diagonal and secondary diagonal这是获取完整primary diagonalsecondary diagonal的更简单方法

squared_matrix = [
    [2, 3, 4],
    [4, 3, 3],
    [3, 3, 4]
]


def primary_diagonal(matrix):
    sum = 0
    for i in range(len(matrix)):
        sum += matrix[i][i]
    return sum

def secondary_left_diagonal(matrix):
    sum = 0
    for i in range(len(matrix)):
        sum += matrix[i][len(matrix) - i - 1]
    return sum


print(primary_diagonal(squared_matrix))
print(secondary_left_diagonal(squared_matrix))

Result结果

9
10

Here is one way one how to do it:这是一种方法:

Since the matrix is square we can get sum of a diagonal and anti-diagonal by using a original and reversed lists.由于矩阵是正方形的,我们可以通过使用原始列表和反向列表来获得对角线和反对角线的总和。

matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

to_sum =[]                             # an empty list for collection values

for i in range(len(matrix)):           # diagonal coordinats [0][0], [1][1].... [n][n]
    to_sum.append(matrix[i][i])        # append value of diagonal
    rev = matrix[i][::-1]              # for anti-diagonal reverse list
    to_sum.append(rev[i])              # append value of anti-diagonal
                                       # to_sum list [1, 4, 6, 7, 11, 10, 16, 13]
return sum(to_sum)                     # return sum of all values in list (68)

Since you know the positions of the diagonal elements for row i , you can write it quite densely like:由于您知道第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]
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()

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.让'n'是方阵的阶。

  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.有两条对角线,一条从顶行最左边的元素开始,另一个从顶行的第 n 个元素开始。

  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.只需从索引 1 开始递归地添加 (n+1)。也就是说,数组中从左到右对角线的元素的索引为 1, 1+(n+1) , (n+2)+(n+1) , (2n+3)+(n+1) 直到数组的最后一个索引。

  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.只需将 (n-1) 递归添加到从 index 开始的索引等于“n”,这是方阵的顺序。 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)'.也就是说,数组中从右到左对角线元素的索引是,n,n+(n-1),(2n-1)+(n-1) 等等,直到索引等于'数组的长度 - (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:示例“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

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 是一个二维列表。

''' '''

a = [[],[],[]] #your matrix
s = 0
for i in range(len(a)):
    for j in range(len(a[0])):
           if i == j:
               s += a[i][j]
print('sum ='s)

''' here is a simple approach. ''' 这里是一个简单的方法。 Thanks谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM