0
|
6767 Views
|
4 Replies
|
4 Total Likes
View groups...
Share
GROUPS:

# FirstPosition[ls, SelectFirst[ls, # >= 1 &]]

Posted 10 years ago
 Is there an efferent way to do this? ls = {.5, 1.0, 2.0}; FirstPosition[ls, SelectFirst[ls, # >= 1 &]] 
4 Replies
Sort By:
Posted 10 years ago
 If you know the position of something in a Mathematica expression then you can extract it from that expression using Part (the First in the last line here is because FirstPosition returns a list containing the position) ls = {.5, 1.0, 2.0}; pos = FirstPosition[ls, _?(# >= 1 &)]; ls[[First[pos]]] By the way, the ls = {.5, 1.0, 2.0}; pos = FirstPosition[ls, _?(# >= 1 &)] returns what your original code does so that's why I didn't then extract the value.
Posted 10 years ago
 The second argument of FirstPosition is a pattern. So there is no need to first find the item to explicitly use as that pattern. You can specify the pattern itself defined as asking about the pure funcition's value (True or False) as in: FirstPosition[ls, _?(# >= 1 &)] 
Posted 10 years ago
 Thanks for the reminder that the argument is a pattern but the original search is for values. Using the output of SelectFirst sets the search up for an exact match. So the naive way to find the last element won't work. ls = {.5, 1.0, 2.0}; Position[ls, SelectFirst[ls, # >= 1 &]][[-1]] {2} Neat way to force the evaluation. _?(# >= 1 &) I think Mathematica needs a LastPosition function as much as it needs FirstPosition.
Posted 10 years ago
 If you are wanting to find the position of the first element of the list that is greater than 1, then: Position[(*in list*)ls, (*of first element *)Select[ ls, # >(*greater than*)1&, 1(*EndSelect*)][] (*EndPosition*)]