首页 > 解决方案 > 如何从 (1000, 1) 创建 (1000, 500) 数组并通过 n 值索引?

问题描述

我需要将我的变量 phi、En 和 Cn 变成适当大小的数组。通过从 Matlab 到 python 的转换,我能够在 Matlab 中成功地做到这一点。我将如何进行这个计算。当 n = 1 时,我基本上需要将整个 x 数组相乘,当 n = 2,...,n = 500 时再次相乘,并为 En 和 Cn 获得正确大小的数组。

def Gaussan_wave_packet():

    quantum_number = 500
    x = np.linspace(0,100,1000).astype(complex)
    x0 = 50, a = 10, l = 1
    A = (1/(4*a**2))**(1/4.0)
    m = 0.511*10**6 #mass
    hbar = 6.58211951*10**(-16)
    L = x[-1]

    #Gaussian wave packet
    psi_x0 = np.exp((-(x - x0)**2)/(4*a**2))*np.exp(1j*l*x)

    #Normalize wave function
    A = (1/(np.sqrt(np.trapz((np.conj(psi_x0)*psi_x0),x))))
    psi_x0_normalized = np.outer(psi_x0,A) # Makes a (1000,1) array

    phi_result  = np.array([])
    En_result = np.array([])
    Cn_result = np.array([])

    for n in range(0,quantum_number):

        phi = ( np.sqrt( 2/L ) * np.sin( ( n * x * np.pi )/L ) ) # Needs to be (1000,500)
        En = ( ( np.power(n,2))*(np.pi**2)*(hbar**2))/(2*m*L**2) # Needs to be (1,500)
        Cn = np.trapz( ( np.conj(phi) * psi_x0_normalized ), x ) # Needs to be (1,500)

标签: pythonarraysnumpymultidimensional-array

解决方案


您可以将元素智能乘法与np.multiply(a,b). 并重塑x以使用隐式扩展并避免 for 循环:

n = np.arange(quantum_number)
phi =  np.sqrt(2/L) * np.sin((np.multiply(n,x.reshape(1000,1)*np.pi)/L ))

您可以将相同的逻辑应用于EnCn

matlab 等价物是:

n = 0:(quantum_number-1);
phi = (2/L)^0.5*sin(n.*x.'*pi/L);

推荐阅读