1
$\begingroup$

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?

$\endgroup$

2 Answers 2

4
$\begingroup$

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}]
   ];
$\endgroup$
2
  • 1
    $\begingroup$ Also, myfun = NDSolveValue[odes, y, {x, 0, time}] seems appropriate in this context (and skip sol altogether). $\endgroup$
    – Michael E2
    Commented Apr 21, 2015 at 2:14
  • $\begingroup$ @MichaelE2: Added edit - good point. $\endgroup$
    – ciao
    Commented Apr 21, 2015 at 2:17
4
$\begingroup$

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  *)
$\endgroup$
3
  • $\begingroup$ Nice - don't recall coming across that, +1 $\endgroup$
    – ciao
    Commented Apr 21, 2015 at 3:02
  • $\begingroup$ Thank you very much for excellent answer. $\endgroup$
    – Zihu Guo
    Commented Apr 21, 2015 at 6:19
  • $\begingroup$ @ZihuGuo You're welcome. $\endgroup$
    – Michael E2
    Commented Apr 21, 2015 at 10:36

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.