簡體   English   中英

在網格(MATLAB)上找到最接近(x,y)坐標的點

[英]Find the nearest point to (x,y) coordinates on mesh (MATLAB)

我創建了一個由極限xmin=-2xmax=2ymin=-2ymax=2和分辨率0.25定義的網格:

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

我需要使用可用於任何坐標的函數找到x=0.9y=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)搜索來找到。 為了靈活性,我將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

如果網格的大小不太大,則始終可以計算到每個點的距離並找到最小值。

將距離定義為d =(x-x0)^ 2 +(y-y0)^ 2,然后遍歷網格中的所有點。 不是超級高效,但是它的工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM