Issue
Let's say I have a 5x5 matrix as follows:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Based on some location, I am given an index in both the (x,y) coordinate where I want to start building concentric squares outwards of values. A few examples below:
3 3 3 3 3
3 2 2 2 2
3 2 1 1 2
3 2 1 1 2
3 2 2 2 2
2 2 2 3 4
1 1 2 3 4
1 1 2 3 4
2 2 2 3 4
3 3 3 3 4
Is there a more automated / function / libraries that can do this easily instead of hard-coding these sort of values?
Solution
Not sure of the exact logic, but assuming x
, y
the coordinates of the top left corner of the square of 1s, you could craft a vertical and horizontal array with numpy.where
and combine them with broadcasting and numpy.maximum
:
x, y = 2, 2
N = 5
Xs = np.arange(N)-x
Ys = np.arange(N)-y
out = np.maximum(np.where(Xs>0, Xs, 1-Xs)[:, None],
np.where(Ys>0, Ys, 1-Ys)
)
Output:
array([[3, 3, 3, 3, 3],
[3, 2, 2, 2, 2],
[3, 2, 1, 1, 2],
[3, 2, 1, 1, 2],
[3, 2, 2, 2, 2]])
Output for x = 1 ; y = 0 ; N = 6
:
array([[2, 2, 2, 3, 4, 5],
[1, 1, 2, 3, 4, 5],
[1, 1, 2, 3, 4, 5],
[2, 2, 2, 3, 4, 5],
[3, 3, 3, 3, 4, 5],
[4, 4, 4, 4, 4, 5]])
Intermediates (x = 5 ; y = 5 ; N = 5
):
# Xs
array([-2, -1, 0, 1, 2])
# np.where(Xs>0, Xs, 1-Xs)[:, None]
array([[3],
[2],
[1],
[1],
[2]])
# Ys
array([-2, -1, 0, 1, 2])
# np.where(Ys>0, Ys, 1-Ys)
array([3, 2, 1, 1, 2])
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.