我需要模拟 MATLAB 函数 find
,它返回数组非零元素的线性索引。例如:
>> a = zeros(4,4)
a =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
>> a(1,1) = 1
>> a(4,4) = 1
>> find(a)
ans =
1
16
numpy 具有类似的函数 nonzero
,但它返回索引数组的元组。例如:
In [1]: from numpy import *
In [2]: a = zeros((4,4))
In [3]: a[0,0] = 1
In [4]: a[3,3] = 1
In [5]: a
Out[5]:
array([[ 1., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 1.]])
In [6]: nonzero(a)
Out[6]: (array([0, 3]), array([0, 3]))
是否有一个函数可以在不自己计算的情况下为我提供线性指数?
最佳答案
numpy 是否涵盖了您:
>>> np.flatnonzero(a)
array([ 0, 15])
在内部,它完全按照 Sven Marnach 的建议行事。
>>> print inspect.getsource(np.flatnonzero)
def flatnonzero(a):
"""
Return indices that are non-zero in the flattened version of a.
This is equivalent to a.ravel().nonzero()[0].
[more documentation]
"""
return a.ravel().nonzero()[0]
关于matlab - 在numpy中获取线性化索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11210070/