I would like to know how it is possible to obtain the diagonals that point downwards (left and right) with respect to a specific index of the matrix.
To be more graphic I will give the following example of an expected output:
matrix = np.array([[2, 0, 0, 2],
[3, 9, 8, 3],
[3, 0, 0, 2],
[0, 0, 0, 0]])
Expected output results for position: matrix[1][2]
matrix[1][2]
8
diag_right = [2]
diag_left = [0, 0]
Same example but using the matrix in matrix[1][2]
matrix = np.array([[x, x, x, x],
[x, x, 8, x],
[x, 0, x, 2],
[0, x, x, x]])
CodePudding user response:
An easy way using numpy would be: (i've changed the matrix to make more clear some results in test_ij)
import numpy as np
def get_right_left_diags(matrix,i,j):
n = len(matrix)
left_diag = np.diag(matrix[i 1:n,j 1:n])
right_diag = np.diag( matrix[i 1:n, j-1::-1])
return right_diag,left_diag
%lets check some results
matrix = np.array([[2, 0, 0, 2],
[3, 9, 8, 3],
[3, 0, 0, 2],
[1, 2, 3, 4]])
n = len(matrix)
cases = [[0,0],[0,3],[1,1],[1,2],[2,1]]
for i,j in cases:
right_diag,left_diag = get_right_left_diags(matrix,i,j)
print(f"i={i}, j={j}, left_diag: {left_diag} \t right_diag: {right_diag}")
this will output:
#i=0, j=0, left_diag: [9 0 4] right_diag: [3 0 2]
#i=0, j=3, left_diag: [] right_diag: [8 0 1]
#i=1, j=1, left_diag: [0 4] right_diag: [3]
#i=1, j=2, left_diag: [2] right_diag: [0 1]
#i=2, j=1, left_diag: [3] right_diag: [1]
for me it has total sense.
CodePudding user response:
matrix = np.array([[2, 0, 0, 2],
[3, 9, 8, 3],
[3, 0, 0, 2],
[0, 0, 0, 0]])
i = 1; j = 2
diag_right = []; diag_left = []
for k in range(1, len(matrix) - i):
if(j k < len(matrix[0])):
diag_right.append(matrix[i k][j k])
if(j-k >= 0):
diag_left.append(matrix[i k][j-k])
Is this what you're looking for?