Trying to get all the diagonal elements of a NXN matrix without using numpy,
This is different from Get diagonal without using numpy in Python
Please don't mark as duplicate.
Here is my snippet using two iteration, it will print all the diagonal element from (0,0) to (n,n). Could some one help me in improving my iteration process or any recursive way to do it.
#!/usr/bin/python
matrix = [[1,2,3,4],
[2,3,4,5],
[3,4,5,6],
[4,5,6,7]]
def get_matrix_diagonal(m):
col = len(m)
result = list()
row = 0
for c in range(col):
position = list()
position.append([row,c])
if c > 0:
i = c
while i > 0:
x = i - 1
y = c - i + 1
position.append([y,x])
i -= 1
result.append(position)
row = row + 1
cc = c
for i in range(row,col):
position = list()
y = i
x = c
position.append([y,x])
j = x - y
while j > 0:
y = c - j + 1
x = cc - y + 1
position.append([y,x])
j -= 1
cc += 1
result.append(position)
return result
for ls in get_matrix_diagonal(matrix):
for co in ls:
x,y = co[0],co[1],
print matrix[x][y],
print
Output:
1
2 2
3 3 3
4 4 4 4
5 5 5
6 6
7