创建由限制xmin=-2
,xmax=2
,ymin=-2
,ymax=2
和0.25
分辨率定义网格:查找最近的点(X,Y)的网格坐标(MATLAB)
[X,Y] = meshgrid(-2:.25:2, -2:.25:2);
我需要找到最近的指向x=0.9
,y=1.1
,其功能可用于任何坐标。
创建由限制xmin=-2
,xmax=2
,ymin=-2
,ymax=2
和0.25
分辨率定义网格:查找最近的点(X,Y)的网格坐标(MATLAB)
[X,Y] = meshgrid(-2:.25:2, -2:.25:2);
我需要找到最近的指向x=0.9
,y=1.1
,其功能可用于任何坐标。
下面的代码计算所有的距离,并发现最小距离的格点。即使网格没有恒定的间距,它也可以工作。
[X,Y] = meshgrid(-2:.25:2, -2:.25:2); %// define grid (arbitrary)
x = 0.9; %// define point
y = 1.1;
d = (x-X).^2+(y-Y).^2; %// compute squared distances
[~, ind] = min(d(:)); %// minimize distance and obtain (linear) index of minimum
resultX = X(ind); %// use that index to obtain the result
resultY = Y(ind);
对于均匀间隔的网格,您可以通过在O(1)
中直接计算找到此值,而不是在整个网格中搜索O(m*n)
。我隔了灵活性xres
和yres
,但你当然可以将它们组合起来:
function [u, v] = getgrid(x, y, xmin, xmax, xres, ymin, ymax, yres)
%// Find how many grid points we are from the center
u=round(x/xres);
v=round(y/yres);
%// Add the center point of grid to each offset
u=u+(-xmin/xres)+mod(1+(xmax-xmin)/xres,2);
v=v+(-ymin/yres)+mod(1+(ymax-ymin)/yres,2);
end
这是一个测试脚本,我写的驱动功能:
xmin=-2; xmax=2; ymin=-2; ymax=2; res=0.25;
[X,Y] = meshgrid(xmin:xres:xmax, ymin:yres:ymax);
x=0.9
y=1.1
[u v]=getgrid(x, y, xmin, xmax, res, ymin, ymax, res)
[X(v,u), Y(v,u)]
x=-0.7
y=1.6
[u v]=getgrid(x, y, xmin, xmax, res, ymin, ymax, res)
[X(v,u), Y(v,u)]
和输出...
>> gogrid
x = 0.90000
y = 1.1000
u = 13
v = 13
ans =
1 1
x = -0.70000
y = 1.6000
u = 6
v = 15
ans =
-0.75000 1.50000
如果需要在一个小时内完成,我会用一个快速又脏的'min(distance(x,y))'循环。 – Adriaan