How to sum the main diagonal of a matrix in python? [closed]

0

I am developing an algorithm and want to know if there is any command to sum the main diagonal of an array in Python

    
asked by anonymous 31.10.2018 / 17:59

2 answers

3

In Python there is no function of its own, but implementing it is fairly trivial.

A square matrix n x n can be represented as:

| (1, 1)   (1, 2)   (1, 3)   ...   (1, n) |
| (2, 1)   (2, 2)   (2, 3)   ...   (2, n) |
| (3, 1)   (3, 2)   (3, 3)   ...   (3, n) |
|  ...      ...      ...     ...    ...   |
| (n, 1)   (n, 2)   (n, 3)   ...   (n, n) |

Where the main diagonal consists of: (1, 1), (2, 2), (3, 3), ..., (n, n); that is, all values at the position (i, j) where i = j.

So, as the index in Python starts at 0, you need to move from 0 to n-1, where n is the size of the array.

def soma_diagonal_principal(matriz):
    n = len(matriz)
    assert n == len(matriz[0]), 'Matriz precisa ser quadrada'
    return sum(matriz[i][i] for i in range(n))

The assert in the function will ensure that the array is square.

The NumPy library has the function numpy.trace . which returns the sum of the diagonal.

    
31.10.2018 / 18:48
1
n= 4

m= [[2,6,4,3],[2,4,6,4],[5,1,0,4],[4,5,4,6]]

sum_diagonal = sum(m[i][i]for i in range(n))

print(sum_diagonal)
    
31.10.2018 / 18:39