x = {4, 1, 2, 5, 6, 7}
y = {1, 2, 4, 5, 6, 9}
There are two lists x and y. How to find out these positions of the elements in list x are smaller than those in corresponding list y and get the following results:
{2, 3, 6}
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityFlatten@Position[Negative[x - y], True]
Also possible:
Flatten@Position[x - y, _?(# < 0 &)]
or, as suggested by J.M.,
Flatten[Position[x - y, _?Negative]]
NegativeQ
rather than Negative
btw... !
$\endgroup$
Feb 3, 2020 at 13:15
Negative[]
and similar functions don't have to immediately evaluate to True
/False
(while *Q[]
functions do so), which makes them usable in assumptions like Assuming[Negative[x], Simplify[UnitStep[x]]]
. (On that note, you can do your last one as Flatten[Position[x - y, _?Negative]]
)
$\endgroup$
Feb 3, 2020 at 13:26
Flatten @ Position[Less @@@ Transpose[{x, y}], True]
Flatten[Position[Thread[x < y], True]]
$\endgroup$
Feb 3, 2020 at 13:27
PositionIndex[Sign[x - y]] @ -1
{2, 3, 6}
Also
PositionIndex[UnitStep[x - y]] @ 0 (* thanks: J.M. *)
{2, 3, 6}
PositionIndex[Negative[x - y]] @ True (* thanks: anderstood *)
{2, 3, 6}
PositionIndex[Thread[x < y]]@True
{2, 3, 6}
If you prefer to have {}
(rather than Missing["KeyAbsent", _]
) as output when no positions satisfy the condition, you can use
Lookup[PositionIndex[Sign[x - y]], -1, {}]
Lookup[PositionIndex[UnitStep[x - y]], 0, {}]
Lookup[PositionIndex[Negative[x - y]], True, {}]
Lookup[PositionIndex[Thread[x < y]], True, {}]
for the four approaces above.
Lookup[PositionIndex[UnitStep[x - y]], 0]
.
$\endgroup$
Feb 3, 2020 at 13:37
PositionIndex[Negative[x - y]][True]
$\endgroup$
Feb 3, 2020 at 14:04
Using Position
and Condition
:
Position[Transpose[{x, y}], {x_, y_} /; x < y]
(*{{2}, {3}, {6}}*)
Extract[Transpose[{x, y}], Position[Transpose[{x, y}], {x_, y_} /; x < y]]
(*{{1, 2}, {2, 4}, {7, 9}}*)
Or using SubsetPosition
and Cases
:
Transpose@SubsetPosition[Transpose[{x, y}], Cases[Transpose[{x, y}], {x_, y_} /; x < y]]
(*{{2}, {3}, {6}}*)
Using MapIndexed
:
x = {4, 1, 2, 5, 6, 7};
y = {1, 2, 4, 5, 6, 9};
MapIndexed[If[Less @@ #1, First@#2, Nothing] &, Transpose@{x, y}]
{2, 3, 6}
SparseArray[Ramp[y-x]]["NonzeroPositions"]
$\endgroup$