For Example, list=RandomInteger[{1,100},2000]
. Yes,I know Position[list,Max[list]]
can do. But it's based on pattern matching! Ordering[list,-1]
could find one position but not all. So how to find all the positions of max value of list
in a more efficient way?Thank you.
Answer
A fast uncompiled alternative without pattern matching is to use the NonzeroPositions
property of SparseArray
, as long as you're dealing with numerical data.
list = RandomInteger[{1, 100}, 10^7];
SparseArray[Unitize[list - Max[list]] - 1]["NonzeroPositions"]; // RepeatedTiming
(* 0.0855 *)
Position[list, Max[list]] // RepeatedTiming
(* 0.509 *)
compPos[list, Max[list]] // RepeatedTiming (* Marius' solution *)
(* 0.0366 *)
SparseArray[Unitize[list - Max[list]], Automatic, 1][
"NonzeroPositions"]; // RepeatedTiming (* MichaelE2's solutions *)
(* 0.0663 *)
Comments
Post a Comment