# How can I create function which contains an ODE system and its numeric solution?

I have created a function like the following, which contains an ODE system. And I want to know the effect of different parameters.

    myodessystem[k1_, k2_, time_] := Module[{odes, y, x, sol, myfun},
odes = {y'[x] == k1 y[x] Cos[k2 x + y[x]], y[0] == 1};
sol = NDSolve[odes, y, {x, 0, time}];
myfun = y[x] /. sol
]


But I can not get the solutions I want:

mysolve = myodessystem[1, 1, 30]

(* {InterpolatingFunction[{{0., 30.}}, <>][x$12879]} *)  And it does not work when I assign a value to the result function:  mysolve[10] (* {InterpolatingFunction[{{0., 30.}}, <>][x$12879]}[10] *)


How can I get the solution of the ODE and get the result value when I assign a value to it?

Note change at end of your function... you might also want to add checks to ensure that there was a solution so as not to return a nonsense function.

myodessystem[k1_, k2_, time_] :=
Module[{odes, y, x, sol, myfun},
odes = {y'[x] == k1 y[x] Cos[k2 x + y[x]], y[0] == 1};
sol = NDSolve[odes, y, {x, 0, time}];
myfun = First[y /. sol]];

mysolve = myodessystem[1, 1, 30];

mysolve[1]

(* 0.991387 *)


Per Michael's cogent comment, this can be condensed to:

myodessystem[k1_, k2_, time_] :=
Module[{odes, y, x, sol, myfun},
odes = {y'[x] == k1 y[x] Cos[k2 x + y[x]], y[0] == 1};
NDSolveValue[odes, y, {x, 0, time}]
];

• Also, myfun = NDSolveValue[odes, y, {x, 0, time}] seems appropriate in this context (and skip sol altogether). – Michael E2 Apr 21 '15 at 2:14
• @MichaelE2: Added edit - good point. – ciao Apr 21 '15 at 2:17

What the OP is trying to code is already in Mathematica in the form of ParametricNDSolveValue.

myodessystem = ParametricNDSolveValue[{y'[x] == k1 y[x] Cos[k2 x + y[x]], y[0] == 1},
y, {x, 0, time}, {k1, k2, time}]
(*  ParametricFunction[<>]  *)

mysolve = myodessystem[1, 1, 30];
mysolve[1]
(*  0.991387  *)

• Nice - don't recall coming across that, +1 – ciao Apr 21 '15 at 3:02
• Thank you very much for excellent answer. – Zihu Guo Apr 21 '15 at 6:19
• @ZihuGuo You're welcome. – Michael E2 Apr 21 '15 at 10:36