4

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?

vesofilev
  • 41
  • 1
  • 2

1 Answers1

6

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]
Kuba
  • 136,707
  • 13
  • 279
  • 740
  • 3
    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 03 '14 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 03 '14 at 12:17
  • No need for that. :-) I think this has it covered now. – Mr.Wizard May 03 '14 at 12:23
  • In some use-cases, one might want Position[list, x_ /; ! PossibleZeroQ[x], {1}, Heads -> False] or other methods of checking sameness/zero/etc. – Michael E2 Oct 31 '21 at 16:52