MathGroup Archive 2011

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: With Nearest

  • To: mathgroup at smc.vnet.net
  • Subject: [mg121124] Re: With Nearest
  • From: Daniel Lichtblau <danl at wolfram.com>
  • Date: Mon, 29 Aug 2011 20:01:00 -0400 (EDT)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com
  • References: <j3anc3$hdo$1@smc.vnet.net> <201108290747.DAA15666@smc.vnet.net>

On 08/29/2011 02:47 AM, Ray Koopman wrote:
> On Aug 27, 5:19 am, graser<gra... at gmail.com>  wrote:
>> Dear Mathematica group,
>> I have a simple question for you.
>> Let's say there is an array or matrix like
>>
>> AA = {{1.3, 1.5}, {21.5, 23.6}, {10, 19}};
>>
>> If I want to extract a list whose second element is close to 20,
>> How can I do it with Nearest function?
>> Or is there any other method possible?
>> ( In this case, the answer should be {10, 19} )
>>
>> Thanks!
>
> If AA is long then
>
>     AA[[ Ordering[ Abs[ AA[[All,2]] - 20 ], 1] [[1]] ]]
> or
>     Extract[ AA, Ordering[ Abs[ AA[[All,2]] - 20 ], 1] ]
>
> will be much faster than anything using Nearest.

That's quite true.

In[6]:= aa = RandomReal[40, {10^5,2}];

In[7]:= Timing[func = Nearest[Map[#[[2]]->#&, aa]];]
Out[7]= {0.17, Null}

In[8]:= Timing[aa[[ Ordering[ Abs[ aa[[All,2]] - 20 ], 1] [[1]] ]]]
Out[8]= {0.01, {23.7973, 19.9997}}

In[9]:= Timing[func[20]]
Out[9]= {0., {{23.7973, 19.9997}}}

But the Nearest approach does have some added flexibility in that it can 
be reused for values other than 20. Whether this is important would 
depend on the application, of course.

Daniel Lichtblau
Wolfram Research




  • Prev by Date: Re: NDSolve solution does not fulfill boundary condition
  • Next by Date: Re: NDSolve solution does not fulfill boundary condition ??
  • Previous by thread: Re: With Nearest
  • Next by thread: Function of N variable