Accessing Multidimensional Arrays with Lower-Dimensional Arrays
In multidimensional arrays, retrieving values along a specific dimension using an array of lower dimensionality can be challenging. Consider the example below:
1 2 3 |
|
How can we access the maxima in a using idx as if we had used a.max(axis=0)? How do we retrieve the corresponding values from b?
Elegant Solution Using Advanced Indexing
Advanced indexing provides a flexible way to achieve this:
1 2 3 4 |
|
This solution exploits the fact that the grid [idx, I, J] spans all possible combinations of indices for the remaining dimensions.
Generalization for Arbitrary Dimensionality
For a general n-dimensional array, a function can be defined to generalize the above solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Alternative Indexing Method
Alternatively, a function can be created to generate a grid of indices for all axes:
1 2 3 4 |
|
This grid can then be used to access a multidimensional array with a lower-dimensional array:
1 2 |
|
The above is the detailed content of How to Access Values in Multidimensional Arrays Using Lower- Dimensional Arrays Effectively?. For more information, please follow other related articles on the PHP Chinese website!