I have a double for loop among all the grid, and I want to make it work faster.
r, vec1, vec2, theta are the vectors of the same length N. c is a constant.
import numpy as np
N = 30
x_coord, y_coord = 300, 300
m1 = np.zeros((x_coord, y_coord))
vec1, vec2 = np.ones(N), np.ones(N)
theta = np.ones(N)
for x in np.arange(x_coord):
for y in np.arange(y_coord):
m1[x,y] = np.sum(np.cos(2.*np.pi*(r*(vec1*x + vec2*y))+theta)) * c
The time for two loops was:
1.03 s ± 8.96 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Also I tried to use np.meshgrid:
def f1(x, y):
sum1 = vec1*x + vec2*y
mltpl1 = r * sum1
sum2 = 2.*np.pi * mltpl1 + theta
sum3 = np.sum(np.cos(sum2))
mltpl2 = sum3 * c
return mltpl2
msh1, msh2 = np.meshgrid(range(x_coord), range(y_coord))
pairs = np.vstack((np.ravel(msh1), np.ravel(msh2))).T
m1 = np.reshape(list(map(lambda x: f1(x[0], x[1]), pairs)), (m1.shape[0], m1.shape[1])).T
Trying meshgrid time was more:
1.25 s ± 48.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
So I need a solution how to do it on a vectors and matrices level. Are there any ideas? Thank you in advance.