GGrewal
GGrewal

Reputation: 177

Vectorizing for loop in Numpy

is there a way to vectorize this?

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

Upvotes: 3

Views: 208

Answers (2)

silvado
silvado

Reputation: 18167

At least one step of vectorization would be not to iterate over the elements of 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]))

This assumes that all other variables are scalars.

Upvotes: 0

eumiro
eumiro

Reputation: 212885

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)

This works if all arrays of length N_frequencysteps are 1-D numpy arrays.

Upvotes: 4

Related Questions