Re: replace with closest value
- To: mathgroup at smc.vnet.net
- Subject: [mg119548] Re: replace with closest value
- From: Stefan Salanski <wutchamacallit27 at gmail.com>
- Date: Wed, 8 Jun 2011 07:16:39 -0400 (EDT)
- References: <iskvgs$5nt$1@smc.vnet.net>
On Jun 7, 6:45 am, graser <gra... at gmail.com> wrote: > Hi > > I have a some question for you! > > Let's say there is a list like that > AA={1.3, 1.5, 1.6, 1.8, 2.1, 2.3, 2.6, 2.9, 3.3, 3.7, 4.2, 4.7, 5.2, > 5.9, 6.6, 7.4, 8.3, 9.4, 10.6, 11.8, 13.1, 14.8, 16.9, 19., 21.5, > 23.6}. > Length[AA]=26 > I want to replace the element in the list with a closest number I > specify in my list BB, > BB={1.2, 1.4, 1.6, 1.8, 2, 2.25, 2.5, 2.75, 3, 3.25, 3.5, 3.75, 4, 5, > 6, 8 , 10 , 15, 20, 25, 40, 60, 100}, > Length[BB]=23 > so that the list AA after I replace will be > > AA={1.2, 1.5, 1.6, 1.8, 2. 2.25, 2.5,3.........20, 25} > Length[AA]=26. > > I wonder if anyone can help me to solve this problem! So there's a function called Nearest, which sounds like it fits your situation pretty well. However I think we might need some clarification on what exactly you want. First of all, your very first element in AA is 1.3, which is equally close to 1.2 and 1.4 in BB. And the next one 1.5 is equally close to 1.4 and 1.6. Do you care which one gets chosen? A short bit of code to do this using Nearest would be First@Nearest[BB, #] & /@ AA {1.4, 1.4, 1.6, 1.8, 2, 2.25, 2.5, 3, 3.25, 3.75, 4, 5, 5, 6, 6, 8, 8, 10, 10, 10, 15, 15, 15, 20, 20, 25} I threw the 'First' on there to specify that in a tie, to just pick the first one. You could of course pick the last one, or some specific one based on other rules you define. As a side note, I just realized that it seems like Nearest didnt actually work consistently. When there are multiple elements in the list that are 'closest' to your element, its supposed to return a list of those elements, like this: In[12] := Nearest[{1.4, 1.6}, 1.5] Out[12] = {1.4, 1.6} but it didnt do that in this case: In[13] := Nearest[{1.2, 1.4}, 1.3] Out[13] = {1.4} ??? I ran a high precision thing and the cutoff point is somewhere random, and I obviously didnt do it to high enough precision to find the point where it returns {1.2,1.4} ne[1.299999999999999933386618522490607574582099914550781] = {1.2} ne[1.299999999999999933386618522490607574582099914550782] = {1.4} Does anyone have thoughts on this? (I'm running 8.0.1 on 64 bit windows) -Stefan S