Search code examples
pythonnumpymachine-learningpytorchneural-network

Get directional elements in matrix


Lets suppose that I have a point of interest in my matrix that is NxN. The point is located in the position ij. So, given the index ij, is there a simple way to get the line elements passing trough ij and to the origin (that is located in the middle of the matrix) ?

I am using torch and I though that using torch.diag would be a first start but acttualy this function does not pass in the middle of the matrix.

def directionalK(kx,ky, indices):
    '''Function that provides the K values at a given direction dictated by the indices'''
    kx_grid,ky_grid = torch.meshgrid(kx,kx, indexing='ij')
    k_grid = torch.sqrt(kx_grid**2 + ky_grid**2) 
    k_grid[...,:len(k_grid)//2] *=-1 
    y,x = indices
    diag = x - len(k_grid)//2

Solution

  • I think you could solve this using the skimage.draw.line method where you input the starting (i,j) and ending (0,0) coordinates and it calculates the indices belonging to the line which you can use for indexing.

    Worked example:

    from skimage.draw import line
    import numpy as np
    import matplotlib.pyplot as plt
    arr = np.zeros((100, 100))
    i, j = 10, 80
    origin = 50, 50
    rr, cc = line(*origin, i, j)
    arr[rr, cc] = 1
    plt.imshow(arr, cmap='gray', interpolation='nearest')
    

    Gray plot showing the line

    Or if you want the line to continue:

    arr = np.zeros((100, 100))
    rr, cc = line(i, j, 2*origin[0]-i, 2*origin[1]-j)
    arr[rr, cc] = 2
    plt.imshow(arr, cmap='gray', interpolation='nearest')
    

    Longer line