矢量化在Numpy循环

时间:2011-12-14 13:11:06

标签: python multidimensional-array numpy

有没有办法对此进行矢量化?

waveheight=zeros(10000)
for t in range(10000):
    for j in range(N_frequencysteps):
        waveheight[t] = waveheight[t] + (Abs_S_newwave[j] * cos (K[j] * x - (omega[j] * ((t*0.01) - TimeShift)) + TSi_omega[j] + arg_S_newwave[j]))

2 个答案:

答案 0 :(得分:5)

waveheight = (Abs_S_newwave[:,None] * cos(K[:,None] * x - (omega[:,None] * ((arange(10000)[None,:]*0.01) - TimeShift)) + TSi_omega[:,None] + arg_S_newwave[:,None])).sum(axis=0)

如果所有长度为N_frequencysteps的数组都是1-D numpy数组,则此方法有效。

答案 1 :(得分:0)

至少有一步向量化不会迭代waveheight的元素:

waveheight=zeros(10000)
ts = arange(10000)
for j in range(N_frequencysteps):
    waveheight += (Abs_S_newwave[j] * cos(K[j] * x - (omega[j] * 
             ((ts*0.01) - TimeShift)) + TSi_omega[j] + arg_S_newwave[j]))

这假设所有其他变量都是标量。