% kNN  k-Nearest Neighbour classifier
%
% classid = knn(k,x,trsets)
% Inputs:
% k ... how many nearest points
% x [1xN] ... vector of features to be classified
% trsets  ... struct: trsets.fea{i} [power_of_i, N]
%             i ... index of class
%             N ... dimension of feature space
% Returns:
% classid ... index of class of x
% 
% Tomas Svoboda, CMP CTU Prague


function classidx = knn(k,x,trsets)

numclasses = size(trsets.fea,2);	% how many classes


data = [];
for i=1:numclasses,
  data = [data;repmat(i,size(trsets.fea{i},1),1),trsets.fea{i}];
end

DistMat = data(:,2:size(data,2))-repmat(x(:)',size(data,1),1);
if size(DistMat,2)==1
  DistMat = [DistMat,zeros(size(DistMat))];
end
dist	= sum(DistMat'.^2)';
[distSorted,idxsort] = sort(dist);

for i=1:numclasses,
  Count(i) = sum(i==data(idxsort(1:k),1));
end

[howmany,classidx] = max(Count);

return
