Warning, /verification/natl_box/input/closest.m is written in an unsupported language. File is not indexed.
view on githubraw file Latest commit a7207395 on 2006-01-30 23:51:50 UTC
a7207395ee Dimi*0001 function y=closest(v,x,n)
0002 % function CLOSEST(V,X,N)
0003 % Return index of N element closest to value V in vector X.
0004 % By default N=1.
0005 % If N is zero, CLOSEST returns the two closest
0006 % values in vector X that straddle value V.
0007 %
0008 % See also MINMAX MMAX MMIN MMEAN
0009
0010 % d menemenlis 8/21/95
0011
0012 if nargin < 3, n=1; end
0013 if nargin < 2, error('insufficient number of arguments'); end
0014
0015 if n<0
0016 error('N cannot be a negative number')
0017 elseif n==0
0018 y=[nan nan];
0019 ix=find(~isnan(x)&x<v);
0020 if ~isempty(ix)
0021 [my iy]=min(abs(x(ix)-v));
0022 y(1)=ix(iy);
0023 end
0024 ix=find(~isnan(x)&x>=v);
0025 if ~isempty(ix)
0026 [my iy]=min(abs(x(ix)-v));
0027 y(2)=ix(iy);
0028 end
0029 else
0030 y=nan*ones(n,1);
0031 for i=1:n
0032 ix=find(~isnan(x));
0033 if ~isempty(ix)
0034 [my iy]=min(abs(x(ix)-v));
0035 y(i)=ix(iy);
0036 x(y(i))=nan;
0037 end
0038 end
0039 end