% kmedoids_demo.m
% Generation of a small dataset with two classes with Gaussian distribution
% Demo of the k-metoids method
% Dr. David Pan, UAH

close all

N = 100;

% Generate data entries for Class 1
m1 = [3, 3]';   % Mean vector
cov1 = [2 1; 1 2]; % Covariance matrix
rng default  % For reproducibility
r1 = mvnrnd(m1,cov1,N);

data_C1 = zeros(N, 2);
data_C1 = r1;

% Generate data entries for Class 2
m2 = [9, 9]';
cov2 = [2,1; 1,2];
rng default  % For reproducibility
r2 = mvnrnd(m2,cov2,N);

data_C2 = zeros(N, 2);
data_C2 = r2;

% Combine data of two classes
X = vertcat (data_C1, data_C2);


% k-medoids with two clusters
[idx,C] = kmedoids(X,2);

% Display the clusters
plot(X(idx==1,1),X(idx==1,2),'r.','MarkerSize',12)
hold on
plot(X(idx==2,1),X(idx==2,2),'b.','MarkerSize',12)

plot(C(:,1),C(:,2),'co',...
     'MarkerSize',7,'LineWidth',1.5) 
grid

legend('Cluster 1','Cluster 2','Medoids',...
       'Location','NW');
   
find(X(:,1)==C(1,1) & X(:,2) == C(1,2))
find(X(:,1)==C(2,1) & X(:,2) == C(2,2))


% Assign test data point to the neareast cluster
Xtest = [6 4];
[dist, cluster_index] = pdist2(C,Xtest,'euclidean','Smallest',1);
pdist2(Xtest, C(1,:))
pdist2(Xtest, C(2,:))