0
$\begingroup$

I got a real array A, where Dimensions[A] == {5000, 5000, 5}.

Some of the values in A are -1, others are not.

How can I use Position[] to find the indices of those values which are not -1?

$\endgroup$
  • $\begingroup$ It is easy to Position[A,-1] all the indices which are -1. How to find all other indices ? $\endgroup$ – LCFactorization Nov 24 '13 at 7:41
6
$\begingroup$
A = Table[If[Round@# == -1, -1, #] &[RandomReal[{-2, 0}]], {5}, {5}]

{{-1, -1.85034, -0.063618, -1.97166, -1.98232},
 {-1, -0.407057, -1.72254, -1.5231, -1.99315},
 {-1, -1, -1, -1.98979, -1},
 {-1, -1, -0.134094, -1.92523, -1.90799},
 {-0.304344, -1, -1, -1.91487, -1.66092}}

SparseArray[A, Automatic, -1]["NonzeroPositions"]

{{1,2}, {1,3}, {1,4}, {1,5}, {2,2}, {2,3}, {2,4}, {2,5}, {3,4}, {4,3}, {4,4}, {4,5}, {5,1}, {5,4}, {5,5}}
$\endgroup$
  • $\begingroup$ Error message of an example: "Part specification \!(\"NonzeroPositions\") is neither a \ machine-sized integer nor a list of machine-sized integers" $\endgroup$ – LCFactorization Nov 24 '13 at 8:14
  • $\begingroup$ "NonzeroPositions" is a function argument, not a part. Did you use double brackets instead of single? $\endgroup$ – Ray Koopman Nov 24 '13 at 8:36
  • $\begingroup$ It works! thanks $\endgroup$ – LCFactorization Nov 24 '13 at 8:39
  • $\begingroup$ That's the one to use. +1 $\endgroup$ – Mr.Wizard Nov 24 '13 at 11:17
3
$\begingroup$

Position[A, Except[-1], {-1}, Heads -> False]

$\endgroup$
  • $\begingroup$ It does not work for the code "Position[{1, 2, -1, 3}, Except[-1], {2}, Heads -> False]" $\endgroup$ – LCFactorization Nov 24 '13 at 8:35
  • 1
    $\begingroup$ I assumed A was two dimensional, like you said in the question. Fortunately it's easy to fix; see edited answer. $\endgroup$ – Aky Nov 24 '13 at 8:42
  • $\begingroup$ I would assume A to be any dimensional array /list. This should also be an answer. How can I accept both them? $\endgroup$ – LCFactorization Nov 24 '13 at 8:45
  • 1
    $\begingroup$ @LCFactorization when you say the word Matrix in your question I got a real matrix A, it implies 2D matrix. A list such as {1,2,3} is not a matrix. Matrix is rectangular. Always. en.wikipedia.org/wiki/Matrix_%28mathematics%29 $\endgroup$ – Nasser Nov 24 '13 at 8:47
  • $\begingroup$ I agree. thanks for pointing out this. $\endgroup$ – LCFactorization Nov 24 '13 at 8:48
0
$\begingroup$

Below the code will be OK . thanks

 Position[Boole[(# != -1) & /@ A], 1];
$\endgroup$
  • 1
    $\begingroup$ The above does not work. Try A = Table[If[Round@# == -1, -1, #] &[RandomReal[{-2, 0}]], {5}, {5}]; Position[Boole[(# != -1) & /@ A], 1] $\endgroup$ – Nasser Nov 24 '13 at 8:50

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.