Mathematica Use Returned Function - wolfram-mathematica

I'm sure this is very simple, but I ask Mathematica for the characteristic polynomial of an equation, as follows:
m={
{0, n, 0, c1},
{R, 0, 4, c2},
{0, R, 0, 0},
{0, 0, R, c4}
}
CharacteristicPolynomial[m,x]
Now, I would like to save the returned polynomial as a function, so I can later call it (presumably with something like f[1]). Alas, I've been unable to figure out how to do this.

This is fairly straightforward. Simply do this
f[x_] = CharacteristicPolynomial[m,x]
Note the use of Set (=) not SetDelayed (:=) which forces CharacteristicPolynomial to be evaluated once. If you used SetDelayed, then it would be evaluated every time f is evaluated.

Related

Can I specify the components of FourVector in FeynCalc?

I'm using FeynCalc to calculate Compton's scattering. I need to use specific values for the components of the photon polarization four-vector. How can I do that?
I am going to give a short answer here, for more details, see my answer on Mathematica StackExchange:
https://mathematica.stackexchange.com/questions/161767/can-i-specify-the-components-of-fourvector-in-feyncalc/204639#204639
So, one can define the two functions
Mink[t1_, t2_] :=
t1[[1]] t2[[1]] - t1[[2]] t2[[2]] - t1[[3]] t2[[3]] -
t1[[4]] t2[[4]];
LevContracted[a_, b_, c_, d_] :=
Sum[-LeviCivitaTensor[
4][[mu, nu, alpha, beta]]] a[[mu]] b[[nu]] c[[alpha]] d[[beta]], {mu, 1, 4}, {nu, 1, 4}, {alpha, 1,
4}, {beta, 1, 4}];
and define vectors as lists, e.g.
p = {x, y, z, w};
in order to calculate fully contracted amplitudes. Here, I am working with the signature (+---). The additional minus sign in the second function arises from the convention that ɛ​^{0123}=+1 and our vectors are taken to be contravariant.

Define control as variable in Mathematica

When I use Manipulate I can do:
Manipulate[x, {u, 1, 10}]
In reality my controls are many and complicated, so I would prefer to take their
definition out of the Manipulate expression, like that:
control = {u, 1, 10}
Manipulate[x, control]
But that does result in a an error:
Manipulate argument control does not have the correct form for a \
variable specification.
Why doesn't it work that way?
Manipulate has the HoldAll attribute. You can force control to evaluate and everything works ok
control = {u, 1, 10};
Manipulate[x[u], Evaluate[control]]
The problem with this is that the variable u is not properly localised, so if you have already set, e.g., u=1 somewhere, then the Manipulate will return an error.
It might be better if you use appropriate scoping constructs such as With or DynamicModule depending on exactly what you're trying to do.
This is maybe overkill, but it ensures that u is local and moves control outside of the manipulate:
DynamicModule[{u}, With[{control = {u, 1, 10}}, Manipulate[x[u], control]]]
This
con = {u, 1, 10};
Manipulate[
u,
Evaluate#con
]
does work. I suppose it doesn't work without the Evaluate because
Attributes[Manipulate]
shows that Manipulate has the attribute HoldAll (but I may be wrong). To see the effect of this attribute, try this:
SetAttributes[f, HoldAll]
f[con]
f[Evaluate#con]
g[con]
(*
f[con]
f[{u, 1, 10}]
g[{u, 1, 10}]
*)
Thus, it appears that due to the HoldAll atribute, Manipulate simply does not see "inside" con unless you explicitly evaluate it.

setdelayed inside manipulate originates a loop of evaluations. Why?

Why does this:
Manipulate[test[a_] := 2*b; test[c], {b, 0, 1}, {c, 0, 1}]
turns into an evaluation loop?
Shouldn't Manipulate only evaluate when b or c changes?
To fix the problem with minimal changes, do
Manipulate[
test[a_] := 2*b;
test[c], {b, 0, 1}, {c, 0, 1},
TrackedSymbols \[Rule] {b, c}]
instead (i.e., add TrackedSymbols to tell Mathematica what to track for changes).
Yes, the Manipulate will re-evaluate when b or c changes, but also if test changes -- and test is being re-assigned every time any one of those values changes. Hence the endless re-evaluation loop.
As a rule, side-effects should be avoided in the display expressions of constructs like Manipulate and Dynamic in order to avoid evaluation loops, race conditions and other surprising behaviour. In the case at hand, I would suggest removing the implicit dependency on b in test and hoisting its definition outside of the Manipulate:
test[b_, c_] := 2*b; Manipulate[test[b, c], {b, 0, 1}, {c, 0, 1}]
In the real application, there may be obstacles to such a simple refactoring -- but the key point is to remove the := from the dynamic expression.

Plot using With versus Plot using Block (Mathematica)

I want to describe an issue I have been having with Plot using With to keep defined parameters 'local'. I am not necessarily asking for a fix: the problem I have is one of understanding.
Sometimes I use a construction such as the following to obtain a Plot:
Method 1
plot1 = With[{vmax = 10, km = 10},
Plot[Evaluate#((vmax x)/(km + x)), {x, 0, 100},
AxesOrigin -> {0, 0}]]
I like this method, and it is reasonably clear even to non-Mathematica users exactly what is going on.
When the equations to be plotted become more complex, I like to define them external to the plot (using SetDelayed). For example:
f[x_] := (vmax x)/(km + x)
However, the following does not work
Method 2
plot2 = With[{vmax = 10, km = 10},
Plot[Evaluate#f[x], {x, 0, 100}, AxesOrigin -> {0, 0}]]
I have always naively thought that it should. However, based on the Help statement that
Plot treats the variable x as local,
effectively using Block
I have used various workarounds, mostly something like the following
Method 3
plot3 = Plot[With[{vmax = 10, km = 10}, Evaluate#f[x]], {x, 0, 100},
AxesOrigin -> {0, 0}]
This one seems very awkward, and usually requires further explanation even to Mathematica users.
Plot outputs
However, recently I found out by chance that substituting Block for With in Method 2 works exactly as expected.
I can, for example, do something like the following (which to me seems a very versatile approach):
plot4 = Block[{vmax = {10, 10, 10}, km = { 10, 100, 1000}},
Plot[Evaluate#f[x], {x, 0, 100}, AxesOrigin -> {0, 0},
PlotStyle -> {Red, Green, Blue}]]
giving
My questiions are as follows. What is the explanation for the difference in behaviour with With in Method 1 and 2? Should I have expected Method 2 not to work? Furthermore, what is the explanation for the difference in behaviour with Block and With in Method 2? Should I have been able to predict that Block would work?
Funnily enough many workarounds have been suggested to me by those more experienced than I, but nobody suggested using Block.
Finally, I need to keep vmax and km local.(They have been defined algebraically elsewhere)
Your question is not so much about Plot as it is about how the scoping constructs work. The main confusion here is due to the differences between lexical and dynamic scoping. And the main culprit is this definition:
f[x_] := (vmax x)/(km + x)
The problem with it is that it makes f implicitly depend on the global symbols (variables) vmax and km. I am very much against this sort of constructs since they lead to infinite confusion. Now, what happens can be illustrated with the following example:
In[55]:= With[{vmax =1, km = 2},f[x]]
Out[55]= (vmax x)/(km+x)
To understand why this happens, one must understand what the lexical scoping means. We know that With has a HoldAll attribute. The way it works is that it looks are what is literally inside it, and substitutes variables found literally in the body with their values from the declaration list. This happens during the variable-binding stage, and only then it lets the body to evaluate. From this, it is clear that the following will work:
In[56]:= With[{vmax =1, km = 2},Evaluate[f[x]]]
Out[56]= x/(2+x)
This worked because Evaluate overrides the "part" of HoldAll attribute of With, forcing the body to evaluate before anything else (variable binding, and subsequent body evaluation). Therefore, it would be completely equivalent to use just With[{vmax = 1, km = 2}, (vmax x)/(km + x)] above, as you can see with Trace. The next part of the puzzle is why
With[{vmax = 10, km = 10}, Plot[Evaluate#f[x], {x, 0, 100}, AxesOrigin -> {0, 0}]]
does not work. This is because this time we do not evaluate the body first. The presence of Evaluate affects only f[x] inside Plot, but not the evaluation of Plot itself inside With. This is illustrated by
In[59]:= With[{vmax = 10, km = 10}, q[Evaluate#f[x]]]
Out[59]= q[(vmax x)/(km + x)]
Moreover, we do not want Plot to evaluate first, since then the values of vmax and km will not be defined. However, all that With sees is f[x], and since the parameters vmax and km are not literally present in there (lexical scoping, remember), no substitution will be made. Should we use Block here, and things will work, because Block uses dynamic scoping, meaning that it redefines values in time (part of the execution stack if you wish), rather than in place. Therefore, using Block[{a =1, b =2}, ff[x]] where ff implicitly depends on a and b is (roughly) equivalent to a=1;b=2;ff[x] (with the difference that a and b resume their global values after the Block scope is left). So,
In[60]:= Block[{vmax = 10, km = 10}, q[Evaluate#f[x]]]
Out[60]= q[(10 x)/(10 + x)]
To make the With version work, you'd have to inject the expression for f[x] (r.h.s), for example like so:
In[63]:= Unevaluated[With[{vmax = 10, km = 10}, q[f[x]]]] /. DownValues[f]
Out[63]= q[(10 x)/(10 + x)]
Note that this won't work:
In[62]:= With[{fx = f[x]}, With[{vmax = 10, km = 10}, q[fx]]]
Out[62]= q[(vmax x)/(km + x)]
But the reason here is quite subtle: while outer With evaluates before the inner one, it spots the variable name conflicts and renames its variables. Rules are much more disruptive, they don't respect inner scoping constructs.
EDIT
If one insists on nested With-s, here is how one can fool the name conflict resolution mechanism of With and make it work:
In[69]:= With[{fx = f[x]}, With ## Hold[{vmax = 10, km = 10}, q[fx]]]
Out[69]= q[(10 x)/(10 + x)]
Since outer With can no longer detect the presence of inner With (using Apply[With,Hold[...]] makes the inner With effectively dynamically generated), it does not make any renamings, and then it works. This is a general trick to fool lexical scoping name resolution mechanism when you don't want renaming, although the necessity to use it usually indicates a bad design.
END EDIT
But I digressed. To summarize, making your second method work is quite hard and requires really weird constructs like
Unevaluated[ With[{vmax = 10, km = 10}, Plot[Evaluate#f[x], {x, 0, 100},
AxesOrigin -> {0, 0}]]] /. DownValues[f]
or
With[{fx = f[x]},
With ## Hold[{vmax = 10, km = 10},
Plot[Evaluate#fx, {x, 0, 100}, AxesOrigin -> {0, 0}]]]
Once again: all this is because With must "see" the variables explicitly in the code, to make replacements. In contrast, Block does not need that, it replaces values dynamically at the moment of evaluation, based on their modified global values, as if you made assignments, this is why it works.
Now, the real culprit is your definition of f. You could have avoided all these troubles should you have defined your f with explicit parameter-passing:
ff[x_, vmax_, km_] := (vmax x)/(km + x)
Now, this works out of the box:
With[{vmax = 10, km = 10},
Plot[Evaluate#ff[x, vmax, km], {x, 0, 100}, AxesOrigin -> {0, 0}]]
because the parameters are explicitly present in the function call signature, and so are visible to With.
To summarize: what you observed is a consequence of the interplay between lexical and dynamic scoping. Lexical scoping constructs must "see" their variables explicitly in the code at the variable-binding stage (before evaluation), or they won't be effective. Dynamic scoping effectively modifies values of symbols, and is in this sense less demanding (the price you pay is that the code using lots of dynamic scoping is harder to understand, since it mixes state and behavior). The main reason for trouble is the function definition that makes implicit dependencies on global symbols (that are not in the formal parameter list of the function). It is best to avoid such constructs. It is still possible to make things work, but this is considerably more complicated (as was demonstrated above), and, at least for the case at hand, for no good reason.
Just two comments:
using Block, you don't need to use Evaluate. That is, Block[{vmax = 10, km = 2}, Plot[f[x], {x, 0, 100}] will work.
Another way to do this is to define substitution rules:
rule = {vmax -> 10, km -> 10}; Plot[f[x] /. rule, {x, 0, 100}]
The advantage is that you can re-use the rule in other statements.
In addition, you can define multiple substition rules for different cases: rule1 = {vmax -> 10, km -> 10}, rule2 = {vmax -> 2, km -> 2}

Using the solution of a differential equation in two separate plot commands in Mathematica

I've encountered a problem while trying to use the answer from a NDSolve in two separate plot commands. To illustrate the problem, I'll use a simple differential equation and only one plot command. If I write something like this:
{Plot[x[t], {t, 0, 10}], x[4]}
/. NDSolve[{x'[s] == - x[s], x[0] == 1}, x, {s, 0, 10}]
It solves the equation and calculates x[4] with no problem, but the plot turns empty, and I have no idea why.
In my actual problem, my equation is a quite complicated system for several functions, and instead of x[4] I draw a parametric plot of the solved functions. I ultimately intend to include all this in a Manipulate statement so I don't want the NDSolve statement to appear more than once (takes too long) and I can't just calculate it in advance (since it has a lot of parameters).
Edit: I would like to clarify and expand my question: What I actually want to do is to include my plotting statement in a Manipulate statement in the following way:
Manipulate[{Plot[x[t], {t, 0, 10}], x[4]}
/. NDSolve[{x'[s] == - a*x[s], x[0] == 1}, x, {s, 0, 10}]
,{{a,1},0,5}]
Since only the Manipulate statement gives value to the parameter a, I can't calculate the answer to the NDSolve beforehand. Also, since my actual equation system is very complicated and non-linear, I can't use the symbolic function DSolve.
Sorry if it wasn't clear before.
Your problem is that Plot[] does some funny things to make plotting more convenient, and one of the things it does is just not plot things it can't evaluate numerically. So in the expression you posted,
Plot[x[t], {t, 0, 10}]
just goes ahead and evaluates before doing the rule substitution with the solution from NDSolve, producing a graphics object of an empty plot. That graphics object contains no reference to x, so there's nothing to substitute for.
You want to make sure the substitution is done before the plotting. If you also want to make sure the substitution can be done in multiple places, you want to store the solution into a variable.
sol = NDSolve[{x'[s] == - x[s], x[0] == 1}, x, {s, 0, 10}];
{Plot[Evaluate[x[t] /. sol], {t, 0, 10}], x[4] /. sol}
The Evaluate[] in the Plot makes sure that Mathematica only does the substitution once, instead of once for each plot point. It's not important for a simple rule substitution like this, but it's a good habit to use it in case you ever want to plot something more complicated.
In order to make this work in a Manipulate, the simple way is to use With[], which is one of Mathematica's scoping constructs; it's the one to use where you just want to substitute something in without using it as variable you can mutate.
For example,
Manipulate[
With[{sol = NDSolve[{x'[s] == - x[s], x[0] == 1}, x, {s, 0, 10}]},
{Plot[x[t] /. sol // Evaluate, {t, 0, 10}, PlotRange -> {0, 1}],
x[4] /. sol}],
{{a, 1}, {0, 5}}]
Use the PlotRange option to keep the y-axis fixed; otherwise things will jump around in an ugly way as the value of a changes. When you do more complex things with Manipulate, there are a number of options for controlling the speed of updates, which can be important if your ODE is complicated enough that it takes a while to solve.
Meanwhile, I found another way to do this. It's less elegant, but it only uses one substitution so I've thought I'll post it here also.
The idea is to use Hold on the Plot so it wouldn't get evaluated, do the rule substitution and then ReleaseHold, just before the Manipulate.
Manipulate[ReleaseHold[
Hold[ {Plot[x[t], {t, 0, 10}, PlotRange -> {0, 1}], x[4]} ]
/.NDSolve[{x'[s] == -a x[s], x[0] == 1}, x, {s, 0, 10}]
], {{a, 1}, 0, 5}]

Resources