简体   繁体   English

将2D数组放入无循环的if语句-Python

[英]2D array into if statement without loop - Python

I have defined a function which includes an if statement. 我定义了一个包含if语句的函数。 I then want to pass in the X array in the function, which is a 2D array. 然后,我想在函数中传递X数组,它是2D数组。 I tried using np.all, but although it gives no error, it sets ALL the X values to "if abs(x) < L:". 我尝试使用np.all,但尽管它没有错误,但将所有X值都设置为“如果abs(x)<L:”。 How would I be able to pass a 2D array (X) into the function properly? 如何将2D数组(X)正确传递给函数?

x = np.arange(-10.,15.+1.,1.)
y = np.arange(-4.,4.+0.1,0.1)
eps = 0.1
L = 2.
k = np.pi/(2.*L)

def q2(x):
    if abs(x) < L:
        return (((-3.*eps*np.cos(k*x))+(k*(np.sin(k*x)-np.exp(3.*eps*(x-L)))))/((9.*eps**2.) + k**2.))
    if x > L:
        return 0.
    if x < -L:
        return (-k*(1.+np.exp2(-6.*eps*L))*np.exp(3.*eps*(x+L)))/((9.*eps**2.) + k**2.)

def u2(x,y):
    return 0.5*q2(x)*(y**2. - 3.)*np.exp(-0.25*y**2.)

X,Y = np.meshgrid(x,y)
vel_x=u2(X,Y)

You can use numpy.where(CONDITION) to get an array of indices, which can be used to access only those parts of x you are currently interested in: 您可以使用numpy.where(CONDITION)获取一个索引数组,该索引数组只能用于访问您当前感兴趣的x那些部分:

def q2(x):

    q = np.zeros(x.shape)

    # for abs(x) < L
    ind = np.where(np.abs(x) < L)
    q[ind] = (((-3.*eps*np.cos(k*x[ind]))+(k*(np.sin(k*x[ind])-np.exp(3.*eps*(x[ind]-L)))))/((9.*eps**2.) + k**2.))

    # for x < -L
    ind = np.where(x < -L)
    q[ind] = (-k*(1.+np.exp2(-6.*eps*L))*np.exp(3.*eps*(x[ind]+L)))/((9.*eps**2.) + k**2.)

    return q

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

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