Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Fastest way to match the closest value in a vector.
Date: Sat, 14 Apr 2012 04:08:20 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 12
Message-ID: <jmat7k$9ns$1@newscl01ah.mathworks.com>
References: <jmakc3$61e$1@newscl01ah.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: www-03-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: newscl01ah.mathworks.com 1334376500 9980 172.30.248.48 (14 Apr 2012 04:08:20 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sat, 14 Apr 2012 04:08:20 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:764402

"Keith Barth" <denrick888@gmail.com> wrote in message <jmakc3$61e$1@newscl01ah.mathworks.com>...
> Suppose I have a vector x in ascending order that is evenly spaced. (e.g., x=linspace(0,90,N) )
> 
> Suppose x(i)=<y<x(i+1). What is the fastest way to find i?
- - - - - - - - -
  If x is evenly-spaced and ascending, then the formula

 i = floor((y-x(1))/(x(n)-x(1))*(n-1)+1);

will usually give you the correct 'i' for x(i) <= y < x(i+1) in just one step.  However, if it misses due to round off error, you can easily correct it in only one more step by adding or subtracting 1 to i as needed.

Roger Stafford