File Exchange

image thumbnail

Find Nearest Neighbors on Sphere

version 1.7 (12.5 KB) by Kurt von Laven
To be used with the GridSphere function to look up the nearest point to a query on a geodesic grid.


Updated 13 Mar 2015

View License

A geodesic grid is an even grid over the surface of a sphere. The algorithm is optimized for a grid generated by GridSphere and won't work on an arbitrary geodesic grid. All code is compatible with GNU Octave. The GridSphere function is available on the MATLAB file exchange at
FindNearestNeighbors and GridSphere share some functions in common. Each package contains a copy of these functions so that both can stand alone. To eliminate duplicates, simply move all the files into a single folder and replace the shared files when prompted.

Cite As

Kurt von Laven (2020). Find Nearest Neighbors on Sphere (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (5)

Smart code, well documented and straightforward to understand.
Only one thing that could be improved: The code does not work reliably for a high density of points (e.g. for a very dense mesh): The reason is that NUM_LINES_OF_LAT_TO_SEARCH in FindNearestNeighborsWithinNearbyLatitudes is too small (by default 3). It is also not possible to just increase it until the neighbor search works reliably because one then easily gets indexes that are out of bounds. Had to add some if statements to make it work for any point density and automatically determine a useful NUM_LINES_OF_LAT_TO_SEARCH.

Fast and found it easy to use. Thanks!


-- Wrong page. Comment intended for GridSphere code.


Blazingly fast and well documented. Only an example would not have been unbecoming, e.g. to illustrate the fact that returned values are in degrees (whereas Matlab's sph2cart requires radians).

[lat,long] = GridSphere(1000);
latrad = deg2rad(lat);
longrad = deg2rad(long);
[x,y,z] = sph2cart(longrad, latrad, 1);
scatter3(x, y, z, 22);
axis equal vis3d;



Added a link to another FX submission that this submission uses code from.

Made minor corrections to comments. Removed write and execute permissions from group/others on all *.m files. Removed trailing whitespace and switched from 2 spaces after each period to 1 in the interest of readability.

Made code available as a toolbox and removed some unnecessary hidden files.

Replaced tabs with spaces so that the source code displays consistently in all text editors.

Replaced the ElementWiseMax function with an equivalent built-in function.

Added missing Logarithm function file.

Added missing function file.

MATLAB Release Compatibility
Created with R2009b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired by: Geodesic Midpoints

Inspired: Grid Sphere