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:29

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.

查看更多
霸刀☆藐视天下
3楼-- · 2020-06-08 13:32

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:

 #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

查看更多
萌系小妹纸
4楼-- · 2020-06-08 13:40
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 :)

查看更多
5楼-- · 2020-06-08 13:42

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]
查看更多
三岁会撩人
6楼-- · 2020-06-08 13:47

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)
查看更多
家丑人穷心不美
7楼-- · 2020-06-08 13:47

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
查看更多
登录 后发表回答