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$>
References: <jmakc3$61e$>
Reply-To: <HIDDEN>
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: 1334376500 9980 (14 Apr 2012 04:08:20 GMT)
NNTP-Posting-Date: Sat, 14 Apr 2012 04:08:20 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: comp.soft-sys.matlab:764402

"Keith Barth" <> wrote in message <jmakc3$61e$>...
> 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