Reputation: 8530
I think this should be easy, but I'm not sure of an efficient way to do it.
I'd like to build a matrix in numpy that has the cityblock / manhattan closeness to the center of the matrix, in numpy, for any odd size.
For a size of 5, the output would be:
array([[0, 1, 2, 1, 0],
[1, 2, 3, 2, 1],
[2, 3, 4, 3, 2],
[1, 2, 3, 2, 1],
[0, 1, 2, 1, 0]])
What's the best way of doing this? Thanks
Upvotes: 1
Views: 127
Reputation: 221774
Easy and efficient with broadcasting
-
def closeness_manhattan(N):
r = np.arange(N)
a = np.minimum(r,r[::-1])
return a[:,None] + a
Sample runs -
In [14]: closeness_manhattan(4)
Out[14]:
array([[0, 1, 1, 0],
[1, 2, 2, 1],
[1, 2, 2, 1],
[0, 1, 1, 0]])
In [15]: closeness_manhattan(5)
Out[15]:
array([[0, 1, 2, 1, 0],
[1, 2, 3, 2, 1],
[2, 3, 4, 3, 2],
[1, 2, 3, 2, 1],
[0, 1, 2, 1, 0]])
Upvotes: 3