%==============================================================================
%    silh.m
%    Copyright (C) 2007  Amoolya H. Singh, singh@embl.de
%
%    This program is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    This program is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with this program.  If not, see <http://www.gnu.org/licenses/>.
%===============================================================================
function [SM,s] = silh(M,Z);
%------------------------------------------------------------------------------
%
% [SM,s] = silh(M,Z) calculates the optimal number of clusters to
% partition a data matrix M using silhouette analysis
%
% Input: 
%   M, data matrix to be clustered along the rows
%   Z, output of linkage function
% Output:
%   SM, mean silhouettes for 2-10 clusters
%   s, maximum silhouette
%
%------------------------------------------------------------------------------

% don't count more than 10 clusters
maxclusters = 10;
n = size(M,1);
% don't count having just one cluster either
Tmatrix = zeros(n,maxclusters-1); 
SM = zeros(maxclusters-1,1);

% store each clustering for 2 clusters,...,10 clusters
for i=2:maxclusters
  T = clusterdata(M,'distance','euclidean','linkage','ward',...
		'maxclust',i);
  Tmatrix(:,i-1) = T;
end

% gather silhouette calculation for each clustering
for i=2:maxclusters
  s = silhouette(M,Tmatrix(:,i-1),'euclid');
  SM(i-1) = mean(s);
end

% visualize
figure,bar([2:1:maxclusters],SM),axis([2 maxclusters 0 1]) %, axis tight
xlabel('Number of clusters in partition')
ylabel('Mean Silhouette')

% return the max silhouette
[maxsil,i] = max(SM);
nc = i+1;
s = silhouette(M,Tmatrix(:,i),'euclid');
