
% function knn (k nearest neighbours) finds an estimate
% for the class of a given sample, using trainX and trainY
% as guide lines for the classification.

function class = knn(k, dataPoint, trainX, trainY)

% Find out how many samples the training data contains.
trainSize = size(trainX);
Samples = trainSize(1);   

% Initialize distances vector.
distances(1:Samples) = 0;

% calculate distance between each training sample and
% the dataPoint that is to be classified.
for i=1:Samples;
    distances(i) = distance(dataPoint, trainX(i, :));
end

% sort the data in ascending distance order.
[sortedDistances, indices] = sort(distances, 'ascend');

% obtain the best guesses for the y value (class)
yvals(1:k) = trainY(indices(1:k));

% return average of the k neighbours.
class = mean(yvals);