function RESULTS = Confusmat(Labels,PreLabels)
% RESULTS = Confusmat(Labels,PreLabels)
% compute the confusion matrix 
% Confusionmatrix(i,j) denotes class j==>class i
% RESULTS: a struct including the confusion matrix, the accuracy, kappa coefficient, producer
%   accuracy and user accuracy.
Etiquetas = union(Labels,PreLabels); % Class labels
NumClasses = length(Etiquetas); % Number of classes
% Compute confusion matrix
ConfusionMatrix=zeros(NumClasses);
for i=1:NumClasses
    for j=1:NumClasses
        ConfusionMatrix(i,j) = length(find(PreLabels==Etiquetas(i) & Labels==Etiquetas(j)));
    end
end

% Compute overall accuracy
n      = sum(ConfusionMatrix(:));
PA     = sum(diag(ConfusionMatrix));
OA     = PA/n;

colcc=(diag(ConfusionMatrix))'./sum(ConfusionMatrix,1);
rowcc=diag(ConfusionMatrix)./sum(ConfusionMatrix,2);

% Kappa statistics
npj = sum(ConfusionMatrix,1);
nip = sum(ConfusionMatrix,2);
PE  = npj*nip;
Kappa  = (n*PA- PE)/(n^2-PE);

% Outputs
RESULTS.ConfusionMatrix =zeros(NumClasses+1);
RESULTS.ConfusionMatrix(1,2:NumClasses+1) =1:NumClasses;
RESULTS.ConfusionMatrix(2:NumClasses+1,1) =1:NumClasses;
RESULTS.ConfusionMatrix(2:NumClasses+1,2:NumClasses+1) = ConfusionMatrix;
RESULTS.OA              = OA;
RESULTS.Kappa           = Kappa;
RESULTS.producercc      = colcc;
RESULTS.usercc          = rowcc;



