function [class_predictions] = knn(traindata,trainlabels,k, testdata)
% function [class_predictions] = knn(traindata,trainlabels,k, testdata)
%
% produces class labels on the test data using a k-nearest-neighbor classifier
%
%A. Student, CS 175
%
% Inputs
% traindata: a N1 x d vector of feature data (the "memory" for kNN)
% trainlabels: a N1 x 1 vector of classlabels for traindata
% k: an odd positive integer indicating the number of neighbors to use
% testdata: a N2 x d vector of feature data for testing the knn classifier
%
% Outputs
% class_predictions: N2 x 1 vector of predicted class values

% determine the sizes of the input arrays
[ntest dtest] = size(testdata);
[ntrain dtrain] = size(traindata);
nlabels = length(trainlabels);
% check that the necessary dimensions match:
if (dtest ~= dtrain)
error('Dimensions of training and test data do not match');
elseif (nlabels ~= ntrain)
error('Number of training data points and labels do not match');
end

% initialize a vector to contain the class predictions
class_predictions = zeros(ntest,1);

for i=1:ntest
% for each test point
x = testdata(i,:);
distances = sqdistances(x,traindata); % get distances to all training points
[tmp index] = sort(distances);
% sort the distances, store indices in "index"
nnlabels = trainlabels(index(1:k));
% determine the labels of k neighbors
class_predictions(i) = round(mean(nnlabels)); % vote and get a label
end