MATLAB: Nearest Neighbor Algorithm Help!

nearest neighbors

Hey, so I'm struggling trying to find how to use the nearest neighbor algorithm (yes, NOT the command)in order to organize a group of 2000 points into either class 1 or class 2. I plan on using the norm and sort command to accomplish this, with the input of k determining the size of the neighborhood. Please tell me what I can do to fix this script!! Attached are the data points.
data=load('NN.dat'); [rows,cols]=size('data') class1=data([1:2:500],:),1 class2=data([2:2:500],:),2 x=norm(class1-class2)
if class1>x label=2 end if class1<x label(class1)=1 end if class1>x label(class1)=2 end if class2<x label(class2)=2 end tradata=zeros(1000,3); tradata(:,1:2)=filedata(1:1000,:); tradata([1:2:1000],3)=1; tradata([2:2:1000],3)=2;

Best Answer

Here is a KNN classifier code snippet I wrote a few weeks ago. You can adapt it to your situation:
ClassVectors = randi(10, 3, 5); % Class Vectors (3x5)
DataVectors = randi(10, 15, 5);
for k1 = 1:size(ClassVectors,1)
for k2 = 1:size(DataVectors,1)
d(k2,k1) = sqrt(sum((ClassVectors(k1,:)-DataVectors(k2,:)).^2));
end
end
[~,ClassMember] = min(d, [], 2);
It produces a column vector of class members based on the minimum distance from that vector to the matching class.