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[0] == 1}, {f}, {z, 0, 10}]
FindMaximum[f[5] /. 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?


1 Answer 1


You can use ParametricNDSolveValue as follows:

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

FindMaximum[pfunc[t][5], {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[0] == 1}, f, {z, 0, 10}]
func[t_?NumericQ] := f[5] /. sol[t];
FindMaximum[func[t], {t, 1}]

{1.5708, {t -> 21.}}

  • $\begingroup$ 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.... $\endgroup$
    – dashmile
    Commented May 9, 2019 at 14:34
  • $\begingroup$ @dashmile, please see the update. $\endgroup$
    – kglr
    Commented May 9, 2019 at 14:46
  • $\begingroup$ Thanks! So in the end using NumericQ was the key again. $\endgroup$
    – dashmile
    Commented May 9, 2019 at 19:12

Your Answer

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

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