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
asked Nov 5, 2016 at 2:18
Maximilian
8,7603 gold badges57 silver badges74 bronze badges
-
I just made an edit. I actually think it makes most sense only for odd sizes. ThanksMaximilian– Maximilian2016年11月05日 06:30:56 +00:00Commented Nov 5, 2016 at 6:30
-
Also, seems relevant : stackoverflow.com/questions/40126853Divakar– Divakar2016年11月05日 12:03:16 +00:00Commented Nov 5, 2016 at 12:03
1 Answer 1
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]])
answered Nov 5, 2016 at 7:13
Divakar
222k19 gold badges273 silver badges374 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py