1

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?

dashmile
  • 31
  • 4

1 Answers1

0

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.}}

kglr
  • 394,356
  • 18
  • 477
  • 896