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 have a list, obtained after differentiating a list of expressions, which contains zeros and symbols, say:

A = {x1^2, x2^2, x3^2, x4^2}
D[A,x3]

results in the list:

{0, 0, 2 x3, 0}

How do I get the position of the non-zero entry, mathematica cannot compare symbols to zero directly. I could convert the elements of the list to strings but is there a faster way?

share|improve this question
    
Have a look at === vs ==. Posting your code is also a good idea. –  Yves Klett May 3 at 9:37
    
Position[D[A, x3], x_ /; ! TrueQ[x == 0], {1}, Heads -> False] –  Kuba May 3 at 9:41
    
Also Position[D[A, x3], Except[0], 1, Heads -> False] –  belisarius May 3 at 9:55
    
Also ArrayRules[D[A, x3]][[;; -2, 1, 1]] –  belisarius May 3 at 9:59
    
@YvesKlett, my code involves symbolic calculation with many subscripts, which does not look good when posted. –  vesofilev May 3 at 10:10

1 Answer 1

I've failed to find good topic to mark it a duplicate so this is the answer.

Let's assume your list is:

list = {0, 2 x3, 0.}

so we 0 is not 0. and missing this may cause troubles while pattern matching. Take a look here and there.

SparseArray[list]["NonzeroPositions"]
{{2}}

or alternatively:

Position[list, x_ /; ! TrueQ[x == 0], {1}, Heads -> False]
share|improve this answer
1  
The "NonzeroPositions" method should be the fastest available. It however does not work on a list that contains other lists, i.e. fails VectorQ but does not pass ArrayQ. One could replace List expressions first, e.g.: Replace[list, _List -> 1, {1}] –  Mr.Wizard May 3 at 11:55
    
@Mr.Wizard Thanks for the notes. General answer may be long, I'm no really interested in elaborating this subject, mainly because of lack of knowldge. But if you want to do this I will gladly upvote it and delete mine. –  Kuba May 3 at 12:17
    
No need for that. :-) I think this has it covered now. –  Mr.Wizard May 3 at 12:23

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.