% Calculates the median distance between the vectors in X
%  
function [medDist] = compmedDist(X)

	[~, medDist] = CalcMedianDist(X, X);
end


% Calculates the squared distance between the column vectors in matrix X and the column vectors in matrix Y.
% X -> input matrix of dxn
% Y -> matrix of centers, dxm
% XC_dist2 -> output matrix of size nxm
% med_dist -> the median distance between the vectors
function [XC_dist2, med_dist] = CalcMedianDist(X, Y)

	[d nx]=size(X);
	[d nc]=size(Y);
	X2=sum(X.^2,1);
	Y2=sum(Y.^2,1);

	% calculate the square
	XC_dist2 = repmat(Y2, nx, 1)+repmat(X2',1,nc)-2*X'*Y;

	% calculate the median distance
	if (nargout>1)
		med_dist = sqrt(median(XC_dist2(:)));
	end
end

% Slow method to validate implementation
function [medDist] = compmedDistAlt(X)

	for i=1:size(X, 2)
		for j=1:size(X, 2)
		
			z = X(:, i) - X(:, j);
			
			Z(i, j) = sqrt(z'*z);
		
		end	
	end
	
	medDist = median(Z(:));
end