From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: find nearest,closest value
Date: Mon, 16 Feb 2009 02:27:01 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 20
Message-ID: <gnaitl$5dn$>
References: <gmf901$45e$>
Reply-To: <HIDDEN>
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: 1234751221 5559 (16 Feb 2009 02:27:01 GMT)
NNTP-Posting-Date: Mon, 16 Feb 2009 02:27:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: comp.soft-sys.matlab:518455

"megha bhatt" <> wrote in message <gmf901$45e$>...
> Hi,
> I have two vectors a & b and I want to look for closest value of vector b in vector a one by one. How to find it?

  I put your problem aside ten days ago to look at and temporarily forgot about it.  Sorry for the delay.  I interpret your question to mean that for each element of vector 'a' you seek the nearest element of 'b' in terms of absolute difference.  The following assumes that 'a' and 'b' are row vectors and that all the elements of 'a' are finite.  It obtains the two row vectors 'd' and 'ib' of the same length as 'a'.  Each element of 'd' is the absolute difference between the corresponding element of 'a' and the nearest element of 'b'.  Each element of 'ib' is the index with respect to the 'b' vector of that corresponding nearest 'b' element.

 m = size(a,1); n = size(b,1);
 [c,p] = sort([a,b]);
 q = 1:m+n; q(p) = q;
 t = cumsum(p>m);
 r = 1:n; r(t(q(m+1:m+n))) = r;
 s = t(q(1:m));
 id = r(max(s,1));
 iu = r(min(s+1,n));
 [d,it] = min([abs(a-b(id));abs(b(iu)-a)]);
 ib = id+(it-1).*(iu-id);

  It is possible to write a somewhat shorter for-loop code for this in which a search is made for each element of 'a' for the nearest element of 'b' using the 'min' function, but that would be an order m*n algorithm as opposed to the above order (m+n)*log(m+n) algorithm (due principally to the 'sort' operation on [a,b].)  For large m and n, the sort method is therefore considerably faster.

Roger Stafford