Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I need to find the position of the first element of a list that is either greater than zero (or some other criterion) or a symbol.

Something like

 lst={0,0,k,1,4}

and as result

 position = 3

If there was no symbol the following command would do the job

 First[Flatten[Position[lst, _?(Abs[#] > 0 &)]]]

If I add || MatchQ[_Symbol] the answer will always be zero.

Many thanks

share|improve this question
    
How about First[Flatten[Position[lst, _?(NumericQ[#] && Abs[#] > 0 &)]]] ? –  b.gatessucks Jan 14 '13 at 12:29

2 Answers 2

up vote 4 down vote accepted
 Position[lst, Except[0|0., _], {0, Infinity}, 1, Heads -> False][[1,1]]

or

 Cases[lst, {zeros : (0|0.) ..., Except[0|0.], ___} :> 1 + Length[{zeros}], {0}][[1]]

or

 Length@First@Split[lst, #1 == 0 &]

or

 1 + LengthWhile[lst, # == 0 &]

all give 3.

share|improve this answer
    
I just realized that I misunderstood the question. Oops. –  Mr.Wizard Jan 14 '13 at 13:23
    
I'm a bit confused by your code. Why are you looking at levels down to Infinity in the first line? Why are you assuming that the only non-negative numbers are 0? Maybe I still don't understand the question. –  Mr.Wizard Jan 14 '13 at 13:31
    
@kguler - Many thanks, however there is a problem if one has 0. instead of 0 for the first two options. Third works great. Many thanks. –  Ed Mendes Jan 14 '13 at 13:32
    
@EdMendes, excellent point.. will fix in a moment. –  kguler Jan 14 '13 at 13:38
1  
@Mr.W, {0,Inifinity} is my "instinctive default" levelspec ; it is not necessary in this case, 1 or {1} sufficient. Regarding "the only non-negative numbers..", I was going with the condition _?(Abs[#] > 0 &) in Ed's code. –  kguler Jan 14 '13 at 13:52

I misread the question. Assuming I now understand you just want:

lst = {0, 0, k, 1, 4}

Position[lst, _?Positive | _Symbol, 1, 1, Heads -> False][[1, 1]]
3

My misreading was itself an interesting problem. I thought you wanted the position of the first positive value as if the symbols were not in the list. For example:

lst = {b, 0, k, 0, 1, 4}

Position[
 Cases[lst, _?NumericQ],
 _?Positive, 1, 1
][[1, 1]]
3

because 1 is at position three in {0, 0, 1, 4}.

share|improve this answer
    
Wizard - Many thanks. It does not seem to work with a list such as {k,2k,a} though. –  Ed Mendes Jan 14 '13 at 12:50

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.