相关疑难解决方法(0)

如何获取numpy数组的线性索引(sub2ind)

Matlab提供的函数sub2ind"返回行和列下标的线性索引等价物......对于矩阵......".

我需要这个sub2ind函数或类似的东西,但我没有找到任何类似的Python或Numpy函数.我该如何获得此功能?

这是matlab文档中的一个示例(与上面相同):

Example 1

This example converts the subscripts (2, 1, 2) for three-dimensional array A 
to a single linear index. Start by creating a 3-by-4-by-2 array A:

rng(0,'twister');   % Initialize random number generator.
A = rand(3, 4, 2)

A(:,:,1) =
    0.8147    0.9134    0.2785    0.9649
    0.9058    0.6324    0.5469    0.1576
    0.1270    0.0975    0.9575    0.9706
A(:,:,2) =
    0.9572    0.1419    0.7922    0.0357
    0.4854    0.4218    0.9595    0.8491
    0.8003    0.9157    0.6557    0.9340

Find the linear index corresponding to …
Run Code Online (Sandbox Code Playgroud)

matlab numpy

15
推荐指数
1
解决办法
1万
查看次数

多维和线性索引之间的Numpy互换

我正在寻找一种在Numpy中线性和多维索引之间进行互换的快速方法.

为了使我的用法具体化,我有一个大的N个粒子集合,每个粒子分配5个浮点值(维度),给出一个Nx5数组.然后,我使用numpy.digitize并使用适当选择的bin边界来对每个维度进行分区,以便为每个粒子分配5维空间中的bin.

N = 10
ndims = 5
p = numpy.random.normal(size=(N,ndims))
for idim in xrange(ndims):
    bbnds[idim] = numpy.array([-float('inf')]+[-2.,-1.,0.,1.,2.]+[float('inf')])

binassign = ndims*[None]
for idim in xrange(ndims):
    binassign[idim] = numpy.digitize(p[:,idim],bbnds[idim]) - 1
Run Code Online (Sandbox Code Playgroud)

然后binassign包含与多维索引对应的行.如果我想将多维索引转换为线性索引,我想我会想做类似的事情:

linind = numpy.arange(6**5).reshape(6,6,6,6,6)
Run Code Online (Sandbox Code Playgroud)

这将查找每个多维索引以将其映射到线性索引.然后你可以回去使用:

mindx = numpy.unravel_index(x,linind.shape)
Run Code Online (Sandbox Code Playgroud)

我遇到困难的地方是弄清楚如何在每行中包含多维索引的binassign(Nx5数组),并将其转换为1d线性索引,方法是使用它来切割线性索引数组linind.

如果有人有一个(或几个)行索引技巧在多维索引和线性索引之间来回传递,其方式是对所有N个粒子进行矢量化操作,我将非常感谢您的见解.

python indexing numpy

5
推荐指数
1
解决办法
3000
查看次数

标签 统计

numpy ×2

indexing ×1

matlab ×1

python ×1