function val=knn(xtrain,ytrain,x,k)

% Compute array of distances between x and training set
dist=abs(xtrain-x);

% Sort array dist; keep indices 
[t,idx] = sort(dist);

% Reorder yvalues based on order idx
y=ytrain(idx);

% compute estimate of y
val = sum(y(1:k))/k;

return;
