【问题标题】:Indexing a vector with a matrix of indicies with numpy, similar to MATLAB使用 numpy 使用索引矩阵对向量进行索引,类似于 MATLAB
【发布时间】:2020-04-28 22:26:39
【问题描述】:

我想从用索引矩阵索引的向量中提取一个填充了值的矩阵
output(i, j) = vector(indices(i, j))

在 Matlab 中,这可以通过output = vector(indices) 来实现。

在 Python/numpy 中,我为此目的使用了以下循环,但我想知道是否有更有效的方法:

    idx = np.random.randint(0, 100, (25, 10))
    data = np.random.random(100)
    output = np.empty((np.size(idx, 0), np.size(idx, 1)))
    for i in range(0, np.size(idx, 0)):
        output[i, :] = np.squeeze(data[idx[i, :]])

非常感谢

【问题讨论】:

    标签: python matlab numpy matrix indexing


    【解决方案1】:
    Output=vector[x, y]
    

    XY 是您选择的坐标。 同样,如果你想指定一个区间:

    Output=vector[X1:X2, Y1:Y2]
    

    只需[] 而不是()

    【讨论】:

    • 非常感谢您的回答 Bans Akin。除非我误解了您的建议,否则我不想从二维数组中索引 [X, Y] 坐标。相反,我想使用二维数组中的索引迭代地索引一维数组,输出到相应的二维数组中。
    【解决方案2】:
    In [547]: idx = np.random.randint(0, 100, (25, 10)) 
         ...: data = np.random.random(100) 
         ...: output = np.empty((np.size(idx, 0), np.size(idx, 1))) 
         ...: for i in range(0, np.size(idx, 0)): 
         ...:    output[i, :] = np.squeeze(data[idx[i, :]]) 
    
    In [553]: idx.shape                                                                                       
    Out[553]: (25, 10)
    In [554]: output.shape                                                                                    
    Out[554]: (25, 10)
    

    简单索引;无需迭代

    In [555]: np.allclose(output, data[idx])                                                                  
    Out[555]: True
    

    MATLAB 和numpy 在使用两个数组进行索引时存在差异,每个维度一个。简而言之,在 MATLAB 中索引块更容易,在numpy 中索引对角线更直接。但这与这里无关。

    【讨论】:

      猜你喜欢
      • 2013-03-18
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 2012-07-08
      • 2015-06-10
      • 1970-01-01
      • 2016-06-22
      • 2021-06-29
      相关资源
      最近更新 更多