assuming I have any function such as
f(x, y, z) = xyz
what’s the fastest way of calculating every value for f given three linear input arrays x, y, and z?
Of course I can do something along the lines of,
JavaScript
x
11
11
1
import numpy as np
2
3
x = np.linspace(-1., 1., 11)
4
y = np.linspace(-1., 1., 11)
5
z = np.linspace(-1., 1., 11)
6
7
for xi, xx in enumerate(x):
8
for yi, yy in enumerate(y):
9
for zi, zz in enumerate(z):
10
f(xi, yi, zz) = xx*yy*zz
11
but this is probably not the best way to do it, especially if the input arrays become larger. Is there a better way of doing it, such as with a list comprehension (but multidimensional) or any other way? Help is appreciated.
Advertisement
Answer
First create the grid mesh array (x,y,z) as 3-tuples using meshgrid
then you can apply the function in sequence:
JavaScript
1
6
1
import numpy as np
2
x = y = z = np.linspace(-1.0,1.0,11)
3
grid_coordinates = np.array(np.meshgrid(x,y,z)).reshape(-1,3)
4
f = lambda x,y,z : x*y*z
5
f_values = [ f(x,y,z) for x,y,z in grid_coordinates ]
6
A unit test for the f_values
,
JavaScript
1
2
1
f_values[10] == grid_coordinates[10][0]*grid_coordinates[10][1]*grid_coordinates[10][2]
2