1

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
2
  • I just made an edit. I actually think it makes most sense only for odd sizes. Thanks Commented Nov 5, 2016 at 6:30
  • Also, seems relevant : stackoverflow.com/questions/40126853 Commented Nov 5, 2016 at 12:03

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.