[Date Index]
[Thread Index]
[Author Index]
Re: Finding position of an element in a list:
*To*: mathgroup at smc.vnet.net
*Subject*: [mg84015] Re: Finding position of an element in a list:
*From*: Albert Retey <awnl at arcor.net>
*Date*: Thu, 6 Dec 2007 07:25:32 -0500 (EST)
*References*: <fj89m3$a90$1@smc.vnet.net>
Hi,
> (This is an easy problem, but I was unable to get it work in Mathematica,
> probably because of the precision - I tried setting precision too, still got stuck)
this has presumably absolutely nothing to do with precision...
> Suppose we have a list, xlis, having some elements, and I have to find one
> nearest value I am interested in that list. In the below example, I
> wanted to find the position of a number belonging to list and close to 6
> (which is 5.5 located at 7th).
> I can do this:
>
> xlis = {0, 1, 3, 10, 4, 5, 5.5, 10.25};
> dropOuterBraces[lst_List] :=
> StringTake[#1, {2, StringLength[#1] - 1}] &[
> ToString[lst]]; (* took from previous help posted by Peter Pein *)
I don't think that this function is a good choice for the problem at
hand: conversion of expressions to string to manipulate them is rarely a
good idea and I think Peter's function served a very different purpose...
> n1 = Nearest[xlis, 6]
> eval = dropOuterBraces[n1]
If you use InputForm[eval] or FullForm[eval] you will find that
dropOuterBraces returns a string, not a number, so it is the expected
behavior that no occurance of the string "5.5" is found within the list
containing the number 5.5. One solution could be to revert eval to a
number with ToExpression[eval], but why not just use:
n1=First[Nearest[xlis,6]]
Position[xlis,n1]
which extracts the first element of the list which Nearest returns and
works perfectly for me. Note that Nearest returns always a list,
presumably since
1. it is possible to have more than one nearest member, like in:
Nearest[{1,3},2]
2. it is possible to ask Nearest for the n nearest, like in:
Nearest[{1,2,3,4,5,6,7,8,9},5,4]
In your case, only the first of these cases could make Nearest return a
list longer than one. In this case additional information is needed to
decide which one you want n1 to be set to. Also note that
dropOuterBraces would return a string "1,3" for case 1, which doesn't
make sense even if converted back with ToExpression.
Conclusion: don't use ToString when not necessary...
hth,
albert
Prev by Date:
**Re: MathLink and VC++ 2008**
Next by Date:
**Ndsolve**
Previous by thread:
**Re: Finding position of an element in a list:**
Next by thread:
**Re: Finding position of an element in a list:**
| |