# FindMaximum with parametrized NDSolve

I am trying to solve a parametrized ODE, and wanting to find the parameter that maximize the solution at a specific point.

For example, in the following code I am trying to solve the ODE $$df/dz=t \cos(f)$$ that is parametrized by $$t$$ and find the parameter $$t$$ that maximized the solution at $$z=5$$:

sol[t_?NumericQ] :=
First@NDSolve[{f'[z] == t Cos[f[z]], f == 1}, {f}, {z, 0, 10}]
FindMaximum[f /. sol[t], {t, 1}]


Execution of the code finds an answer, but with a bunch of error messages like

ReplaceAll: {sol[t]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing


Note that I have specified that the parameter t is a numerical value by t_?NumericQ above. This has been suggested as the solution to similar problems in this forum, e.g. in optimization problem with NDSolve, but it doesn't solve my issue.

Any help?

You can use ParametricNDSolveValue as follows:

pfunc = ParametricNDSolveValue[{f'[z] == t Cos[f[z]], f == 1}, f, {z, 0, 10}, {t}];

FindMaximum[pfunc[t], {t, 1}]


{1.5708, {t -> 21.}}

Update: "is there a way to use NDSolve?"

ClearAll[sol, func]
sol[t_?NumericQ] := First @ NDSolve[{f'[z] == t  Cos[f[z]], f == 1}, f, {z, 0, 10}]
func[t_?NumericQ] := f /. sol[t];
FindMaximum[func[t], {t, 1}]


{1.5708, {t -> 21.}}

• Thanks for the reply, but is there a way to use NDSolve? The actual problem is more complicated, and it will be the best to use NDSolve in that situation.... – dashmile May 9 '19 at 14:34
• @dashmile, please see the update. – kglr May 9 '19 at 14:46
• Thanks! So in the end using NumericQ was the key again. – dashmile May 9 '19 at 19:12