Skip to content

Instantly share code, notes, and snippets.

@kmader
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmader/9934533 to your computer and use it in GitHub Desktop.
Save kmader/9934533 to your computer and use it in GitHub Desktop.
Calculate Nearest Neighbor in Matlab
% calculate nearest neighbor
function [nndist,nntheta] = findnn(xcol,ycol)
colIndex=1:length(xcol);
nndist=zeros(1,length(xcol));
nntheta=zeros(1,length(xcol));
for i=colIndex
curX=xcol(i);
curY=ycol(i);
[mindist,minind]=min(sqrt((xcol(find(colIndex~=i))-curX).^2+(ycol(find(colIndex~=i))-curY).^2));
if(minind>=i)
% since we remove the i-th element before computing
minind=minind+1;
end
nndist(i)=mindist;
nntheta(i)=atan2(ycol(minind)-curY,xcol(minind)-curX);
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment