Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Consider a toy list

l = {x[2],x[32],x[43],x[56],x[72]};

I would like to find the position of the first element within this list, for which x[y] is such that y>N where N is a positive integer that I will specify. In case if N is bigger than any label of any x[y], then the result should be zero. So for example:

getPos[l,35]

3

getPos[l,60]

5

getPos[l,80]

0

How can I do that in an efficient manner?

share|improve this question
2  
Maybe I don't understand the question but FirstPosition? – unlikely Feb 22 at 23:10
    
Beware of things like x[n_] := 3; l = {x[2],x[32],x[43],x[56],x[72]}; – Dr. belisarius Feb 22 at 23:13
up vote 7 down vote accepted

For default you can use third arg as in

p[n_] := First@FirstPosition[l, x[k_] /; k >= n, {0}]
share|improve this answer

Thanks to a comment by unlikely here is the solution:

getPos[l_List,myN_Integer]:=FirstPosition[l,x[qq_Integer] /; qq > myN,{0}][[1]]
share|improve this answer
1  
Better to use n than N. – bbgodfrey Feb 22 at 23:16
    
Fixed it to something that starts with a lower case letter. – Kagaratsch Feb 22 at 23:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.