How to find the nearest points to given coordinates with MATLAB?

cardogar picture cardogar · Jul 1, 2013 · Viewed 11.9k times · Source

I need to solve a minimization problem with Matlab and I'm wondering which is the easiest solution. All the potential solutions that I've been thinking in require lot of programming effort.

Suppose that I have a lat/long coordinate point (A,B), what I need is to search for the nearest point to this one in a map of lat/lon coordinates.

In particular, the latitude and longitude arrays are two matrices of 2030x1354 elements (1km distance) and the idea is to find the unique indexes in those matrices that minimize the distance to the coordinates (A,B), i.e., to find the closest values to the given coordinates (A,B).

Any help would be very appreciated.

Thanks!

Answer

Mohsen Nosratinia picture Mohsen Nosratinia · Jul 1, 2013

Let Lat and Long denote latitude and longitude matrices, then

dist2=sum(bsxfun(@minus, cat(3,A,B), cat(3,Lat,Long)).^2,3);
[I,J]=find(dist2==min(dist2(:)));

I and J contain the indices in A and B that correspond to nearest point. Note that if there are multiple answers, I and J will not be scalar values, but vectors.