To investigate the numerical behavior of a six-parameter function, you seek an efficient method to traverse its parameter space. Initially, you employed a custom function to combine array values, followed by reduce() to apply it repeatedly. While functional, this approach proved cumbersome.
Newer versions of NumPy (1.8.x and above) offer a far superior solution: numpy.meshgrid(). This function enables the creation of multidimensional arrays comprising all possible combinations of input arrays. In your case:
import numpy as np a = np.arange(0, 1, 0.1) combinations = np.array(np.meshgrid(a, a, a, a, a, a)).T.reshape(-1, 6)
This approach significantly enhances performance, as demonstrated by the following benchmark:
%timeit np.array(np.meshgrid(a, a, a, a, a, a)).T.reshape(-1, 6) # Output: 10000 loops, best of 3: 74.1 µs per loop
Alternatively, you could use the following custom function for maximum control:
def cartesian(arrays): arr = np.empty((len(arrays.shape), len(arrays))) for n, array in enumerate(arrays): arr[n, :] = array return arr.T.reshape(-1, len(arrays)) %timeit cartesian([a, a, a, a, a, a]) # Output: 1000 loops, best of 3: 135 µs per loop
The above is the detailed content of How Can NumPy's `meshgrid` Function Efficiently Generate All Combinations of Array Values?. For more information, please follow other related articles on the PHP Chinese website!