Path: news.mathworks.com!not-for-mail
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$1@fred.mathworks.com>
References: <gmf901$45e$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-03-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1234751221 5559 172.30.248.38 (16 Feb 2009 02:27:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 16 Feb 2009 02:27:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:518455

"megha bhatt" <mubhatt19@yahoo.co.in> wrote in message <gmf901$45e$1@fred.mathworks.com>...
> 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