﻿function [dmcen2,dmcen2j]=dmcen(S,w)
%sintax: [dmcen,dmcenid]=dmcen(S,w)
%
%S: sensitivity/specificity matrix
%w: weight for the convex combinations

%  DMCEN=w MCEN+(1-w) DMCENid
%  DMCEN(j)= w MCEN(j)+(1-w)DMCENid(j)  j=1,2,...,K(number of classes)
%
%Global DMCEN in Eq.(26) and per-class (j) DMCEN in Eq.(25) in
%
%O. Valencia M.C. Ortiz, M.S. Sánchez, L.A. Sarabia
%A modified entropy-based performance criterion for class-modelling with multiple classes
%Chemometrics and Intelligent Laboratory Systems 217 (2021) 104423
%https://doi.org/10.1016/j.chemolab.2021.104423

%22/6/2021

F=1-S;
F = F + diag(diag(S) - diag(F));
K=size(F,1);

%Our proposal
dmcenjid=(1-diag(F))';% Eq. (23)
dmcenid=sum(dmcenjid);
if dmcenid~=0
    dmcenid=(dmcenjid*dmcenjid')/dmcenid;%Eq. (24)
end

lb=log(2*K-2);%basis of the logarithm
if K==2,lambda=.5;else, lambda=1;end
d=2*sum(sum(F))-lambda*trace(F);

mcenj=zeros(1,K);
R=mcenj;
if d~=0
    for j=1:K
        s=sumasj(F,j);
        R(j)=s/d;
        for m=1:K
            if m~=j
                Rjmj=F(j,m)/s;
                Rmjj=F(m,j)/s;
                if Rjmj~=0
                    mcenj(j)=mcenj(j)-Rjmj*log(Rjmj);
                end
                if Rmjj~=0
                    mcenj(j)=mcenj(j)-Rmjj*log(Rmjj);
                end
            end
        end
        mcenj(j)=mcenj(j)/lb;%Eq.(19)
    end
end
mcen=R*mcenj';%Eq.(20)
dmcen2=w*mcen+(1-w)*dmcenid;%Eq.(26)
dmcen2j=w*mcenj+(1-w)*dmcenjid;%Eq.(25)

function d=sumasj(F,j)
K=size(F,1);
d=-F(j,j);
for k=1:K
    d=d+ F(j,k)+F(k,j);
end
