簡體   English   中英

將2D數組放入無循環的if語句-Python

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

我定義了一個包含if語句的函數。 然后,我想在函數中傳遞X數組,它是2D數組。 我嘗試使用np.all,但盡管它沒有錯誤,但將所有X值都設置為“如果abs(x)<L:”。 如何將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)

您可以使用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