function accuracy = mvn_knnclass(D, cl_assig, k, cl_filter)
%MVN_KNNCLASS

%   (c) 2011, Dominik Schnitzer, <dominik.schnitzer@ofai.at>
%   http://www.ofai.at/~dominik.schnitzer/mvn
%
%   This file is part of the MVN Octave/Matlab Toolbox
%   MVN is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 of the License, or
%   (at your option) any later version.
%
%   MVN is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You should have received a copy of the GNU General Public License
%   along with MVN.  If not, see <http://www.gnu.org/licenses/>.

accuracy = 0;

if (nargin < 4)
    cl_filter = [];
end

for i = 1:length(cl_assig)
    
    D(i, i) = +Inf;
    [~, nn_idx] = sort(D(i, :));
    
    if (~isempty(cl_filter))
        kk = 0;
        for j = 1:length(cl_assig)
            if (cl_filter(nn_idx(j)) ~= cl_filter(i))
                kk = kk + 1;
                if (cl_assig(nn_idx(j)) == cl_assig(i))
                    accuracy = accuracy + 1/k;
                end
                
                if (kk == k)
                    break;
                end
            end
        end
    else
        for kk = 1:k
            if (cl_assig(nn_idx(k)) == cl_assig(i))
                accuracy = accuracy + 1/k;
            end
        end
    end
    
end

accuracy = accuracy / length(cl_assig);
