0
votes

I'm trying to do a nearest neighbor search that yields a single point as the single "nearest neighbor" to another point in matlab.

I've got the following data:

  1. A longitude grid that is size 336x264 "lon"
  2. some random point within the bounds of the longitude grid "dxf"

I've tried using MATLAB's "knnsearch" function

https://www.mathworks.com/help/stats/knnsearch.html

But sadly when I use the command:

idx = knnsearch(lon, dxf)

I am met with the error:

"Y must be a matrix with 264 columns."

Is there an alternative nearest neighbor search I can use to find the nearest neighbor to a single point within MATLAB? Is there a simpler solution I can implement?

I literally just want to find the closest point within the "lon" matrix to point "dxf".

Thanks! Taylor

2
I'm not clear on what you're asking. You have a 336x264 grid and you want to find the grid point that is closest to a point (presumably a 2-coordinate) point dxf?beaker
@beaker That is correct!Taylor

2 Answers

1
votes

You should first convert your grid to an n-by-2 matrix (if you created this using meshgrid, it's simply G = [XX(:) YY(:)]), you can then try it with pdist2 if you have the Statistics and Machine Learning Toolbox (which you do):

[D,I] = pdist2(P, G, 'euclidian', 'Smallest', 1);

Where G is the grid and P is your m-by-2 array of points to test.

0
votes

If you're working without Toolboxes, you can construct a simple distance formula yourself:

xx = [0:364];  % Not sure what your limits were so just making some up here
yy = [0:264];
[X, Y] = meshgrid(xx,yy);
dxf = [221.7, 109.1];  % Again just pulling numbers from nether regions 

G = [X(:),Y(:)];
d = sqrt( sum( (G-dxf).^2, 2) );
[minDist, idxMinDist] = min(d);
solution = G(idxMinDist,:);

You can modify the limits for xx and yy to fit your specific setup accordingly.