# Optimizing a function involving NDSolve results in error messages

I want to minimize a function f with NMinimize but an error occurs that says:

f[l_] := (
kk = NDSolve[{y'[x] == 2*x + 3, y[l] == 0}, y, {x, 0, l}];
out = Evaluate[y[0] /. kk];
out[[1]])

NMinimize[{f[t], 0 <= t <= 10}, f, t]


During evaluation of In[18]:= NDSolve::ndsv: Cannot find starting value for the variable y. >>

During evaluation of In[18]:= ReplaceAll::reps: {NDSolve[{(y^[Prime])[x]==3+2 x,y[{t}]==0},y,{x,0,{t}}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>

During evaluation of In[18]:= NMinimize::argrx: NMinimize called with 3 arguments; 2 arguments are expected. >>

Out[18]= NMinimize[{y[0], 0 <= t <= 10}, f, t]


How can I fix the function f to avoid this problem?

• Try f[l_?NumericQ] := Module[{kk = First[NDSolve[{\[FormalY]'[x] == 2 x + 3, \[FormalY][l] == 0}, \[FormalY], {x, 0, l}]]}, \[FormalY][0] /. kk] Commented Jun 12, 2012 at 13:25
• This article helps explain what ?NumericQ is doing. support.wolfram.com/kb/3820 Commented Jun 12, 2012 at 19:58

Check this

f[l_?NumericQ] := Module[
{kk, y, x, out},
kk = NDSolve[{y'[x] == 2*x + 3, y[l] == 0}, y, {x, 0, l}];
out = Evaluate[y[0] /. kk];
out[[1]]
];
res=NMinimize[{f[t], 0 <= t <= 10}, t]


it gives

{-130., {t -> 10.}}


You can check if the answer is correct by plotting your function.

Show[Plot[f[t], {t, 0, 10}, Frame -> True],
Graphics[{Red, PointSize[Large], Point[{res[[2, 1, 2]], res[[1]]}]}]]


Welcome to the site! But please check the other questions in the site as similar questions have been many times answered.

• thank you very much J.M. and dear PlatoManiac Commented Jun 12, 2012 at 13:41