Consider the followoing example from np.meshgrid docs:
JavaScript
x
5
1
nx, ny = (3, 2)
2
x = np.linspace(0, 1, nx)
3
y = np.linspace(0, 1, ny)
4
xv, yv = np.meshgrid(x, y)
5
In my application, instead of x
and y
, I’ve 25 variables. To create a grid out of the 25 variables, one way would be:
JavaScript
1
7
1
v1 = np.linspace(0, 1, 10)
2
v2 = np.linspace(0, 1, 10)
3
4
v25 = np.linspace(0, 1, 10)
5
6
z_grid = np.meshgrid(v1, v2, , v25)
7
However, the code will look ugly and not modular w.r.t. the number of variables (since each variable is hard-coded). Therefore, I am interested in something like the following:
JavaScript
1
4
1
n_variables = 25
2
z = np.array([np.linspace(0, 1, 10)] * n_variables)
3
z_grid = np.dstack(np.meshgrid(z))
4
However, I am guessing meshgrid(z)
is not the correct call, and I should expand z
to n_variables
arrays. Any thoughts on how I can expand the 2D array into multiple 1D arrays?
Advertisement
Answer
this should do it.
JavaScript
1
4
1
n_variables = 25
2
z = np.array([np.linspace(0, 1, 10)] * n_variables)
3
z_grid = np.dstack(np.meshgrid(*z))
4
the * operator before list, unpacks list elements. consider following:
JavaScript
1
5
1
v1 = [1,2,3]
2
v2 = [4,5,6]
3
list_of_v = [v1,v2]
4
some_fucntion(v1,v2) == some_function(*list_ov_v)
5