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}

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?

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

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.


or alternatively:

Position[list, x_ /; ! TrueQ[x == 0], {1}, Heads -> False]
  • 2
    $\begingroup$ 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}] $\endgroup$ – Mr.Wizard May 3 '14 at 11:55
  • $\begingroup$ @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. $\endgroup$ – Kuba May 3 '14 at 12:17
  • $\begingroup$ No need for that. :-) I think this has it covered now. $\endgroup$ – Mr.Wizard May 3 '14 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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