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$
2
  • $\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$ Commented Jun 12, 2012 at 13:25
  • 1
    $\begingroup$ This article helps explain what ?NumericQ is doing. support.wolfram.com/kb/3820 $\endgroup$
    – Searke
    Commented Jun 12, 2012 at 19:58

1 Answer 1

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$
1
  • $\begingroup$ thank you very much J.M. and dear PlatoManiac $\endgroup$ Commented Jun 12, 2012 at 13:41

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.