% 3-20-2007
% Script file: irisknn.m
% Training K-NN Classifier from datairis.txt (75 patterns)
%
d=4; N=150; n1=25; n2=25; n3=25;  n=n1+n2+n3;

fin=fopen('datairis.txt');
fgetl(fin); fgetl(fin); fgetl(fin);   % skip three header lines
A=fscanf(fin,'%f',[d+1  N]);
X=A(1:d,:);
%
% Put the training patterns in array T(1:d, 1:n)
%     testing patterns in Y1(:,1:n1), Y2(1:d, 1:n2), Y3(1:d,1:n3)
%
T=[X(:,1:25), X(:,51:75),X(:,101:125)];
Y1=X(:,25:50);  Y2=X(:,76:100);  Y3=X(:,126:150);

fout=fopen('irisknn.txt','w');
fprintf(fout,'K-NN Training and Testing for iris data\n');
%
% Testing the patterns from the the "first class" 
% using K-NN, with (K,Kh)=(3,2) or (5,3)??
%
K=3; 
Kh=(K+1)/2; 
count=0; 
Error=zeros(n,1);
  for i=1:n1
    y=Y1(:,i);
    for j=1:n
      x=T(:,j);
      R(j)=norm(x-y,2);
    end
    [Rs, index]=sort(R);
    for j=1:K
      if (index(j) <= n1)
        count=count+1;
      end 
    end
    if (count < Kh) 
      Error(i)=1
    end
  end
%
% Testing the patterns from the the "second class" 
% using K-NN, with (K,Kh)=(3,2) or (5,3)??
%
  for i=1:n2
    y=Y2(:,i);
    for j=1:n
      x=T(:,j);
      R(j)=norm(x-y,2);
    end
    [Rs, index]=sort(R);
    for j=1:K
      if ((index(j) > n1) && (index(j) <= n1+n2))
        count=count+1;
      end 
    end
    if (count < Kh) 
      Error(i)=1
    end
  end

  for i=1:n3
    y=Y3(:,i);
    for j=1:n
      x=T(:,j);
      R(j)=norm(x-y,2);
    end
    [Rs, index]=sort(R);
    for j=1:K
      if ((index(j) > n1+n2) && (index(j) <= n1+n2+n3))
        count=count+1;
      end 
    end
    if (count < Kh) 
      Error(i)=1
    end
  end
%
% Printout the test results
% E=reshape(Error,25,3);
%
for j=1:25 
  fprintf(fout,'%2d',Error(j)); 
end 
fprintf(fout,'\n');
for j=26:50
  fprintf(fout,'%2d',Error(j));
end
fprintf(fout,'\n');
for j=51:75
  fprintf(fout,'%2d',Error(j));
end
fprintf(fout,'\n');
fclose(fin); fclose(fout);
