%PLOTDG Plot dendrogram
% 
%   PLOTDG(DENDROGRAM,K)
% 
% INPUT
%   DENDROGRAM Dendrogram
%   K          Number of clusters
%
% OUTPUT
%
% DESCRIPTION
% Plots a dendrogram as generated by HCLUST. If the optional K is given the
% dendrogram is compressed first to K clusters. Along the horizontal axis
% the numbers stored in DENDROGRAM(1,:) are written as text. The dendrogram
% itself is defined by DENDROGRAM(2,:) in which each entry stands for the
% level on which the previous and next group of objects are clustered.
% 
% SEE ALSO
% HCLUST

% Copyright: R.P.W. Duin, duin@ph.tn.tudelft.nl
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands

% $Id: plotdg.m,v 1.4 2003/10/07 11:56:15 bob Exp $

function plotdg(dendrogram,k)

	prtrace(mfilename);
	
	[n,m] = size(dendrogram);
	if n ~= 2
		error('No proper dendrogram supplied')
	end
	if nargin == 2	% compress dendrogram to k clusters
		if k > m
			error('Number of clusters should be less than sample size')
		end
		F = [dendrogram(2,:),inf];
		S = sort(-F); t = -S(k+1);   % find cluster level
		I = [find(F >= t),m+1];      % find all indices where cluster starts
		dendrogram = [I(2:k+1) - I(1:k); F(I(1:k))];
		m = k;
	end
	[S,I] = sort(dendrogram(2,:));

	C = [0:m-1;1:m;zeros(1,m);2:m+1];
	X = zeros(m,4); Y = X;
	T = zeros(m,3);
	for i=1:m-1
		X(i,:) = [C(2,I(i)), C(2,I(i)), C(2,C(1,I(i))), C(2,C(1,I(i)))];
		Y(i,:) = [C(3,I(i)), S(i), S(i), C(3,C(1,I(i)))];
		C(:,C(1,I(i))) = [C(1,C(1,I(i))), (C(2,I(i)) + C(2,C(1,I(i))))/2, ...
				  S(i), C(4,I(i))]';
		C(1,C(4,I(i))) = C(1,I(i));
		T(i,:) = sprintf('%3d',dendrogram(1,i));
	end
	T(m,:) = sprintf('%3d',dendrogram(1,m));
	T = char(T);
	X(m,:) = [0 0 m+1 m+1];
	Y(m,:) = [0 0 0 0];
	plot(X',Y','-b');
	h = gca;
	set(h,'box','off');
	set(h,'xtick',[1:m]);
	set(h,'xticklabel',T);
	set(h,'fontsize',8)

	return

	
