在一个NumPy数组中找到最接近网格的元素的索引。

huangapple go评论70阅读模式
英文:

Finding the index of element in a numpy array the closest to meshgrids

问题

假设我有以下的meshgrids ```omega```, ```phiy```, 和 ```phix```。

```python
import numpy as np

phi = np.linspace(-0.75, 0.75, num=4)
omega = np.linspace(-100, 100, num=5)
omega, phiy, phix = np.meshgrid(omega, phi, phi, sparse=True, indexing='ij')

rand = np.random.rand(5, 4)

然后我想要得到以下的 C

def f(j, k):
    return np.argmin(np.abs(phi[j]**2 + np.sin(phi[k]) - phi))

C = np.empty((5, 4, 4))
for i in range(5):
    for j in range(4):
        for k in range(4):
            C[i, j, k] = rand[i, f(j, k)]

是否有更紧凑和更好的方法来获得它,使用一些meshgrids的工具?


<details>
<summary>英文:</summary>

Suppose I have the following meshgrids ```omega```, ```phiy```, and ```phix```.

import numpy as np

phi=np.linspace(-0.75,0.75,num=4)
omega=np.linspace(-100,100,num=5)
omega,phiy,phix=np.meshgrid(omega,phi,phi,sparse=True,indexing='ij')

rand=np.random.rand(5,4)

Then I want to get the following ```C```

def f(j,k):
return np.argmin(np.abs(phi[j]**2+np.sin(phi[k])-phi))

C=np.empty((5,4,4))
for i in range(5):
for j in range(4):
for k in range(4):
C[i,j,k]=rand[i,f(j,k)]

Are there any more compact and better ways to get it, using some tools for meshgrids?


</details>


# 答案1
**得分**: 1

你可以通过消除 `for` 循环并仅使用向量化操作来更快地计算你的 `f` 函数:

```python
# f_mat[i,j] contains f(i,j)
f_mat = np.abs((phi[None].T**2 + np.sin(phi))[...,None] - phi).argmin(-1)
C = rand[:,f_mat]
英文:

You can do this quite a bit faster by eliminating the for loops and using vectorized operations only to compute your f function:

# f_mat[i,j] contains f(i,j)
f_mat = np.abs((phi[None].T**2 + np.sin(phi))[...,None] - phi).argmin(-1)
C = rand[:,f_mat]

huangapple
  • 本文由 发表于 2023年6月29日 14:15:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76578466.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定