4
$\begingroup$

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?

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

1 Answer 1

6
$\begingroup$

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]
$\endgroup$
4
  • 3
    $\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
    Commented May 3, 2014 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
    Commented May 3, 2014 at 12:17
  • $\begingroup$ No need for that. :-) I think this has it covered now. $\endgroup$
    – Mr.Wizard
    Commented May 3, 2014 at 12:23
  • $\begingroup$ In some use-cases, one might want Position[list, x_ /; ! PossibleZeroQ[x], {1}, Heads -> False] or other methods of checking sameness/zero/etc. $\endgroup$
    – Michael E2
    Commented Oct 31, 2021 at 16:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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