简体   繁体   English

功能变化不大。 面具。 蟒蛇

[英]Little change in a function. Mask. Python

I have the following function: 我有以下功能:

def delta(r, dr):
   res = np.zeros(r.shape)
   mask1 = (r >= 0.5*dr) & (r <= 1.5*dr)
   res[mask1] = (5-3*np.abs(r[mask1])/dr \
    - np.sqrt(-3*(1-np.abs(r[mask1])/dr)**2+1))/(6*dr)
   mask2 = np.logical_not(mask1) & (r <= 0.5*dr)
   res[mask2] = (1+np.sqrt(-3*(r[mask2]/dr)**2+1))/(3*dr)
   return res

Where r is a numpy.array of size (shape[0],shape[1]) and dr is a single value. 其中r是大小为(shape[0],shape[1])numpy.arraydr是单个值。 I want to modify the function to make dr also an array of the same size as r and for each value of r take the analogous value from dr . 我要修改的功能,使dr也相同的尺寸的阵列r和用于的每个值r采取从类似值dr

For example r[0,0] goes with dr[0,0] , r[0,1] with dr[0,1] and so on. 例如, r[0,0]dr[0,0]r[0,1]dr[0,1] ,依此类推。 Any ideas? 有任何想法吗?

You could multiply the 2D mask with the input array, which in effect is masking and thus perform the computations resulting in a 2D array instead of 1D array with boolean indexing as done so far. 您可以将2D蒙版与输入数组相乘,后者实际上是蒙版,因此执行计算会产生2D数组,而不是到目前为止具有布尔索引的1D数组。 The only difference would be setting values into the output array, for which you need to mask both the array to be set and the 2D computed array from which values would be selected. 唯一的区别是将值设置到输出数组中,为此您需要屏蔽要设置的数组和要从中选择值的2D计算数组。

The implementation would look like this - 实现看起来像这样-

# Initialize output array   
res = np.zeros(r.shape)

# Get mask1 and compute values for all elements and use the mask to set only
# TRUE positions with the computed values
mask1 = (r >= 0.5*dr) & (r <= 1.5*dr)
V1 = (5-3*np.abs(r*mask1)/dr - np.sqrt(-3*(1-np.abs(r*mask1)/dr)**2+1))/(6*dr)
res[mask1] = V1[mask1]

# Similarly for mask2 and the computations with that mask
mask2 = np.logical_not(mask1) & (r <= 0.5*dr)
V2 = (1+np.sqrt(-3*(r*mask2/dr)**2+1))/(3*dr)
res[mask2] = V2[mask2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM