I need to create code that identifies the positions of all maximum elements of a list. I already know that if myList
contains only numbers, I can do
mList={0,1}
Position[myList,Max[myList]]
This will return, as expected, {{2}}
.
However my case is a bit more complicated because the list contains variables.
Here is an example to illustrate:
myList = {1, a};
Position[myList, Max[myList]]
This returns {}
.
I fully understand that this is because none of the elements in myList
matches the expression Max[1,a]
.
I've tried various variants of the following, to no avail:
PiecewiseExpand[Max[myList]]
Position[myList,%]
The first line returns, as expected: "1 if a<=1, a otherwise". But the second line returns {}
. (Again, I understand that this is because the list elements don't match the piecewise function.)
Is there a way to change this code so that I get the following desired result:
"1 if a <=1; 2 otherwise"
(That is: I want the output to be the unevaluated conditional statement.)
Answer
posMax[list_] := Module[{pw = PiecewiseExpand[Max[list]]},
If[NumericQ@pw, Position[list, pw], MapAt[Position[list, #] &, pw, {{1, All, 1}, {2}}]]]
Examples:
posMax[{0, 3, 2}]
{{2}}
posMax[{0, a}] // TeXForm
$\begin{cases} \left( \begin{array}{c} 2 \\ \end{array} \right) & a>0 \\ \left( \begin{array}{c} 1 \\ \end{array} \right) & \text{True} \end{cases}$
posMax[{0, 1, a, b}] // TeXForm
$\begin{cases} \left( \begin{array}{c} 2 \\ \end{array} \right) & a\leq 1\land b\leq 1 \\ \left( \begin{array}{c} 3 \\ \end{array} \right) & a>1\land a-b\geq 0 \\ \left( \begin{array}{c} 4 \\ \end{array} \right) & \text{True} \end{cases}$
Comments
Post a Comment