【问题标题】:Indices in Numpy and MATLABNumpy 和 MATLAB 中的索引
【发布时间】:2021-07-23 13:54:23
【问题描述】:

我在 Matlab 中有一段代码要转换成 Python/numpy。

我有一个矩阵ind,其尺寸为 (32768, 24)。我有另一个矩阵X,其尺寸为 (98304, 6)。当我执行操作时

result = X(ind)

矩阵的形状是(32768, 24)。

但是当我执行相同的形状时在 numpy 中

result = X[ind]

我得到result 矩阵的形状为 (32768, 24, 6)。

如果有人能帮助我解释为什么我可以得到这两种不同的结果以及如何解决它们,我将不胜感激。我也想在 numpy 中获得 result 矩阵的形状 (32768, 24)

【问题讨论】:

  • 在 numpy 的情况下,ind 仅适用于第一个维度,例如X[ind,:]
  • @hpaulj 这在这种情况下没有任何作用。即使我按照您的建议进行操作,我仍然会得到相同的结果。
  • 我没有提出任何建议!
  • MATLAB 到底在做什么? ind 的值是多少(相对于X 的形状)?我过去的 MATLAB 编码很好,所以我无法完全想象这个动作。我可以启动 Octave 并做一些实验,但我更喜欢你解释一下。

标签: numpy matlab array-indexing


【解决方案1】:

在 Octave 中,如果我定义:

>> X=diag([1,2,3,4])
X =

Diagonal Matrix

   1   0   0   0
   0   2   0   0
   0   0   3   0
   0   0   0   4

>> idx = [6 7;10 11]      
idx =

    6    7
   10   11

然后索引选择一个块:

>> X(idx)
ans =

   2   0
   0   3

numpy 等效项是

In [312]: X=np.diag([1,2,3,4])
In [313]: X
Out[313]: 
array([[1, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4]])
In [314]: idx = np.array([[5,6],[9,10]])   # shifted for 0 base indexing
In [315]: np.unravel_index(idx,(4,4))      # raveled to unraveled conversion
Out[315]: 
(array([[1, 1],
        [2, 2]]),
 array([[1, 2],
        [1, 2]]))
In [316]: X[_]         # this indexes with a tuple of arrays
Out[316]: 
array([[2, 0],
       [0, 3]])

另一种方式:

In [318]: X.flat[idx]
Out[318]: 
array([[2, 0],
       [0, 3]])

【讨论】:

  • 非常感谢。非常感谢您的帮助
猜你喜欢
  • 2014-01-08
  • 2014-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多