function fnctval = functr(cs)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function fnctval = functr(cs)                          %
%  This function computes                                %
%  R = sum(r_j^l)/(256*m*n) where                        %
%    r_j = max distance of a member of cluster j to its  %
%        center.                                         %
%  or                                                    %
%  D = sum(d_i^l)/(256*myk) where                        %
%    d_i = distance of point i to its cluster center.    %
%  (The denominators in R and D keep the functions       %
%     well-scaled.)                                      %
%  The input array cs contains the cluster centers,      %
%      stacked as a column vector.                       %
%  DPO 03/03                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

global myast myk myell mywhichfunction 

[m,p,q]=size(myast);
centers = reshape(cs,q,myk);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  Assign each point to the nearest cluster.             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[aclus,clustercounts] = map_to_cluster(myast,centers);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  Compute R and D.                                      %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

r = zeros(myk,1);
D = 0;

for i=1:m,
   for j=1:p,
      kk = aclus(i,j);
      d = norm(reshape(myast(i,j,:),q,1)-centers(:,kk));
      r(kk) = max(r(kk),d);
      D = D + d^myell;
   end
end

D = D / (256*m*p);
R = sum(abs(r).^myell)/(256*myk);

if (mywhichfunction == 'minimizing R')
   fnctval = R;
else
   fnctval = D;
end


