numpy数组中相邻值的加权和

时间:2013-02-10 18:09:42

标签: python numpy python-3.x scipy weighted

在numpy数组中采用加权值的最简单/最快的方法是什么?

示例:使用Euler方法求解热方程

length_l=10
time_l=10
u=zeros((length_l,length_l))# (x,y)
u[:, 0]=1
u[:,-1]=1
print(u)
def dStep(ALPHA=0.1):
    for position,value in ndenumerate(u):
        D2u= (u[position+(1,0)]-2*value+u[position+(-1, 0)])/(1**2) \
            +(u[position+(0,1)]-2*value+u[position+( 0,-1)])/(1**2)
        value+=ALPHA*D2u()
while True:
    dStep()
    print(u)

D2u应该是二维的第二个中心差异。如果我可以添加(1,4)+(1,3)=(2,7)之类的索引,这将有效。不幸的是,python将它们添加为(1,4)+(1,3)=(1,4,1,3)

请注意,计算D2u相当于使用此内核围绕当前位置获取点积:

 0, 1, 0
 1,-4, 1
 0, 1, 0

这可以作为点积进行矢量化吗?

1 个答案:

答案 0 :(得分:3)

我想你想要这样的东西:

import numpy as np
from scipy.ndimage import convolve

length_l = 10
time_l = 10
u = np.zeros((length_l, length_l))# (x,y)
u[:,  0] = 1
u[:, -1] = 1

alpha = .1
weights = np.array([[ 0,  1,  0],
                    [ 1, -4,  1],
                    [ 0,  1,  0]])

for i in range(5):
    u += alpha * convolve(u, weights)
    print(u)

你可以通过以下方式减少一点:

weights = alpha * weights
weights[1, 1] = weights[1, 1] + 1

for i in range(5):
    u = convolve(u, weights)
    print(u)