2015-09-09 59 views
1

创建由限制xmin=-2xmax=2ymin=-2ymax=20.25分辨率定义网格:查找最近的点(X,Y)的网格坐标(MATLAB)

[X,Y] = meshgrid(-2:.25:2, -2:.25:2); 

我需要找到最近的指向x=0.9,y=1.1,其功能可用于任何坐标。

+0

如果需要在一个小时内完成,我会用一个快速又脏的'min(distance(x,y))'循环。 – Adriaan

回答

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); 
+0

难道你不能只使用'距离'而不是手写完整的等式? – Adriaan

+0

@Adriaan你的意思是'pdist2'?也许你可以使用它,但不知道在这种情况下如何;它可能会更慢 –

+0

啊,是的,就是那个。为什么它比手工做得慢? 'pdist2'也做各种检查吗? – Adriaan

0

如果网格的大小不是太大,可以随时计算到每个点的距离并找到最小值。

您定义的距离为d =(X-X0)^ 2 +(Y-Y0)^ 2,经过在网格的所有点。 不是超高效的,但它的工作。

+1

请提供一个工作代码。如果你想只丢一单成荫的想法,使用注释 – Adriaan

+0

我不能添加评论:(直到你可以。我倒是没有将此作为一个完全不-的回答 –

+1

然后获得代表,但已经很接近了。我们都经历了这个阶段,只是忍耐! – Adriaan

1

对于均匀间隔的网格,您可以通过在O(1)中直接计算找到此值,而不是在整个网格中搜索O(m*n)。我隔了灵活性xresyres,但你当然可以将它们组合起来:

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 
相关问题