function [confnn,Misclassified12,Misclassified21,err] = knn(C1Train,C1Test,C2Train,C2Test,k) 

%C1Train = normalize(C1Train);
%C1Test  = normalize(C1Test);
%C2Train = normalize(C2Train);
%C2Test  = normalize(C2Test);

Misclassified12 = [];
Misclassified21 = [];

nC1Tr = size(C1Train,1);
nC1Ts = size(C1Test,1);
d = size(C1Test,2);

nC2Tr = size(C2Train,1);
nC2Ts = size(C2Test,1);
size1 = size(C1Test,1);
size2 = size(C2Test,1);
size1Tr = size(C1Train,1);
size2Tr = size(C2Train,1);

c = [C1Train;C2Train];
true_class = [zeros(size1Tr,1)+1;zeros(size2Tr,1)+2;];
confnn = zeros(2,2);

for i = 1:1:size1,
            t = repmat(C1Test(i,:),size(c,1),1);
            abs_diff = abs(c-t);
            %dist = sum(abs_diff,2);
            dist = zeros(size(abs_diff,1),1);
            for  j = 1: 1: size(c,1),
              dist(j,1) = norm(abs_diff(j,:));
            end;   
            [Y,I] = sort(dist);
            neighbors_ind = I(1:k);
            neighbors = true_class(neighbors_ind);
            class1=find(neighbors == 1);
            class2=find(neighbors == 2);
            joint = [size(class1,1);size(class2,1)];
            [Y best_class]=max(joint);
            confnn(1,best_class)= confnn(1,best_class)+1;
					if ( best_class ~= 1 ) Misclassified12 = [Misclassified12;i]; end;
end;

for i = 1:1:size2,
            t = repmat(C2Test(i,:),size(c,1),1);
            abs_diff = abs(c-t);
            %dist = sum(abs_diff,2);
					dist = zeros(size(abs_diff,1),1);
               
            for  j = 1: 1: size(c,1),
              dist(j,1) = norm(abs_diff(j,:));
            end;   

            %dist = (abs_diff(:,1).^2+abs_diff(:,2).^2).^(0.5); 
            [Y,I] = sort(dist);
            neighbors_ind = I(1:k);
            neighbors = true_class(neighbors_ind);
            class1=find(neighbors == 1);
            class2=find(neighbors == 2);
            joint = [size(class1,1);size(class2,1)];
            [Y best_class]=max(joint);
           
            confnn(2,best_class)= confnn(2,best_class)+1;	   
					if ( best_class ~= 2 ) Misclassified21 = [Misclassified21;i];  end;
end;

err = 100*(sum(sum(confnn))-trace(confnn))/(size1+size2);



