This question (and the first answer in particular), teaches us how to find all the local maxima and minima of a function.
My question is: how can I separate the maxima from the minima? My goal is to find the curve that fits all the local maxima
Using the code from the cited answer:
GetRLine3[MMStdata_, IO_: 1][x_: x] :=
ListInterpolation[#, InterpolationOrder -> IO, Method -> "Spline"][
x] & /@ (({{#[[1]]}, #[[2]]}) & /@ # & /@ MMStdata);
data = Transpose[{# + RandomReal[]*0.1 & /@ Range[-10, 30, 0.4],
Tanh[#] + (Sech[2 x - 0.5]/1.5 + 1.5) /. x -> # & /@
Range[-4, 4, 0.08]}];
xLimits = {Min@#1, Max@#1} & @@ Transpose[data];
f = First[100*D[GetRLine3[{data}, 3][x], x]];
vals = Reap[
soln = y[x] /.
First[NDSolve[{y'[x] == Evaluate[D[f, x]],
y[-9.9] == (f /. x -> -9.9)}, y[x], {x, -9.9, 30},
Method -> {"EventLocator", "Event" -> y'[x],
"EventAction" :> Sow[{x, y[x]}]}]]][[2, 1]];
I tried to modify it using WhenEvent
, instead:
vals = Reap[
soln = y[x] /.
First[NDSolve[y'[x] == Evaluate[D[f, x]], y[-9.9] == (f /. x -> -9.9),
WhenEvent[y'[x] == 0 && y''[x] <= 0, Sow[{x, y[x]}],
y[x], {x, -9.9,30}]]]][[2, 1]];
I used it because I need the maxima, therefore the point with a negative second derivative, but I only get a long sequence of errors.