4
$\begingroup$

I would like to find the positions of multiple occurrences of a minimum value in a list. For instance, for the list {1, 2, 1, 3}, I want to obtain the two positions for the occurrences of the number 1.

MinimalBy[{1, 2, 1, 3}, id (x)] gives me these occurrences, but not the positions.

$\endgroup$
3
  • 1
    $\begingroup$ MinimalBy[Range@Length@list, list[[#]] &]? $\endgroup$
    – Michael E2
    Commented May 2, 2019 at 3:05
  • 1
    $\begingroup$ Or modifying this answer: minpos[a_] := SparseArray[UnitStep[# - a]]["AdjacencyLists"] &@Min@a and then minpos[list]. $\endgroup$
    – Michael E2
    Commented May 2, 2019 at 3:11
  • $\begingroup$ Possible duplicate: mathematica.stackexchange.com/questions/40231/… $\endgroup$
    – Michael E2
    Commented May 2, 2019 at 3:13

3 Answers 3

6
$\begingroup$
lst = {1, 2, 1, 3};
Random`Private`PositionsOf[lst, Min @ lst]

{1, 3}

Also

 Flatten@Position[lst, Min @ lst]

{1, 3}

$\endgroup$
3
$\begingroup$
list = {1, 2, 1, 3}
PositionIndex[list][Min[list]]

{1, 3}

$\endgroup$
2
  • $\begingroup$ Even more appropriate for the task is: :PositionSmallest[list] $\endgroup$ Commented Apr 26, 2023 at 6:46
  • $\begingroup$ @MichaelWeyrauch You should write it as an answer. I am running v12.2.0 which is a few years old. $\endgroup$
    – Syed
    Commented Apr 26, 2023 at 11:45
3
$\begingroup$

o.k. as suggested by Syed, here comes my answer: As of Mathematica Version 13.2:

list={1,2,1,3}
PositionSmallest[list]

{1, 3}

Also there is:

PositionLargest[list]

{4}

$\endgroup$
1
  • $\begingroup$ I love the new PositionSmallest and PositionLargest functions---significantly cleaner syntax for this common issue. I am left scratching my head, however, as to how it took until v13.x for them to be introduced... $\endgroup$
    – erfink
    Commented Apr 27, 2023 at 1:17

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.