英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论