I have,
arr_x = np.arange(.1, .9, 1/125)
arr_y = np.arange(.1, .9, 1/125)
mx, my = np.meshgrid(arr_x, arr_y, sparse = True)
L = [0,1,2,3]
Meval = mx my
How do I make it so that Meval
keeps the structure of the coordinate grid, but Meval
is 0 whenever (x,y) is not a member of arr_x[L]
cross_product arr_y[L]
; as in, I want conditional evaluation, I know I can do this easily with a for loop but apparently that is "slower" than doing it the vectorized way with numpy.meshgrid
.
Thanks!
CodePudding user response:
IIUC, you can make a mask the same way you make mx
, my
, and then use the mask to set values to 0:
xmask = np.ones(len(arr_x),bool)
ymask = np.ones(len(arr_y),bool)
xmask[L] = False
ymask[L] = False
#e.g.
#arr_x :
#array([0.1 , 0.108, 0.116, 0.124, 0.132, 0.14 , 0.148, 0.156, 0.164,
# 0.172, 0.18 , 0.188, 0.196, 0.204, 0.212, 0.22 , 0.228, 0.236,
# 0.244, 0.252, 0.26 , 0.268, 0.276, 0.284, 0.292, 0.3 , 0.308,
# 0.316, 0.324, 0.332, 0.34 , 0.348, 0.356, 0.364, 0.372, 0.38 ,
# 0.388, 0.396, 0.404, 0.412, 0.42 , 0.428, 0.436, 0.444, 0.452,
# 0.46 , 0.468, 0.476, 0.484, 0.492, 0.5 , 0.508, 0.516, 0.524,
# 0.532, 0.54 , 0.548, 0.556, 0.564, 0.572, 0.58 , 0.588, 0.596,
# 0.604, 0.612, 0.62 , 0.628, 0.636, 0.644, 0.652, 0.66 , 0.668,
# 0.676, 0.684, 0.692, 0.7 , 0.708, 0.716, 0.724, 0.732, 0.74 ,
# 0.748, 0.756, 0.764, 0.772, 0.78 , 0.788, 0.796, 0.804, 0.812,
# 0.82 , 0.828, 0.836, 0.844, 0.852, 0.86 , 0.868, 0.876, 0.884,
# 0.892])
#xmask:
#array([False, False, False, False, True, True, True, True, True,
# True, True, True, True, True, True, True, True, True,
# True, True, True, True, True, True, True, True, True,
# True, True, True, True, True, True, True, True, True,
# True, True, True, True, True, True, True, True, True,
# True, True, True, True, True, True, True, True, True,
# True, True, True, True, True, True, True, True, True,
# True, True, True, True, True, True, True, True, True,
# True, True, True, True, True, True, True, True, True,
# True, True, True, True, True, True, True, True, True,
# True, True, True, True, True, True, True, True, True,
# True])
mx_mask, my_mask = np.meshgrid(xmask, ymask, sparse=True)
M = mx my
#M:
#array([[0.2 , 0.208, 0.216, ..., 0.976, 0.984, 0.992],
# [0.208, 0.216, 0.224, ..., 0.984, 0.992, 1. ],
# [0.216, 0.224, 0.232, ..., 0.992, 1. , 1.008],
# ...,
# [0.976, 0.984, 0.992, ..., 1.752, 1.76 , 1.768],
# [0.984, 0.992, 1. , ..., 1.76 , 1.768, 1.776],
# [0.992, 1. , 1.008, ..., 1.768, 1.776, 1.784]])
M_mask = mx_mask my_mask
M[M_mask] = 0
#M:
#array([[0.2 , 0.208, 0.216, ..., 0. , 0. , 0. ],
# [0.208, 0.216, 0.224, ..., 0. , 0. , 0. ],
# [0.216, 0.224, 0.232, ..., 0. , 0. , 0. ],
# ...,
# [0. , 0. , 0. , ..., 0. , 0. , 0. ],
# [0. , 0. , 0. , ..., 0. , 0. , 0. ],
# [0. , 0. , 0. , ..., 0. , 0. , 0. ]])