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

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

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

问题

  1. 假设我有以下的meshgrids ```omega```, ```phiy```, ```phix```
  2. ```python
  3. import numpy as np
  4. phi = np.linspace(-0.75, 0.75, num=4)
  5. omega = np.linspace(-100, 100, num=5)
  6. omega, phiy, phix = np.meshgrid(omega, phi, phi, sparse=True, indexing='ij')
  7. rand = np.random.rand(5, 4)

然后我想要得到以下的 C

  1. def f(j, k):
  2. return np.argmin(np.abs(phi[j]**2 + np.sin(phi[k]) - phi))
  3. C = np.empty((5, 4, 4))
  4. for i in range(5):
  5. for j in range(4):
  6. for k in range(4):
  7. C[i, j, k] = rand[i, f(j, k)]

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

  1. <details>
  2. <summary>英文:</summary>
  3. 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)

  1. 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)]

  1. Are there any more compact and better ways to get it, using some tools for meshgrids?
  2. </details>
  3. # 答案1
  4. **得分**: 1
  5. 你可以通过消除 `for` 循环并仅使用向量化操作来更快地计算你的 `f` 函数:
  6. ```python
  7. # f_mat[i,j] contains f(i,j)
  8. f_mat = np.abs((phi[None].T**2 + np.sin(phi))[...,None] - phi).argmin(-1)
  9. 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:

  1. # f_mat[i,j] contains f(i,j)
  2. f_mat = np.abs((phi[None].T**2 + np.sin(phi))[...,None] - phi).argmin(-1)
  3. 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:

确定