I have to create a 2D numpy array from the values x, y from a function return to plot using contourf from matplotlib, and so far I'm using a "C" like structure, that it seems to be very inefficient in Python:
dim_x = np.linspace(self.min_x, self.max_x, self.step)
dim_y = np.linspace(self.min_y, self.max_y, self.step)
X, Y = np.meshgrid(dim_x, dim_y)
len_x = len(dim_x)
len_y = len(dim_y)
a = np.zeros([len_x, len_y], dtype=complex)
for i, y in enumerate(dim_y):
for j, x in enumerate(dim_x):
a[i][j] = aux_functions.final_potential(complex(x, y), element_list)
cs = plt.contourf(X, Y, (a.real), 100)
How can this be done in a more pythonic way?
Thanks!
final_potentialfunction do? What you want to do is "vectorize" that function, rather than writing nested loops.fromfunctionorvectorizeare fine, but they're just as inefficient as your loop.numpytutorials. (e.g. tramy.us/numpybook.pdf Also see scipy-lectures.github.com ) The basic idea is to apply operations to the entire array instead of individual elements. If you'll give an example of yourfinal_potentialfunction, we can help walk you through it. It's usually quite simple, but it might not be immediately obvious if you haven't done it before. In some cases (e.g. finite difference methods) it simply can't be done, but these are relatively rare.sinof each item and if the result is greater than 0, multiplies it by 2, otherwise just returningsin(x). This could be written asresult = np.sin(x); result[result > 0] *= 2, wherexis an array of your values.