Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 在网格上找到(x,y)坐标最近的点(MATLAB)_Arrays_Matlab - Fatal编程技术网

Arrays 在网格上找到(x,y)坐标最近的点(MATLAB)

Arrays 在网格上找到(x,y)坐标最近的点(MATLAB),arrays,matlab,Arrays,Matlab,我创建了一个网格,该网格由限制定义xmin=-2,xmax=2,ymin=-2,ymax=2和分辨率0.25: [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;

我创建了一个网格,该网格由限制定义
xmin=-2
xmax=2
ymin=-2
ymax=2
和分辨率
0.25

[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);

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

将距离定义为d=(x-x0)^2+(y-y0)^2,并遍历网格中的所有点。
效率不是很高,但确实有效。

对于均匀分布的网格,您可以在
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(距离(x,y))
循环。请提供一个工作代码。如果您只想抛出一个单行的想法,请使用commentsI无法添加注释:(然后获得rep,直到你可以。我不会把它标记为一个完全不是答案,但它很接近。我们都经历了那个阶段,请忍耐!你不能用
距离
而不是手写完整的方程式吗?@Adriaan你的意思是
pdist2
?也许你可以使用它,但不确定在这种情况下如何使用;可能是slowerah,是的,就是这个。为什么它比手工做慢呢?
pdist2
也做各种检查吗?@Adriaan它应该是
d=pdist2([xy],[x(:)y(:));
。是的,我的意思是因为检查而慢,因为它内部使用循环也是统计工具箱的一部分,可能不可用。