1
$\begingroup$

Excuse the simplicity of the question, but I'm trying to plot two (quite) simple ODEs in Mathematica. I'd like them to be reasonably attractive plots, and to include a slider bar to modify the values of k1, k2 and k3. If anyone could help me that would be great! I'm new to Mathematica.

x2'[t] = k2 x2[t] - k1 x1[t]
x1'[t] = k3 x1[t]
$\endgroup$
  • $\begingroup$ your equations are not clear. Assumed second one is x1'[t]==k3 x1[t] $\endgroup$ – Nasser Dec 3 '17 at 23:54
  • $\begingroup$ Thanks for the feedback, this is fixed! $\endgroup$ – Ubermensch_010 Dec 4 '17 at 0:34
3
$\begingroup$

enter image description here

Manipulate[
 Module[{x1, x2, t, sol, eq1, eq2},
  eq1 = x2'[t] == k2 x2[t] - k1 x1[t];
  eq2 = x1'[t] == k3 x1[t];
  sol = First@
    DSolve[{eq1, eq2, x1[0] == x10, x2[0] == x20}, {x1[t], x2[t]}, t];
  Plot[{x1[t] /. sol, x2[t] /. sol}, {t, 0, tMax}, Frame -> True, 
   FrameLabel -> {{"solution", None}, {"time", "My nice plot"}}, 
   BaseStyle -> 12, GridLines -> Automatic, 
   GridLinesStyle -> LightGray, 
   PlotRange -> {Automatic, {0, Automatic}}, 
   PlotLegends -> {"x1(t) bad Wolfs", "x2(t) poor Sheep"}]
  ],

 {{k1, .1, "k1"}, .01, 1, .01, Appearance -> "Labeled", ImageSize -> Tiny},
 {{k2, .2, "k2"}, .01, 1, .01, Appearance -> "Labeled", ImageSize -> Tiny},
 {{k3, .3, "k3"}, .01, 1, .01, Appearance -> "Labeled", ImageSize -> Tiny},
 Delimiter,
 {{x10, 2, "x1(0)"}, 0, 10, .1, Appearance -> "Labeled", ImageSize -> Tiny},
 {{x20, 50, "x2(0)"}, 0, 100, .1, Appearance -> "Labeled", ImageSize -> Tiny},
 {{tMax,3,"time"},.1,50,.1, Appearance->"Labeled",ImageSize->Tiny},     
 Alignment -> Center, SynchronousUpdating -> True, 
 SynchronousInitialization -> True, FrameMargins -> 1, 
 ImageMargins -> 1, ControlPlacement -> Left
 ]
|improve this answer|||||
$\endgroup$
  • $\begingroup$ Thank you! This is for a population problem (x1 is wolf population x2 is sheep population), so is there any way to cap the lower bound of the y axis at zero? (doesn't make much sense to have a negative population) $\endgroup$ – Ubermensch_010 Dec 4 '17 at 0:28
  • $\begingroup$ @Ubermensch_010 yes, you can use PlotRange, updated., $\endgroup$ – Nasser Dec 4 '17 at 0:36
  • $\begingroup$ @Ubermensch_010 The - k1 x1[t] term in x2'[t] is problematic, because it can be negative even when x2==0. As a population biologist, I suggest you'd be better off using a nonlinear set of equations, the simplest of which is the Lotka-Volterra predator-prey model, to avoid negative population sizes. You'll have to switch from DSolve to NDSolve in this case. $\endgroup$ – Chris K Dec 4 '17 at 19:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.