Say for example, I have a Numpy 2D array (7 rows, 7 columns) filled with zeros:
my_ array = numpy.zeros((7, 7))
Then for sake of argument say that I want to select the element in the middle and set its value to 1:
my_array[3,3] = 1
Now say that I have been given a Manhattan distance of 3, how do I subset my array to only select the elements that are less than or equal to the Manhattan distance (from the middle element) and set those elements to 1? The end result should be:
I could iterate through each element in the the 2D array but do not want to do this as this is too expensive, especially if my matrix is very large and the Manhattan distance is very small (for example 70x70 matrix with Manhattan distance of 10).
CodePudding user response:
I would create an auxiliar matrix of size 2,n,n with meshgrid to almacenate the index, then substract the desired index center, sum absolute value of index substracted and put a threshold comparation. Here some example
import numpy as np
import matplotlib.pyplot as plt #to draw result
n=70 #size of matrix
distance = 10 #distance
centerCoord = [35,35]
#here i create a mesh matrix of indices
xarr = np.arange(n)
idxMat = np.meshgrid(xarr,xarr) #create a matrix [2,n,n]
pt = np.array(centerCoord).reshape(-1,1,1) #point of size [2,1,1]
elems = np.abs(idxMat-pt).sum(axis=0) <= distance
plt.matshow(elems)
the result:
If you need indices then call np.where
that will return you 2 arrays (xindexList,yindexList)