Given a numpy array like:
L = 2
np.random.randint([-1,1],size=(L,L), dtype=int)
array([[1, -1],
[-1, 1]])
How can I transform it into an array of similar shape (efficiently)
np.random.choice([-1, 1], size=(2,2,4))
array([[[-1, -1, 1, 1],
[-1, -1, 1, -1]],
[[-1, 1, -1, 1],
[ 1, -1, 1, 1]]])
But unlike shown here where the 3rd dimension is random to contain the 4 neighbors in it (0-padded on the corners).
I.e.
[[1, -1], [-1, 1]]
has for the first element a neighborhood of:
- 0, 0, -1,-1,
- for the second 1,0, 0, 1 and so on.
I want to store this neighborhood vector into the 3rd dimension of the matrix.
Is this possible without manually looping the matrix?
edit
For the example of:
[[1, -1], [-1, 1]]
[[[0,0,-1-1], [1,0,0,1]],
...]
You can try the following:
It gives:
Compute the array of neighbors:
Then, for example
out[2, 1]is[4, 0, 6, 8]i.e. the array of neighbors ofa[2, 1]in the[up, down, left, right]order (with 0 padding).