所以我想我可能在这里走错了路,但基本上是
我有一个三维网格,我找到了该网格中所有点到测试点的所有距离
import numpy as np
#crystal_lattice structure
x,y,z = np.linspace(-2,2,5),np.linspace(-2,2,5),np.linspace(-2,2,5)
xx,yy,zz = np.meshgrid(x,y,z)
#testpoint
point = np.array([1,1,1])
d = np.sqrt((point[0]-xx)**2 + (point[1]-yy)**2 + (point[2]-zz)**2)
#np.shape(d) = (5, 5, 5)
然后我试图找到最接近该测试点的网格点的坐标。 我的想法是排序d(展平然后搜索),得到最低值的索引。
low_to_hi_d = np.sort(d, axis=None) # axis=0 flattens the d, going to flatten the entire d array and then search
lowest_val = low_to_hi_d[0]
index = np.where(d == lowest_val)
#how do I get the spatial coordinates of my index, not just the position in ndarray (here the position in ndarray is (3,3,3) but the spatial position is (1,1,1), but if I do d[3,3,3] I get 0 (the value at spatial position (1,1,1))
在我的3d网格上使用该索引来查找点坐标(而不是该点处的d值)。我正在尝试这样的事情,我很确定我过于复杂。 如何获得最接近我的测试点的三维网格点的(x,y,z)?
答案 0 :(得分:2)
如果您只是想找到最近点的坐标,那么您就错了。生成网格网格并计算这么多重复项的距离是没有意义的。您可以轻松独立地在每个维度中执行此操作:
import numpy as np
x,y,z = np.linspace(-2,2,5),np.linspace(-2,2,5),np.linspace(-2,2,5)
p=np.array([1,1,1])
closest=lambda x,p: x[np.argmin(np.abs(x-p))]
xc,yc,zc=closest(x,p[0]),closest(y,p[1]),closest(z,p[2])
答案 1 :(得分:1)
我不完全确定这是你想要的。
您可以找到最小d
的索引:
idx = np.unravel_index(np.argmin(d), d.shape)
(3, 3, 3)
并使用它来索引你的meshgrid:
xx[idx], yy[idx], zz[idx]
(1.0, 1.0, 1.0)