2
$\begingroup$

Say I have a function $f(x,y)$ that depends on two variables. How can I find the maximum of the function $f(x,y) \big|_{y = constant}$ for every value of $y$ and plot the value of $f(x_{max}(y), y)$ vs $y$? (I.e. $x_{max}(y)$ is the minimum of the function for a given value of $y$.)

So this would plot the trajectory of the maxima, which could be seen as a ridge of the function.

The solution does not have to be analytic, numerical is fine.


Example:

f = -(x^2 + 1)*(y^2 + 1)
DensityPlot[f, {x, -10, 10}, {y, -10, 10}, PlotRange -> Automatic, PlotLegends -> Automatic, MaxRecursion -> 10]
Plot[f /. x -> 0, {y, -10, 10}]

So here it is trivial to find the maximum of the function at constant $y$, it is simply $x_{max}(y)=0$. The desired plot is the last one, except that instead of f/.x->0 a function that finds the maximum at each $y$ is required.

$\endgroup$
2
  • 1
    $\begingroup$ Have you tried Plot[NMaxValue[-(x^2 + 1)*(y^2 + 1), x], {y, -10, 10}]? $\endgroup$ Aug 23, 2017 at 13:24
  • $\begingroup$ @J.M. that works! I was not aware of the NMaxValue command. $\endgroup$ Aug 23, 2017 at 13:53

1 Answer 1

2
$\begingroup$
f = -(x^2 + 1)*(y^2 + 1);

max = MaxValue[f /. y :> #, {x}] & /@ Range[-10, 10, 1];

{-101, -82, -65, -50, -37, -26, -17, -10, -5, -2, -1, -2, -5, -10, -17, -26, -37, -50, -65, -82, -101}

ListLinePlot[max, DataRange -> {-10, 10}]

enter image description here

To visualize it in 3D you can use MeshFunctions:

fun[x_, y_] := -(x^2 + 1)*(y^2 + 1)

Plot3D[fun[x, y], {x, -10, 10}, {y, -10, 10},
 MeshFunctions -> (ConditionalExpression[
     Derivative[1, 0][fun][#1, #2], 
     Derivative[2, 0][fun][#1, #2] < 0] &),
 MeshStyle -> Directive[Red, Thickness[0.02]],
 Mesh -> {{0}},
 PlotRange -> {Automatic, Automatic, {-100, 100}}]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.