Related
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.
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}
I have earlier asked how to make allTrue[{x,list},test] function that protects the placeholder symbol x from evaluation in current context in the same way as Table[expr,{x,...}] protects x
The recipe that I ended up using failed intermittently, and I found the problem down to be caused by automatic conversion of lists to PackedArrays. Here's a failing example
SetAttributes[allTrue, HoldAll];
allTrue[{var_, lis_}, expr_] :=
LengthWhile[lis,
TrueQ[ReleaseHold[Hold[expr] /. HoldPattern[var] -> #]] &] ==
Length[lis];
allTrue[{y, Developer`ToPackedArray[{1, 1, 1}]}, y > 0]
I want allTrue[{x,{1,2,3}},x>0] to return True regardless of whether {1,2,3} gets automatically converted into PackedArray, what is a better way to implement it?
This is a version I've been using for quite a while (wrote it for a second edition of my book originally, but I ended up using it a lot). If arguments represent some unevaluated code, then the test function must have HoldAll or HoldFirst attributes if we want a single piece of code representing one specific clause to be passed to it in its unevaluated form (which may or may not be desirable).
ClearAll[fastOr];
Attributes[fastOr] = {HoldRest};
fastOr[test_, {args___}] := fastOr[test, args];
fastOr[test_, args___] :=
TrueQ[Scan[
Function[arg, If[test[arg], Return[True]], HoldAll],
Hold[args]]];
Edit: I just noticed that the solution by Daniel Reeves at the bottom of the page linked in the question, is very similar to this one. The main difference is that I care about both short-circuiting and keeping arguments unevaluated (see below), while Daniel focuses on the short-circuiting part only.
It does have a short-circuiting behavior. We need HoldRest attribute since we want to preserve the arguments in their unevaluated form. We also need the HoldAll (or HoldFirst) attribute in a pure function to preserve each of the arguments unevaluated until it is passed to test. Whether or not it gets evaluated before it is used in the body of test depends now on the attributes of test. As an example:
Clear[fullSquareQ];
fullSquareQ[x_Integer] := IntegerQ[Sqrt[x]];
In[13]:= Or ## Map[fullSquareQ, Range[50000]] // Timing
Out[13]= {0.594, True}
In[14]:= fastOr[fullSquareQ, Evaluate[Range[10000]]] // Timing
Out[14]= {0., True}
Here is an example where we pass as arguments some pieces of code inducing side effects (printing). The code of the last argument has no chance to execute, since the result has already been determined at the previous clause:
In[15]:= fastOr[# &, Print["*"]; False, Print["**"]; False,
Print["***"]; True, Print["****"]; False]
During evaluation of In[15]:= *
During evaluation of In[15]:= **
During evaluation of In[15]:= ***
Out[15]= True
Note that, since fastOr accepts general pieces of unevaluated code as clauses for Or, you have to wrap your list of values in Evaluate if you don't care that they are going to be evaluated at the start ( as is the case with the Range example above).
Finally, I will illustrate the programmatic construction of held code for fastOr, to show how it can be used (consider it a tiny crash course on working with held expressions if you wish). The following function is very useful when working with held expressions:
joinHeld[a___Hold] := Hold ## Replace[Hold[a], Hold[x___] :> Sequence[x], {1}];
Example:
In[26]:= joinHeld[Hold[Print[1]], Hold[Print[2], Print[3]], Hold[], Hold[Print[4]]]
Out[26]= Hold[Print[1], Print[2], Print[3], Print[4]]
Here is how we use it to construct programmatically the held arguments that were used in the example with Print-s above:
In[27]:=
held = joinHeld ## MapThread[Hold[Print[#]; #2] &,
{NestList[# <> "*" &, "*", 3], {False, False, True, False}}]
Out[27]= Hold[Print["*"]; False, Print["**"]; False, Print["***"]; True, Print["****"]; False]
To pass it to fastOr, we will use another useful idiom: append (or prepend) to Hold[args] until we get all function arguments, and then use Apply (note that, in general, if we don't want the piece we are appending / prepending to evaluate, we must wrap it in Unevaluated, so the general idiom looks like Append[Hold[parts___],Unevaluated[newpart]]):
In[28]:= fastOr ## Prepend[held, # &]
During evaluation of In[28]:= *
During evaluation of In[28]:= **
During evaluation of In[28]:= ***
Out[28]= True
Regarding the original implementation you refer to, you can look at my comment to it I made some while ago. The problem is that TakeWhile and LengthWhile have bugs for packed arrays in v. 8.0.0, they are fixed in the sources of 8.0.1 - so, starting from 8.0.1, you can use either mine or Michael's version.
HTH
Edit:
I just noticed that in the post you referred to, you wanted a different syntax. While it would not be very difficult to adopt the approach taken in fastOr to this case, here is a different implementation, which arguably is in closer correspondence with the existing language constructs for this particular syntax. I suggest to use Table and exceptions, since iterators in Table accept the same syntax as you want. Here it is:
ClearAll[AnyTrue, AllTrue];
SetAttributes[{AnyTrue, AllTrue}, HoldAll];
Module[{exany, exall},
AnyTrue[iter : {var_Symbol, lis_List}, expr_] :=
TrueQ[Catch[Table[If[TrueQ[expr], Throw[True, exany]], iter], exany]];
AllTrue[iter : {var_Symbol, lis_List}, expr_] :=
Catch[Table[If[! TrueQ[expr], Throw[False, exall]], iter], exall] =!= False;
];
A few words of explanation: I use Module on the top level since the custom exception tags we need to define just once, can as well do that at definition-time. The way to break out of Table is through exceptions. Not very elegant and induces a small performance hit, but we buy automatic dynamic localization of your iterator variables done by Table, and simplicity. To do this in a safe way, we must tag an exception with a unique tag, so we don't catch some other exception by mistake. I find using Module for creating persistent exception tags to be a very useful trick in general. Now, some examples:
In[40]:= i = 1
Out[40]= 1
In[41]:= AnyTrue[{i, {1, 2, 3, 4, 5}}, i > 3]
Out[41]= True
In[42]:= AnyTrue[{i, {1, 2, 3, 4, 5}}, i > 6]
Out[42]= False
In[43]:= AllTrue[{i, {1, 2, 3, 4, 5}}, i > 3]
Out[43]= False
In[44]:= AllTrue[{i, {1, 2, 3, 4, 5}}, i < 6]
Out[44]= True
In[45]:= AllTrue[{a, {1, 3, 5}}, AnyTrue[{b, {2, 4, 5}}, EvenQ[a + b]]]
Out[45]= True
In[46]:= AnyTrue[{a, {1, 3, 5}}, AllTrue[{b, {2, 4, 5}}, EvenQ[a + b]]]
Out[46]= False
I started with an assignment to i to show that possible global values of iterator variables don't matter - this is taken care of by Table. Finally, note that (as I commented elsewhere), your original signatures for AllTrue and AnyTrue are a bit too restrictive, in the sense that the following does not work:
In[47]:= lst = Range[5];
AllTrue[{i, lst}, i > 3]
Out[48]= AllTrue[{i, lst}, i > 3]
(since the fact that lst represents a list is not known at the pattern-matching time, due to HoldAll attribute). There is no good reason to keep this behavior, so you can just remove the _List checks: AnyTrue[iter : {var_Symbol, lis_}, expr_] and similarly for AllTrue, and this class of use cases will be covered.
Hi I am using Mathematica 5.2. Suppose I have an array list like
In[2]:=lst=Tuples[{0,1},4]
Out[2]={{0,0,0,0},{0,0,0,1},{0,0,1,0},{0,0,1,1},
{0,1,0,0},{0,1,0,1},{0,1,1,0},{0,1,1,1},
{1,0,0,0},{1,0,0,1},{1,0,1,0},{1,0,1,1},
{1,1,0,0},{1,1,0,1},{1,1,1,0},{1,1,1,1}}
Now I want to get 16 arrays from the above array like st1={0,0,0,0}; st2={0,0,0,1}, st3={0,0,1,0}...
How can I get these array lists using a loop. Because if the no. of elements of the above array named lst become larger then it will not be a wise decision to take each of the element of the array lst separately and give their name separately. I tried this like the following way but it is not working...
Do[st[i]=lst[[i]],{i,1,16}]
Plz some body help me in this problem...
It does work, but what you create are the so-called indexed variables. You should access them also using the index, for example:
In[4]:= {st[1], st[2], st[3]}
Out[4]= {{0, 0, 0}, {0, 0, 1}, {0, 1, 0}}
I think what you are trying to do could be done by:
lst = Tuples[{0, 1}, 4];
Table[Evaluate[Symbol["lst" <> ToString[i]]] = lst[[i]], {i, Length#lst}]
So that
lst1 == {0,0,0,0}
But this is not a useful way to manage vars in Mathematica.
Edit
I'll try to show you why having vars lst1,lst2 .. is not useful, and is against the "Mathematica way".
Mathematica works better by applying functions to objects. For example, suppose you want to work with EuclideanDistance. You have a point {1,2,3,4} in R4, and you want to calculate the nearest point from your set to this point.
This is easily done by
eds = EuclideanDistance[{1, 2, 3, 4}, #] & /# Tuples[{0, 1}, 4]
And the nearest point distance is simply:
min = Min[eds]
If you want to know which point/s are the nearest ones, you can do:
Select[lst, EuclideanDistance[{1, 2, 3, 4}, #] == min &]
Now, try to do that same things with your intended lst1,lst2 .. asignments, and you will find it, although not impossible, very,very convoluted.
Edit
BTW, once you have
lst = Tuples[{0, 1}, 4];
You can access each element of the list just by typing
lst[[1]]
etc. In case you need to loop. But again, loops are NOT the Mathematica way. For example, if you want to get another list, with your elements normalized, don't loop and just do:
lstNorm = Norm /# lst
Which is cleaner and quicker than
Do[st[i] = Norm#lst[[i]], {i, 1, 16}]
You will find that defining downvalues (like st[i]) above) is useful when solving equations, but besides that many operations that in other languages are done using arrays, in Mathematica are better carried out by using lists.
Edit
Answering your comment actually I need each element of array lst to find the value of function such as f[x,y,z,k]=x-y+z+k. Such function may be
(#1 - #2 + #3 + #4) & ### lst
or
(#[[1]] - #[[2]] + #[[3]] + #[[4]]) & /# lst
Out:
{0, 1, 1, 2, -1, 0, 0, 1, 1, 2, 2, 3, 0, 1, 1, 2}
HTH!
You can do this:
Table[
Evaluate[
Symbol["st" <> ToString#i]] = lst[[i]],
{i, 1, Length#lst}];
at the end of which try Names["st*"] to see that you now have st1 to st16 defined. You could also do this with MapIndexed, like so:
MapIndexed[(Evaluate#Symbol["sts" <> ToString~Apply~#2] = #1) &, lst]
after which Names["sts*"] shows again that it has worked. Both of these can be done using a loop if this is what you (but I do not see what it buys you).
On the other hand, this way, when you want to access one of them, you need to do something like Symbol["sts" <> ToString[4]]. Using what you have already done or something equivalent, eg,
Table[
Evaluate[stg[i]] = lst[[i]],{i, 1, Length#lst}]
you end up with stg[1], stg[2] etc, and you can access them much more easily by eg Table[stg[i],{i,1,Length#lst}]
You can see what has been defined by ?stg or in more detail by DownValues[stg].
Or is it something else you want?
Leonid linked to a tutorial, which I suggest you read, by the way.
There are N ways of doing this, though like belisarius I have my doubts about your approach. Nonetheless, the easiest way I've found to manage things like this is to use what Mathematica calls "pure functions", like so:
In[1]:= lst = Tuples[{0,1}, 4];
In[2]:= With[{setter = (st[#1] = #2) &},
Do[setter[i, lst[[i]]], {i, Length#lst}]];
Doing it this way, the evaluation rules for special do just what you want. However, I'd approach this without a loop at all, just using a single definition:
In[3]:= ClearAll[st] (* Clearing the existing definitions is important! *)
In[4]:= st[i_Integer] := lst[[i]]
I think if you provide more detail about what you're trying to accomplish, we'll be able to provide more useful advice.
EDIT: Leonid Shifrin comments that if you change the definition of lst after the fact, the change will also affect st. You can avoid this by using With in the way he describes:
With[{rhs = lst},
st[i_Integer] := rhs[[i]]];
I don't know which will be more useful given what you're trying to do, but it's an important point either way.
Maybe something like this?
MapThread[Set, {Array[st, Length#lst], lst}];
For example:
{st[1], st[10], st[16]}
Out[14]= {{0, 0, 0, 0}, {1, 0, 0, 1}, {1, 1, 1, 1}}
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}]