# find derivative with defined function

  s[a_, b_] := NDSolve[{y''[x] == y[x] Cos[x + y[x]], y[0] == a, y'[0] == 1}, y, {x,0, b}]


I need to find the minimal of $\int _1^by[x]^2$ in the region $-1<a<1$ and $b>1$, and express $a$ in terms of $b$, what I am doing is like:

w[a_,b_]:=First[NIntegrate[Evaluate[y[x]^2 /. s[a, b]], {x, 0, b}]]
j[a_,b_]:=D[w[a,b],a]
h[b_]:=a/.FindRoot[j[a,b]==0,{a,0}]


I am too naive, does anyone have any idea? thanks AS Michael E2 suggests using ND, so instead of

j[a_,b_]:=D[w[a,b],a]


I change it as:

j[d_,b_]:=ND[w[a,b],{a,1},d]


but when I enter j[1,1] as a check, I receive a warning instead of the a number. So I tried b.gatessucks's suggestion, using NMinimize,

    w[b_]:=NMinimize[NIntegrate[Evaluate[y[x]^2 /. s[a, b]], {x, 0, b}],{a}]


Unfortunately, w[1] does not give a number. Anyway, thanks for your help. and thanks ruebenko

-
I think you will probably have to use ND to find the derivative in j. – Michael E2 Jul 22 '13 at 23:11
Why not using NMinimize on w ? – b.gatessucks Jul 23 '13 at 6:02

Here is a way to do it. We make it a parametric value. Note that the integration is part of that.

pf = ParametricNDSolveValue[{y''[x] == y[x] Cos[x + y[x]], y[0] == a,
y'[0] == 1}, Integrate[y[s]^2, {s, 0., b}], {x, 0, b}, {a, b}];
Plot[pf[a, 1.1], {a, -1, 1}]


Then we construct the derivative at a specific b:

dpf = D[pf[a, 1.1], a];


Note that the result is still a parametric function. Next, we need to numericalize the result from the integration as it can not evaluate other wise:

j[x_] := N[dpf /. {a -> x}]


While finding the minimum NIntegrate complains a bit but I think those are OK but you could tune this further.

FindRoot[j[a] == 0, {a, -1/2., -1., 1.}]
(* messages *)
(* {a -> -0.532829} *)

-
thanks very much! I get it. for very b, I find the value of a that minimize the function. I express it as j[b_] := Quiet[FindRoot[N[D[pf[a, b], a] /. {a -> a}] == 0, {a, -0}]] – 3c. Jul 23 '13 at 15:05
@user8583, you could also have the b as a parameter. Something like: dpf = D[pf[a, b], a];j[x_, y_] := N[dpf /. {a -> x,b -> y}]; FindRoot[j[a, 1.1] == 0, {a, -1/2., -1., 1.}] should also work. – user21 Jul 23 '13 at 15:24
I find another problem, pf = ParametricNDSolveValue[{y''[x] == y[x] Cos[x + y[x]], y[0] == a, y'[0] == 1}, Integrate[y[s]^2, {s, 0., b}], {x, 0, b}, {a, b}]; Plot[pf[a, 1.1], {a, -1, 1}], if I define another function,g[a_,b_]:=c/.FindRoot[a+b==c,{c,0}], and put this g inside the original function, so the original function becomes y''[x] == g[a,b] y[x] Cos[x + y[x]]. But mathematica gives me an error message. Do you have any idea? thanks a lot – 3c. Jul 24 '13 at 14:29
@user8583, this is a new question which you should post. – user21 Jul 24 '13 at 15:16
ok, thanks anyway – 3c. Jul 24 '13 at 15:23