How to Access Multidimensional Arrays with Fewer Dimensions?

Linda Hamilton
Release: 2024-10-21 11:32:02
Original
908 people have browsed it

How to Access Multidimensional Arrays with Fewer Dimensions?

Accessing Multidimensional Arrays with Fewer Dimensions

Consider an n-dimensional array, such as a, and an (n-1)-dimensional array, idx. To access a using idx along a given dimension, we can employ advanced indexing.

For a 3-dimensional array a, we can calculate the maximum values along the first dimension using idx as follows:

<code class="python">m, n = a.shape[1:]
I, J = np.ogrid[:m, :n]
a_max_values = a[idx, I, J]</code>
Copy after login

This approach can be generalized for arrays with any number of dimensions:

<code class="python">def argmax_to_max(arr, argmax, axis):
    new_shape = list(arr.shape)
    del new_shape[axis]
    grid = np.ogrid[tuple(map(slice, new_shape))]
    grid.insert(axis, argmax)
    return arr[tuple(grid)]</code>
Copy after login

To index an n-dimensional array with an (n-1)-dimensional array, we can create 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>
Copy after login

Using this grid, we can index into the input arrays:

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

This approach provides an elegant solution for accessing multidimensional arrays with fewer dimensions.

The above is the detailed content of How to Access Multidimensional Arrays with Fewer Dimensions?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!