4
$\begingroup$

How do I determine the position of rows whose entries all satisfy some condition (e.g., all elements of the row are positive)? I've found out how to use Select to extract the correct rows, but I haven't been able to find out how to use Position to do the equivalent.

A = {{-1, 2, 3}, {4, 5, 6}, {-7, 8, 9}}
Select[A, And @@ Thread[# > 0] &]

gives

{{4, 5, 6}}

but I want to know the position of that row (i.e. {2}).

$\endgroup$
  • 1
    $\begingroup$ Position[And @@ Thread[# > 0] & /@ A, True]? $\endgroup$ – kglr Feb 4 '15 at 22:54
  • $\begingroup$ wonderful. thanks! $\endgroup$ – user12734 Feb 5 '15 at 0:11
4
$\begingroup$

Use the function VectorQ,

A = {{-1, 2, 3}, {4, 5, 6}, {-7, 8, 9}};
Position[A, x_ /; VectorQ[x, # > 0 &], {1}]

or

Position[VectorQ[#, # > 0 &] & /@ A, True, {1}]

As Mr.Wizard points out that you should use a levelspec {1} to avoid testing subexpressions.

$\endgroup$
  • 2
    $\begingroup$ A good choice as VectorQ has early exit behavior, and does not unpack packed arrays. +1 (Edit: however, you should use a levelspec {1} to avoid testing subexpressions and losing this benefit.) $\endgroup$ – Mr.Wizard Feb 5 '15 at 8:31
  • 1
    $\begingroup$ @Mr.Wizard is there any nice thread what can unpack? $\endgroup$ – Kuba Feb 5 '15 at 8:31
  • 1
    $\begingroup$ @Kuba You mean this? $\endgroup$ – Mr.Wizard Feb 5 '15 at 8:32
  • $\begingroup$ @Mr.Wizard it seems so, thanks :) $\endgroup$ – Kuba Feb 5 '15 at 8:33
3
$\begingroup$
aA = {{-1, 2, 3}, {4, 5, 6}, {-7, 8, 9}};

Position[And @@ Thread[# > 0] & /@ aA, True]
(* {{2}} *)

Or, using the third argument of Position to set the levelspec to 1:

Position[aA, _?(And @@ Thread[# > 0] &), 1]
(* {{2}} *)
$\endgroup$
1
$\begingroup$

Without #, yeah:

Position[A, {__?Positive}, {1}]
{{2}}
$\endgroup$

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.