Plotting NDSolve inside Manipulate

wolfram-mathematica

Solution

Yes, just make them arguments of function `ODEN`. A few more points to improve the code:

1) Make code self-reliable by using `Initialization` to introduce functions

3) Use `ControlType -> None` to introduce a dummy localized variable to avoid additional `Module` inside `manipulate` - because `Manipulate` wraps `DynamicModule` anyway around its content.

Manipulate[

 sol = NDSolve[Join[ODEN[10, k1, k2], ODENInit[10, 0]], 
   ODENVars[10], {t, 0, 10}];

 Plot[Evaluate@Table[x[i][t] /. sol, {i, 1, 10}], {t, 0, 10}],

 {{k1, 1}, 0.1, 10, .1},
 {{k2, 1}, 0.1, 10, .1},
 {sol, ControlType -> None},

 Initialization :> {

   ODENInit[n_, xIni_] := 
    Join[{x[1][0] == xIni}, Table[x[i][0] == 0, {i, 2, n}]],

   ODEN[n_, k1_, k2_] := 
    Join[{x[1]'[t] == k1 - k2 x[1][t]}, 
     Table[x[i]'[t] == k1 x[i - 1][t] - k2 x[i][t], {i, 2, n}]],

   ODENVars[n_] := Table[x[i][t], {i, 1, n}]

   }]

To answer your comment, if you a really prone to keeping `k` globally defined outside the function, then this will do:

Manipulate[

 Block[{sol, k1 = mk1, k2 = mk2},
  sol = NDSolve[Join[ODEN[10], ODENInit[10, 0]], 
    ODENVars[10], {t, 0, 10}];
  Plot[Evaluate@Table[x[i][t] /. sol, {i, 1, 10}], {t, 0, 10}]],

 {{mk1, 1}, 0.1, 10, .1}, {{mk2, 1}, 0.1, 10, .1}]

Problem

I have the following working Mathematica code: ``` ODENInit[n_, xIni_] := Join[{x[1][0] == xIni}, Table[x[i][0] == 0, {i, 2, n}]] ODEN[n_] := Join[{x[1]'[t] == k1 - k2 x[1][t]}, Table[x[i]'[t] == k1 x[i - 1][t] - k2 x[i][t], {i, 2, n}]] ODENVars[n_] := Table[x[i][t], {i, 1, n}]; Manipulate[ Module[{sol}, sol = NDSolve[ Join[ODEN[10], ODENInit[10, 0]] /. {k1 -> mk1, k2 -> mk2}, ODENVars[10], {t, 0, 10}]; Plot[Evaluate@Table[x[i][t] /. sol, {i, 1, 10}], {t, 0, 10}]], {{mk1, 1}, 0.1, 10, .1}, {{mk2, 1}, 0.1, 10, .1}] ``` Is there any way of rewriting the Manipulate part such that I wouldn't need to reassign k1 and k2 parameters to dummy ones, here mk1 and mk2? Thanks for any hints in advance.

Original source