1

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:

end result

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).

Woodford
  • 3,746
  • 1
  • 15
  • 29

1 Answers1

3

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:

enter image description here

If you need indices then call np.where that will return you 2 arrays (xindexList,yindexList)

Ulises Bussi
  • 1,635
  • 1
  • 2
  • 14
  • it's faster than the double for if the size N is bigger than 50 (the change is between 20 and 50) about 10x faster – Ulises Bussi Nov 05 '21 at 17:39
  • Hi, thanks for the answer! I will try this on my jupyter notebook and get back to you with feedback :) – datum_analyser Nov 05 '21 at 17:52
  • hope it helps! I have some code testing speeds. remember if you want to access the original matrix you could use `elems` as a mask like `matrix[elems]` if you want to get the indices then dot `id_x,id_y = np.where(elems)` and then `indices = np.array([id_x,id_y]).T` then you have the pairs by `indices[0], indices[1],.... ` – Ulises Bussi Nov 05 '21 at 17:55
  • Excellent!! This solved my problem. Thank you so much :) – datum_analyser Nov 07 '21 at 01:24