MATLAB: K-means Clustering Result Always Changes

algorithmclusteringk-meanskmeansStatistics and Machine Learning Toolbox

I'm working on k-means in MATLAB. Here are my codes:
load cobat.txt
k=input('Enter the number of cluster: ');
if k<8
[cidx ctrs]=kmeans(cobat, k, 'dist', 'sqEuclidean');
Z = [cobat cidx]
else
h=msgbox('Must be less than eight');
end
"cobat" is the file of mine and here it looks:
65 80 55
45 75 78
36 67 66
65 78 88
79 80 72
77 85 65
76 77 79
65 67 88
85 76 88
56 76 65
My problem is everytime I run the code, it always shows different result, different cluster. How can I keep the clustering result always the same?

Best Answer

%generate some initial cluster centers according to some deterministic algorithm
%in this case, I construct a space-diagonal equally spaced, but choose your
%own algorithm
minc = min(cobat, 1);
maxc = max(cobat, 1);
nsamp = size(cobat,1);
initialcenters = repmat(minc, nsamp, 1) + bsxfun(@times, (0:nsamp-1).', (maxc - minc) ./ (nsamp-1));
%Once you have constructed the initial centers, cluster using those centers
[cidx ctrs] = kmeans(cobat, k, 'dist', 'sqEuclidean', 'start', initialcenters);