Building NDSolve inside Manipulate

I have the following Mathematica working 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 a way to rewrite part of the Manipulation, so I would not need to reassign the parameters k1 and k2 to dummy ones, here are mk1 and mk2? Thanks for any tips in advance.

+4
source share
1 answer

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

1) Make the code self-reliant using Initialization to introduce functions

3) Use ControlType -> None to introduce a dummy localized variable to avoid the extra Module inside manipulate - because manipulate wraps the DynamicModule anyway around its contents.

 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}] }] 

enter image description here

To answer your comment, if you are really inclined to keep 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}] 
+5
source

All Articles