I've been using Mathematica for a while now, and there are multiple common tasks that I end up doing. I'd like to learn how to convert them into functions so that I can store them in some file and load them at startup.
Most of these common tasks involve taking a set of equations and doing something with them. Thing is, I don't want to fix the variables the equations are written in, and would like behavior similar to NDSolve
where one can specify the functions as well as which variable is which.
For example, take this task:
Pd = ParametricNDSolve[{v'[t] == (v[t] - v[t]^3/3 - ω[t])/0.2,
ω'[t] == (1 + v[t])/0.2,
ω[0] == b, v[0] == a}, {v[t], ω[t]},
{t, 0, 20}, {a, b}];
PVec[x_, y_] := {D[(v[t] /. Pd) [x, y], t] /. t -> 0,
D[(ω[t] /. Pd) [x, y], t] /. t -> 0};
VectorPlot[PVec[x, y], {x, -2, 1}, {y, -1.2, 0.5}]
Here, I'm parametrically solving the pair of equations
$$ \begin{align} v'(t)&=\frac{-\frac{1}{3} v(t)^3+v(t)-\omega (t)}{0.2}\\ \omega'(t)&=\frac{v(t)+1}{0.2} \end{align} $$
with the parameters being the initial state of $v$ and $\omega$. Now, I take the vector field of their derivatives at $t=0$, and vector plot it. Basically, I want to get a quick map of how the initial trajectories ($(v'(t),\omega'(t))$) change for different initial conditions without having to open EquationTrekker
and do things manually.
So now, I want to take this task and write it as a function akin to TrajectoryMap[{eqn1,eqn2},{{var1,varmin,varmax},{var2,varmin,varmax}},{{timevar,timepoint},tmin,tmax,tpoint}]
where this particular code would run as
TrajectoryMap[{v'[t] == (v[t] - v[t]^3/3 - ω[t])/0.2,
ω'[t] == (1 + v[t])/0.2}, {{v[t],-2,1}, {ω[t],-1.2,0.5}}, {{t,0},0,20}]
(or something similar)
Here, timepoint
is the value of t
for which the derivative of the interpolating function is calculated.
I can tell that this will probably need some combination of Hold
s and Evaluate
s, but I can't seem to get the right one.
How should I go about converting this code (or any arbitrary code of a similar type) into a custom function?
TrajectoryMap[...]
to do what is being done in the code block above, right? If so, where do you specify the ICs and the plot ranges? $\endgroup$ParametricNDSolve
parameters, they get substituted withx,y
later on. The vector plot is a plot of $(v'(t),\omega'(t))$ at various initial conditions. The plot ranges are specified in the{{v[t],-2,1}, {ω[t],-1.2,0.5}}
(i.e. the{{var1,varmin,varmax},{var2,varmin,varmax}}
) part. $\endgroup$t
other than 0–20? $\endgroup$t
-- in fact, none at all. I'll add that bit, though. $\endgroup$