function yi= interp_nearest(xdata,ydata,xi)
	%% provide interpolation by the nearest neighbor method
	% xdata, ydata - known data points
	% xi - points at which we want interpolated values yi
	% WARNING: no checks is done that xi values are inside xdata range

	% First we need to sort our input vectors
	% we need monotonous grow of x

	% Matlab sort function has extra return value index
	% with the list of indexes so xdata(index) is sorted such that x=xdata(index)
	[x,index]=sort(xdata); 
	% we reuse this index to sort 'y' vector appropriately
	y=ydata(index); 

	%% It is crucial to have yi preinitialized !
	% It significantly speeds up the algorithm, 
	% since computer does not have to reallocate memory for a new data points.
	% Try to comment the following line and compare the execution time 
	% for a large length of xi
	yi=0.*xi; % simple shortcut to initialize return vector with zeros 
	          % this also takes care of deciding  xdata type (row or column).

	N=length(xi); 
	for i=1:N % we will go through all points to be interpolated
		distance=abs(x-xi(i));
		% matlab min returns not only minimum but its index too
		[distance_min, index] = min(distance); 
		% there is a chance that 2 points of xdata have the same distance to the xi
		% so we will take the 1st one
		yi(i)=y(index(1)); 
	end
	plot(x,y,'o', xi,yi,'-');
end


