2
$\begingroup$

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?

$\endgroup$
  • $\begingroup$ Try f[l_?NumericQ] := Module[{kk = First[NDSolve[{\[FormalY]'[x] == 2 x + 3, \[FormalY][l] == 0}, \[FormalY], {x, 0, l}]]}, \[FormalY][0] /. kk] $\endgroup$ – J. M. will be back soon Jun 12 '12 at 13:25
  • 1
    $\begingroup$ This article helps explain what ?NumericQ is doing. support.wolfram.com/kb/3820 $\endgroup$ – Searke Jun 12 '12 at 19:58
8
$\begingroup$

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

enter image description here

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

$\endgroup$
  • $\begingroup$ thank you very much J.M. and dear PlatoManiac $\endgroup$ – vahid iraji Jun 12 '12 at 13:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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