问题描述
所以我想我可能在这里绝对走错了路,但是基本上
So I think I might be absolutely on the wrong track here, but basically
我有一个3维网格,在那个网格的所有点上都找到了到测试点的所有距离
I have a 3-d meshgrid, I find all of the distances to a testpoint at all of the points in that grid
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进行排序(拼合然后搜索),获得最低值的索引.
Then I am trying to find the coordinates of he gridpoint that is the closest to that test point.My idea was to sort d (flatten then search), get the index of the lowest value.
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值).我正在尝试类似的事情,而且我很确定自己过于复杂了. 如何获取最接近测试点的3-d网格点的(x,y,z)?
Use that index on my 3d grid to find the point coordinates (not the d value at that point). I am trying something like this, and I am pretty sure I am overcomplicating it. How can I get the (x,y,z) of the 3-d gridpoint that is closest to my test point?
推荐答案
如果您只是想找到最正确的点的坐标,那么您就走错了路.生成网格并在如此多的副本上计算距离是没有意义的.您可以轻松,独立地在各个维度上做到这一点:
If you just want to find the coordinates of the closest point you are right, you're on the wrong track. There is no point in generating a meshgrid and calculate the distance on so many duplicates. You can do it in every dimension easily and independently:
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])
这篇关于numpy-在3-d矩阵中找到网格点的空间位置(知道该网格点的索引)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!