The function trajectory
below is defined in terms of Manipulate
and calls the auxiliary function soln
:
soln[f_, y0_][t_] :=
y[t] /. First@DSolve[{y'[t] == f[t], y[0] == y0}, y[t], t]
trajectory[f_] := Manipulate[
{f[t], Plot[Evaluate[soln[f, y0][t]], {t, 0, 5}, PlotRange -> 5]},
{{y0, 0}, -2, 2, 0.25}]
Consider the following two calls to trajectory
in the same notebook:
(* example 1 *)
f[t_] := 1 - t^2
trajectory[f]
(* example 2 *)
f[t_] := 2 t - 3
trajectory[f]
After evaluating the two lines in example 1, if I then evaluate the two lines in example 2, immediately the previously displayed output in example 1 changes so as to use the output from example 2.
How can this unwanted interaction be prevented? I would strongly prefer:
not to use different names for the function
f
in the two examples (usingg[t_] := 1 - t^2; trajectory[g]
andh[t_] := 2 t - 3; trajectory[h]
does prevent the unwanted interaction; andnot to use a pure function directly as the argument to
trajectory
(usingtrajectory[(1 - #^2) &]
andtrajectory[(2 # - 3) &]
does prevent the unwanted interaction).
In short, is there some way of doing scoping to prevent what I'm seeing?
Relation to similar question Localizing variables within a Manipulate
I had seen that related question and the answer provided, namely, to use the setting Evaluation->Notebook's Default Context-> Unique to Each Cell Group. However, that is unsatisfactory here because (i) it would require putting a copy of the code for soon
and trajectory
into a separate group with each example invocation of trajectory
; and (ii) even in that case, the code may well be copied by a user into a different notebook where it may be awkward to use the indicated evaluation option.
f
changed and updated. You do not need to even make a new manipulate call to see the interaction. Just definingf
again in the global context will cause the Manipulate to change. $\endgroup$Manipulate
: the idea is to create a functiontrajectory
that can be used with *any" vector field function the user might wish. $\endgroup$