%% clear before start
clear
clc;

%% Import File
disp('Read data...')

%Open training file
file = fopen('faithful.dat');

%Read training data
fscanf(file, '%s\n',2);
data = fscanf(file , '%f' , inf);
N=size(data,1)/(2);
data=reshape(data, 2, N);
data=data';

fclose(file);
disp('...done.')

%% plot data
disp('Green plot...')
h = figure;
hd = plot(data(:, 1), data(:, 2), '.g', 'markersize', 30);
hold on; 
%axis([0 1 0 1]); axis square; 
set(gca, 'box', 'on');
ht = text(0.5, 1.05, 'Data', 'horizontalalignment', 'center');
disp('...done.')

disp('Press any key to continue'); 
pause; %clc;

%% Initial E-step.
disp('K-means...')
centres=[4.2 60; 2.4 80]; % centre initialization
post=zeros(N,2); % post(i,1)==1 if cluster 1 was assigned to sample i
% add your code here
% | | |
% v v v

% ^ ^ ^
% | | |

% Plot the initial model
ncirc = 30; theta = linspace(0, 2*pi, ncirc);
xs = cos(theta); ys = sin(theta);
xvals = centres(:, 1)*ones(1,ncirc) + sqrt([0.2 0.2]')*xs;
yvals = centres(:, 2)*ones(1,ncirc) + sqrt([20 20]')*ys;
hc(1)=line(xvals(1,:), yvals(1,:), 'color', 'r');
hc(2)=line(xvals(2,:), yvals(2,:), 'color', 'b');

dcols = [post(:,1), zeros(N, 1), post(:,2)];
delete(hd);
for i = 1 : N
  hd(i) = plot(data(i, 1), data(i, 2), 'color', dcols(i,:), ...
          'marker', '.', 'markersize', 30);
end
figure(h);
disp('...done.')

%% Final result
fprintf(1, 'Final red cluster centre: (%f,%f)\nFinal blue cluster centre: (%f,%f)\n', centres(1,1), centres(1,2), centres(2,1), centres(2,2));