% Example 8.7
% Applies Ling's method to interpoint distance matrix.

% Continuing with same data used in 
% Example 8.4.
% Use just Topics 6 and 9
ind = find(classlab == 6);
ind = [ind; find(classlab == 9)];
n = length(ind);
clabs = classlab(ind);
data = XX(ind,:);
% Randomly reorder the data and view the 
% interpoint distance matrix as an image.
data = data(randperm(n),:);
Y = pdist(data);
Ys = squareform(Y);
imagesc(Ys);
colormap(gray(256))
title('Interpoint Distance Matrix - Random Order')
axis off

% Now apply Ling's method. First need to
% get a partition or clustering.
Z = linkage(Y,'complete');
% Now get the ordering based on the 
% cluster scheme.
T = cluster(Z,'maxclust',2);
% Sort these, so points in the same cluster
% are adjacent.
[Ts,inds] = sort(T);
% Sort the distance matrix using this and replot.
figure
imagesc(Ys(inds,inds))
title('Interpoint Distance Matrix - Cluster Order')
colormap(gray(256))
axis off






