% CLUSTER ANALYSIS RESULTS
% June 11, 2013 3:30pm

% LOAD DATA %
%%%%%%%%%%%%%

% Data generated by california1.dta - RE-RUN

%clear
cd('/Users/filizgarip/Desktop/Revisions Sep 13 for SSM/');
seed = 931316785;


% Import data from File -> Import, save workspace as "calif_data_new.mat"

load califdatanew

data = califdatanew;
id      = data(:,1);
datanew = data(:,3:15);

datanames = {'age','sex','married','separated','white','black','hispotr',...
            'hs','somecol','col', 'adv','mig','migprt'};
        
datacur = datanew;

% K-MEANS CLUSTERING %
%%%%%%%%%%%%%%%%%%%%%%
   
       % IMPORTANT NOTE: We need to run many replicates for kmeans. Matlab
       % automatically selects the solution that minimizes the total sum of
       % distances (see the demo of cluster analysis). Otherwise, we may
       % get stuck in local minima, and miss the global solution.
        
[cl2,cm2] = kmeans(datacur,2, 'distance','cityblock','replicates',50,'display','final'); 
[s2,h2] = silhouette(datacur, cl2,'cityblock');
saveas(h2,'sil2.tif');
 
%[cl3,cm3] = kmeans(datacur,3,'distance','cityblock','replicates',100,'display','final');
%[s3,h3] = silhouette(datacur, cl3,'cityblock');
%saveas(h3,'sil3.tif');

%[cl4,cm4] = kmeans(datacur,4,'distance','cityblock','replicates',1000,'display','final'); 
%[s4,h4] = silhouette(datacur, cl4,'cityblock');
%saveas(h4,'sil4.tif');

%[cl5,cm5] = kmeans(datacur,5,'distance','cityblock','replicates',1000,'display','final'); 
%[s5,h5] = silhouette(datacur, cl5,'cityblock');
%saveas(h5,'sil5.tif');

%[cl6,cm6] = kmeans(datacur,6,'distance','cityblock','replicates',1000,'display','final'); 
%[s6,h6] = silhouette(datacur, cl6,'cityblock');
%saveas(h6,'sil6.tif');

% Select the number of clusters

nocl = 2;
clcur = cl2;
cmcur = cm2;

save CLUSTERS data datanames cl* cm* nocl

      
clids = [id clcur];    
dlmwrite('cluster.txt', clids,',');
     
   













