2011-12-14 102 views
3

有沒有一種方法來實現這個向量化?向量化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])) 

回答

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的陣列。矢量化

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])) 

這假定所有的其它變量是標量。