1 |
function y=closest(v,x,n) |
2 |
% function CLOSEST(V,X,N) |
3 |
% Return index of N element closest to value V in vector X. |
4 |
% By default N=1. |
5 |
% If N is zero, CLOSEST returns the two closest |
6 |
% values in vector X that straddle value V. |
7 |
% |
8 |
% See also MINMAX MMAX MMIN MMEAN |
9 |
|
10 |
% d menemenlis 8/21/95 |
11 |
|
12 |
if nargin < 3, n=1; end |
13 |
if nargin < 2, error('insufficient number of arguments'); end |
14 |
|
15 |
if n<0 |
16 |
error('N cannot be a negative number') |
17 |
elseif n==0 |
18 |
y=[nan nan]; |
19 |
ix=find(~isnan(x)&x<v); |
20 |
if ~isempty(ix) |
21 |
[my iy]=min(abs(x(ix)-v)); |
22 |
y(1)=ix(iy); |
23 |
end |
24 |
ix=find(~isnan(x)&x>=v); |
25 |
if ~isempty(ix) |
26 |
[my iy]=min(abs(x(ix)-v)); |
27 |
y(2)=ix(iy); |
28 |
end |
29 |
else |
30 |
y=nan*ones(n,1); |
31 |
for i=1:n |
32 |
ix=find(~isnan(x)); |
33 |
if ~isempty(ix) |
34 |
[my iy]=min(abs(x(ix)-v)); |
35 |
y(i)=ix(iy); |
36 |
x(y(i))=nan; |
37 |
end |
38 |
end |
39 |
end |