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!
It would be ideal if you could rewrite
final_potentialas a vectorized function. A simple and, perhaps, too-obvious example:But if you really can’t do that, you could also
vectorize:In your case, it would probably look something like this:
This will probably be a bit faster than nested
forloops, although the overhead of a python function call will negate a lot of numpy’s efficiency. In tests I’ve done in the past, usingvectorizeprovided a modest 5x speedup. (That’s compared to a 100x or 1000x speedup for pure numpy operations, as in theX * Yexample.)