1
I am developing an algorithm and I want to know if there is a command to add the main diagonal of an array in Python
1
I am developing an algorithm and I want to know if there is a command to add the main diagonal of an array in Python
4
In Python there is no proper function for this, but implementing it is quite 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 is composed of: (1, 1), (2, 2), (3, 3), ..., (n, n); that is, all values in position (i, j) where i = j.
So, as the index in Python starts at 0, you need to go from 0 to n-1, n being the size of the matrix.
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 matrix is square.
The Numpy library has the function numpy.trace
that returns the diagonal sum.
thank you.......
3
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)
Browser other questions tagged python
You are not signed in. Login or sign up in order to post.
Not in Python, but it’s a trivial operation to implement. Why not try it yourself and post here if you can’t?
– Woss
thanks, I’ve got it
– user129775