In built or module function that can create a point source nxn array?

Viewed 39

Just wondering if there's a function that can produce an nxn array where the centre has the maximum value, and the edges have a value of 0 like so:

0 0 0 0 0 0 0
0 1 1 1 1 1 0
0 1 2 2 2 1 0
0 1 2 3 2 1 0
0 1 2 2 2 1 0
0 1 1 1 1 1 0
0 0 0 0 0 0 0

Would be nice if there was something similar to np.arange where I can just insert n and get an array like the one above, but I'm not too hopeful.

1 Answers

I don't think there is a built-in for this. But you can build one:

def get_center(size):
    a = np.minimum(np.arange(size), size - 1 - np.arange(size))
    return np.minimum(a, a[:,None])

get_center(7)

Out:

array([[0, 0, 0, 0, 0, 0, 0],
       [0, 1, 1, 1, 1, 1, 0],
       [0, 1, 2, 2, 2, 1, 0],
       [0, 1, 2, 3, 2, 1, 0],
       [0, 1, 2, 2, 2, 1, 0],
       [0, 1, 1, 1, 1, 1, 0],
       [0, 0, 0, 0, 0, 0, 0]])
Related