%nearestmean.m
%Nearest mean 
data=randn(2,100);
M1=[0.9 0.3;0.4 0.9];
M2=[0.9 0.2;0.2 0.6];
x=M1*data+repmat([1 1]',1,100); 
y=M2*data+repmat([-1 -1]',1,100); TRAINDATA=[x(:,1:1:50) y(:,1:1:50)];
C1=cov(x(:,1:1:50)');
TESTDATA=[x(:,51:1:100) y(:,51:1:100)]; 
C2=cov(y(:,1:1:50)');
figure 
plot(x(1,1:1:50),x(2,1:1:50),'r*')
hold on 
plot(y(1,1:1:50),y(2,1:1:50),'k*') 
%Euclidean distance 
MEAN1=mean(x(:,1:1:50)'); 
MEAN2=mean(y(:,1:1:50)'); 
INDEX=[]; 
S1=sum((TESTDATA-repmat(MEAN1',1,100)).^2); 
S2=sum((TESTDATA-repmat(MEAN2',1,100)).^2); 
INDEX1=[]; 
for i=1:1:100 
    if(S1(i)<S2(i)) INDEX1=[INDEX1 1]; 
    else INDEX1=[INDEX1 2]; 
    end
end
%Mahanobolis distance 
INDEX2=[]; 
S1=sum((TESTDATA-repmat(MEAN1',1,100))'*inv(C1)* (TESTDATA-repmat(MEAN1',1,100)));
S2=sum((TESTDATA-repmat(MEAN2',1,100))'*inv(C2)* (TESTDATA-repmat(MEAN2',1,100)));
INDEX2=[];
for i=1:1:100 
    if(S1(i)<S2(i)) 
        INDEX2=[INDEX2 1]; 
    else INDEX2=[INDEX2 2]; 
    end
end
POS1=length(find((INDEX1-[ones(1,50) ones(1,50)*2]) ==0)); 
POS2=length(find((INDEX2-[ones(1,50) ones(1,50)*2]) ==0));
figure 
subplot(3,1,1) 
stem(INDEX1,'b*')
subplot(3,1,2)
stem(INDEX2,'r*')
subplot(3,1,3)
stem([ones(1,50)
ones(1,50)*2],'r*')
figure 
for i=1:1:100 
    if(INDEX1(i)==1) 
        plot(TESTDATA(1,i),TESTDATA(2,i),'r*')
        hold on 
    else
        plot(TESTDATA(1,i),TESTDATA(2,i),'k*') 
    end
end
figure
for i=1:1:100
    if(INDEX2(i)==1)
        plot(TESTDATA(1,i),TESTDATA(2,i),'r*')
        hold on
    else
        plot(TESTDATA(1,i),TESTDATA(2,i),'k*')
    end
end
