function [f,dd] = fgrade(FM,x,k)
% FGRADE calculate membership degree in multidimensional fuzzy sets.
% [F,F1] = FGRADE(FM,X) calculates membership grades of the elements of
% X into clusters (multi-dimensional fuzzy sets) defined in FM
% which is generated by FMCLUST. 
%
% F is computed by using the clustering-like formula (probabilistic)
% and F1 is computed by the similarity-like formula (possibilistic).

% (c) Robert Babuska, 1994-98

c = FM.c(k);
m = FM.m(k);
P = FM.P{k}; 
V = FM.V{k};
Alist = FM.Alist{k};
NI = length(Alist);

M = zeros(NI,NI,c);
for j = 1 : c,
   M(:,:,j) = det(P(Alist,Alist,j)).^(1/length(Alist))*inv(P(Alist,Alist,j));
end;

x1 = ones(size(x,1),1);
d = [];
for j = 1 : c, 				% for all clusters
   xv = x - x1*V(j,Alist);
   if NI == 1,
      d(:,j) = M(:,:,j)*xv.^2;            
   else
      d(:,j) = sum((xv*M(:,:,j).*xv)')';
   end;
end;
dd = 1./(1+d);
d = (d+1e-100).^(-1/(m-1));          % clustering dist
f = (d ./ (sum(d')'*ones(1,c)));
