1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
function test_data = knn(test_data, tr_data,k)
test_data_n = size(test_data,1);
tr_data_n = size(tr_data,1);
%Step 1: Computing euclidean distance for each testdata
dist = abs(repmat(test_data,1,tr_data_n) - repmat(tr_data(:,1)',test_data_n,1));
%Step 2: compute k nearest neighbors and store them in an array
[~,position] = sort(euclideandistance);
A = tr_data(position(1:k),2);
M = mode(A);
if (M~=1)
test_data(sample,2) = M;
else
test_data(sample,2) = tr_data(position(1),2);
[M,F] = mode(knntrdata);
end
end |
Partager