gpt4 book ai didi

python - 使用 numpy 用索引矩阵对向量进行索引,类似于 MATLAB

转载 作者:太空宇宙 更新时间:2023-11-03 19:53:20 25 4
gpt4 key购买 nike

我想提取一个矩阵,其中填充有索引矩阵索引的向量中的值
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, :]])

非常感谢

最佳答案

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 中索引 block 更容易,在 numpy 中索引对角线更直接。但这与这里无关。

关于python - 使用 numpy 用索引矩阵对向量进行索引,类似于 MATLAB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59695763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com