function [ z , Zset ] = centroid( D , nodes )
%CENTROID  returns the centroid value of nodes or a graph
%
%   CENTROID( D )  returns the centroid value of a graph
%      that is given by its distance matrix D.
%
%   CENTROID( D , nodes ) returns the centroid value of 
%      the nodes specified in the  nodes  vector.
%
%   [ z , Zset ] = CENTROID( D )  additionally returns the 
%      centroid set of the graph.
%
%  Last change:  10/2/2005 - Florian Knorn

if nargin < 1 || nargin > 2
	error('Please input at least the distance matrix D');
end
if isnan( D )
	error('How can D be of type LOGICAL ? Adjacency matrix ?');
end
if nargin == 2
	if nargout == 2
		error('Centroid set only returned if no nodes specified');
	end
	n = length(nodes);
else
	n = 0;
end

if n % node-mode
	z = zeros(n,1);
	s = sum(D,2); % stati
	for i = 1:n
		tempstat = s;
		tempstat(nodes(i)) = [];
		z(i) = s(nodes(i)) - min(tempstat);
	end
else % graph-mode
	z_all = centroid(D,1:size(D,1));
	z = min(z_all);
	Zset = find(z_all==z);
end