You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

任意维度Numpy数组顺序索引实现方法问询(保留网格结构)

Sequentially Indexing Points in a Numpy mgrid Array (Any Dimension n)

Great question! You absolutely can index points in a numpy mgrid array sequentially for any dimension n without reshaping it (which would break the grid structure you need). Let's break down how this works, using your n=4 example as a guide.

Understanding the mgrid Array Structure

First, let's clarify what np.mgrid[[slice(0,11,1)]*4] produces: it's a 5-dimensional array with shape (4, 11, 11, 11, 11). The first dimension holds the coordinate components (x, y, z, w for n=4), and the remaining 4 dimensions are the grid itself—each position corresponds to a unique point in 4D space.

Core Solution: Use np.unravel_index to Convert Linear Indices

Numpy's np.unravel_index function is perfect here. It converts a linear index (like 0, 1, 11, or 14640) into the multi-dimensional index that maps to the same position in the grid. Since mgrid generates grids in C-order (row-major) (meaning the last dimension changes fastest), this matches the default behavior of np.unravel_index.

Step-by-Step for Your n=4 Example

For any linear index k, follow these steps:

  1. Calculate the multi-dimensional index using np.unravel_index(k, (11,)*4) (the second argument is a tuple representing the size of each grid dimension, 11 in your case).
  2. Use this multi-dimensional index to slice all coordinate components from A with A[:, *unraveled_index].

Let's test this with your examples:

  • First point (k=0):

    idx = np.unravel_index(0, (11,)*4)
    A[:, *idx]  # Equivalent to A[:, 0, 0, 0, 0]
    

    Output: array([0, 0, 0, 0])

  • Second point (k=1):

    idx = np.unravel_index(1, (11,)*4)
    A[:, *idx]  # Equivalent to A[:, 0, 0, 0, 1]
    

    Output: array([0, 0, 0, 1])

  • 12th point (k=11):

    idx = np.unravel_index(11, (11,)*4)
    A[:, *idx]  # Equivalent to A[:, 0, 0, 1, 0]
    

    Output: array([0, 0, 1, 0])

  • Last point (k=14640):

    idx = np.unravel_index(14640, (11,)*4)
    A[:, *idx]  # Equivalent to A[:, 10, 10, 10, 10]
    

    Output: array([10, 10, 10, 10])

Generalizing to Any n

This approach works for any dimension n and any grid size. For example, if you have a 3D grid with each dimension spanning 0 to 4 (size 5):

grid_size = 5
n = 3
A = np.mgrid[[slice(0, grid_size, 1)]*n]
k = 7  # Linear index we want to map
idx = np.unravel_index(k, (grid_size,)*n)
print(A[:, *idx])  # Output: array([0, 1, 2])

Why This Works Without Reshaping

Crucially, this method doesn't modify the original mgrid array at all—we're just using index conversion to access the points sequentially. The grid structure (and its original shape) remains intact, exactly as you need.

内容的提问来源于stack exchange,提问作者jmlarson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:06:03