Home  >  Article  >  Backend Development  >  How to Access Values in Multidimensional Arrays Using Lower- Dimensional Arrays Effectively?

How to Access Values in Multidimensional Arrays Using Lower- Dimensional Arrays Effectively?

Barbara Streisand
Barbara StreisandOriginal
2024-10-21 13:34:02286browse

How to Access Values in Multidimensional Arrays Using Lower- Dimensional Arrays Effectively?

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:

<code class="python">a = np.random.random_sample((3,4,4))
b = np.random.random_sample((3,4,4))
idx = np.argmax(a, axis=0)</code>

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:

<code class="python">m, n = a.shape[1:]  # Extract dimensions excluding axis 0
I, J = np.ogrid[:m, :n]
a_max_values = a[idx, I, J]  # Index using the grid
b_max_values = b[idx, I, J]</code>

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:

<code class="python">def argmax_to_max(arr, argmax, axis):
    """
    Apply argmax() operation along one axis to retrieve maxima.

    Args:
        arr: Array to apply argmax to
        argmax: Resulting argmax array
        axis: Axis to apply argmax (0-based)
    Returns:
        Maximum values along specified axis
    """
    new_shape = list(arr.shape)
    del new_shape[axis]

    grid = np.ogrid[tuple(map(slice, new_shape))]  # Create grid of indices
    grid.insert(axis, argmax)

    return arr[tuple(grid)]</code>

Alternative Indexing Method

Alternatively, a function can be created to generate a grid of indices for all axes:

<code class="python">def all_idx(idx, axis):
    grid = np.ogrid[tuple(map(slice, idx.shape))]
    grid.insert(axis, idx)
    return tuple(grid)</code>

This grid can then be used to access a multidimensional array with a lower-dimensional array:

<code class="python">a_max_values = a[all_idx(idx, axis=axis)]
b_max_values = b[all_idx(idx, axis=axis)]</code>

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn