# Plotting an association key corresponding to the maximum value

I have an Association <|0->q^2, 1->2p q, 2->p^2|>, where q=1-p. I would like to plot the key (0, 1 or 2) corresponding to the greatest value, as a piecewise function of p, where p is between 0 and 1.

This is what I have tried:

assoc=<|0->q^2, 1->2p q, 2->p^2|>;
keys=Keys[assoc];
values=Values[assoc];
optimalkey=keys[[Position[values,Max[values]][[1,1]]]];
Plot[Evaluate[optimalkey/.q->1-p],{p,0,1}]


This causes the error messages "Part 1 of {} does not exist", and several repetitions of "The expression {}[[1,1]] cannot be used as a Part specification."

However, I notice that

assoc=<|0->q^2, 1->2p q, 2->p^2|>;
keys=Keys[assoc];
values=Values[assoc];
optimalvalue=Max[values];
Plot[Evaluate[optimalvalue/.q->1-p],{p,0,1}]


produces a nice plot of a piecewise polynomial function, as expected and without generating any errors.

• Plot[keys[[Position[values /. q -> 1 -p, Max[values /.q -> 1 -p]] [[1, 1]]]], {p, 0, 1}]?
– kglr
Commented Feb 25, 2018 at 2:10
• or. Plot[With[{vals=values/. q->1-p},keys[[Position[vals, Max[vals]][[1,1]]]]],{p,0,1}]?
– kglr
Commented Feb 25, 2018 at 2:14
• or, optimalkey[v_] := keys[[Position[v, Max[v]][[1, 1]]]]; Plot[With[{p=p,q=1-p},optimalkey[values]] , {p, 0, 1}]
– kglr
Commented Feb 25, 2018 at 2:31
• Thank you very much kglr !!! Commented Feb 25, 2018 at 20:17

In

optimalkey=keys[[Position[values,Max[values]][[1,1]]]];


Max cannot return a value because values are expressions involving p and q; they are symbols with no values stored in them hence Max returns unevaluated. What that means is that when Position uses its second argument, it cannot match anything in values (since it is devoid of an expression with head Max) so it returns {}. In turn, {}[[1,1]] generates the error message, reported in the question.

On the other hand, plotting Max[values], on the second code block, does not produce exactly what is expected. Like in the previous case, Max does not return a value, so plotting simply uses the monomials in the input association.

Block[{p,q},
With[{assoc=<|0->q^2, 1->2p q, 2->p^2|>},
getMax[pval_]:=Max[assoc/.{q->1-pval,p->pval}]
]
]


getMax should provide the desired values.

Note: the second code block in the question, probably returns the correct output.

• Many thanks, yosimitsu ! Commented Feb 25, 2018 at 20:18