I have an equidistant two-dimensional grid with N points, so n x n size. I want to create a NxN distance matrix D where element D_ij is the distance between point i and point j.
E.g matrix [[a b],[c d]] should have distance matrix [[0 1 1 1.414],[1 0 1.1.414 1], [1 1.414 0 1],[1.414 1 1 0]].
I have done this in a very brute force way, shown below
N=2**2
n=int(np.sqrt(N))
row = np.arange(0,n)
grid = np.tile(row,n)
#East matrix. For each point, the matrix yields the distance in the x direction(east) to the other points. The first row covers each point in the first row in the grid, and so on.
D_E = np.zeros((N,N))
for i in range(N):
for j in range(N):
D_E[i,j] = grid[j]-grid[i]
#Same logic as above, but this time in the y_direction
D_S = np.zeros((N,N))
row2 = np.arange(0,n)
grid2 = np.repeat(row2,n)
for i in range(N):
for j in range(N):
D_S[i,j] = grid2[j]-grid2[i]
D = np.sqrt(D_E**2 + D_S**2)
Is there any better way to do this, perhaps more pythonic that I have not thought about?
PS.
I can add that the main goal in the end is to create a covariance matrix for the grid, using the distance matrix D to create the N x N covariance matrix, since each element in the covariance matrix is decided by the covariance function which inputs the euclidian distance between points in the grid.