Right now I have code where some function func executes the way I want it to when I give it specific arguments in its definition (so I make it func[x1_,x2_]:=... and then later I make it func[x1_,x2_,x3_]:=... without changing anything else and it works the way I would like it to). Is there a way to automatically substitute whatever arguments I specify for this function?
UPDATE:
I haven't isolated the problem code yet, but this code here does not do what I want:
(* Clear all stuff each time before running, just to be safe! *)
\
Clear["Global`*"]
data = {{238.2, 0.049}, {246.8, 0.055}, {255.8, 0.059}, {267.5,
0.063}, {280.5, 0.063}, {294.3, 0.066}, {307.7, 0.069}, {318.2,
0.069}};
errors = {{x1, 0.004}, {x2, 0.005}};
getX[x1_, x2_] := 1/x2^2
getY[x__] =
Evaluate[Simplify[
Sqrt[Sum[(D[getX[x], errors[[i]][[1]]] errors[[i]][[2]])^2, {i,
Length[errors]}]]]]
map[action_, list_] := action ### list
y = map[getY, data];
y
getY[2, 3]
This code here does: (gives {67.9989, 48.0841, 38.9524, 31.994, 31.994, 27.8265, 24.3525, 24.3525} for y)
(* Clear all stuff each time before running, just to be safe! *) \ Clear["Global`*"]
data = {{238.2, 0.049}, {246.8,
0.055}, {255.8, 0.059}, {267.5,
0.063}, {280.5, 0.063}, {294.3, 0.066}, {307.7, 0.069}, {318.2,
0.069}}; errors = {{x2, 0.004}, {x1, 0.005}};
getX[x1_, x2_] := 1/x2^2
getY[x1_, x2_] := Evaluate[Simplify[ Sqrt[Sum[(D[getX[x1, x2], errors[[i]][[1]]]
errors[[i]][[2]])^2, {i, Length[errors]}]]]]
map[action_, list_] := action ### list
y = map[getY, data]; y
getY[2, 3]
UPDATE 2:
My math:
I intend to take the square root of the sum of the squares of all the partial derivatives of the getX function. Thus the body of the getY function. Then I want to evaluate that expression for different values of x1 and x2. Thus I have the arguments for getY.
Use __, e.g.
In[4]:= f[x__] = {x}
Out[4]= {x}
In[5]:= f[1,2,3,4,5,6]
Out[5]= {1, 2, 3, 4, 5, 6}
In[6]:= f[a,b,c]
Out[6]= {a, b, c}
Well the issue is that in the first version, with explicit number of arguments, you have used Evaluate to evaluate the right hand side. You can not do this when the number of arguments is variable, because evaluator does not know which signature of getX to use.
So the solution is to replace getY with the following:
getY[x__] := (Simplify[
Sqrt[(D[getX ##
errors[[1 ;; Length[{x}], 1]], {errors[[All, 1]]}].
errors[[All, 2]])^2]]) /.
Thread[errors[[1 ;; Length[{x}], 1]] -> {x}]
This would first use variables from errors list exactly as many as you have supplied in the arguments of getY, compute the derivative symbolically, and then perform the Dot, instead of Sum which is faster. Then the outputs will be the same.
Notice that in your two versions of the code, errors have different values.
Alternatively, you can use Derivative like so:
getY2[x__] :=
Abs[(Derivative[##][getX][x] & ###
IdentityMatrix[Length[{x}]].errors[[All, 2]])]
Using it gives the same result.
Related
I want to evaluate f below by passing a list to some function:
f = {z[1] z[2], z[2]^2};
a = % /. {z[1]-> #1,z[2]-> #2};
F[Z_] := Evaluate[a] & ## Z ;
So now if I try F[{1,2}] I get {2, 4} as expected. But looking closer ?F returns the definition
F[Z_] := (Evaluate[a] &) ## Z
which depends on the value of a, so if we set a=3 and then evaluate F[{1,2}], we get 3. I know that adding the last & makes the Evaluate[a] hold, but what is an elegant work around? Essentially I need to force the evaluation of Evaluate[a], mainly to improve efficiency, as a is in fact quite complicated.
Can someone please help out, and take into consideration that f has to contain an Array[z,2] given by some unknown calculation. So writing
F[Z_] := {Z[[1]]Z[[2]],Z[[2]]^2}
would not be enough, I need this to be generated automatically from our f.
Many thanks for any contribution.
Please consider asking your future questions at the dedicated StackExchange site for Mathematica.
Your questions will be much less likely to become tumbleweeds and may be viewed by many experts.
You can inject the value of a into the body of both Function and SetDelayed using With:
With[{body = a},
F[Z_] := body & ## Z
]
Check the definition:
Definition[F]
F[Z$_] := ({#1 #2, #2^2} &) ## Z$
You'll notice Z has become Z$ due to automatic renaming within nested scoping constructs but the behavior is the same.
In the comments you said:
And again it bothers me that if the values of z[i] were changed, then this workaround would fail.
While this should not be a problem after F[Z_] is defined as above, if you wish to protect the replacement done for a you could use Formal Symbols instead of z. These are entered with e.g. Esc$zEsc for Formal z. Formal Symbols have the attribute Protected and exist specifically to avoid such conflicts as this.
This looks much better in a Notebook than it does here:
f = {\[FormalZ][1] \[FormalZ][2], \[FormalZ][2]^2};
a = f /. {\[FormalZ][1] -> #1, \[FormalZ][2] -> #2};
Another approach is to do the replacements inside a Hold expression, and protect the rules themselves from evaluation by using Unevaluated:
ClearAll[f, z, a, F, Z]
z[2] = "Fail!";
f = Hold[{z[1] z[2], z[2]^2}];
a = f /. Unevaluated[{z[1] -> #1, z[2] -> #2}] // ReleaseHold;
With[{body = a},
F[Z_] := body & ## Z
]
Definition[F]
F[Z$_] := ({#1 #2, #2^2} &) ## Z$
How is it possible to use a mathematical function as module- parameter
Such as:
PersonalPlot[fun0_, var0_, min0_, max0_] :=
Module[{fun = fun0, var = var0 , min = min0, max = max0},
(*this is incorrect*)
fun = fun[var_];
Plot[fun, {var, min, max}]
]
PersonalPlot[x^2,x,0,3];
You're right, that statement is incorrect. Mathematica evaluates it to something like
x^2[x]
when you call PersonalPlot and that evaluates to, well, in words to x to the power of 2 of x which doesn't make a lot of sense. There are a number of ways round the problem. The simplest would be to dispense with a Module altogether and define:
PersonalPlot1[fun0_, var0_, min0_, max0_] := Plot[fun0, {var0, min0, max0}]
which you would call like this:
PersonalPlot1[x^2, x, 0, 3]
Note that a call like this PersonalPlot1[x^2, y, 0, 3] produces an empty plot because the variable in the function passed in is not the same variable as the second argument. Read on.
If you want to define a module which takes a function as an argument, then this is one way of doing it:
PersonalPlot2[fun0_, var0_, min0_, max0_] :=
Module[{fun = fun0, var = var0, min = min0, max = max0},
Plot[fun[var], {var, min, max}]]
which you would call like this
PersonalPlot2[#^2 &, x, 0, 3]
Note:
The function passed into the function is a pure function. If you are not already familiar with Mathematica's pure functions now would be a good time to consult the relevant parts of the documentation.
This explicitly tells the Plot command to evaluate fun[var] over the range you specify.
Your local variables are not strictly necessary since your function works by side-effect, producing a plot rather than manipulating (copies of) the arguments passed to it. You could rewrite this simply as:
PersonalPlot2b[fun0_, var0_, min0_, max0_] := Module[{},
Plot[fun0[var0], {var0, min0, max0}]]
Another possibility would be to drop the argument which represents the variable input to the function passed to PersonalPlot, like this:
PersonalPlot3[fun0_, min0_, max0_] := Module[{x},
Plot[fun0[x], {x, min0, max0}]]
which you would call like this
PersonalPlot3[#^2 &, 0, 3]
In this version I've made x local to the Module to avoid clashes with any workspace variable also called x. This avoids errors arising from using different names for the argument to the function (the pure function has no argument names) and the second argument to PersonalPlot; that has now been dropped.
There are probably several other useful ways of passing arguments to functions whether those functions use modules or not.
EDIT
Most of us who've used Mathematica for a while don't, I think, regard #^2& as something to avoid. If you don't like it, you could use the more explicit syntax, like this:
fun1 = Function[x,x^2]
which you can then pass around like this
PersonalPlot[fun1,0.0,4.0]
By using this approach you can make your functions a bit less error prone by requiring the right types to be passed in, like this
PersonalPlot[fun_Function, min_Real, max_Real] := ...
but it's really up to you.
Off the top of my head I don't know how Plot does it, I'd have to look in the documentation.
The following three examples may add to previous answer in illustrating some of the possible ways to pass functions as arguments.
Example 1:
square[x_] := x^2/50;
fplot1[f_, x1_, x2_] := Plot[f, {x, x1, x2}];
fplot1[x^2/50, -2 Pi, 2 Pi]
fplot1[{square[x], Sin[x]}, -2 Pi, 2 Pi]
Example 2:
fplot2[f_, x1_, x2_] :=
Module [ (*
This type of function passing works also works in Module so long as x is not defined as a local variable. *)
{},
Plot[f, {x, x1, x2}]
];
fplot2[Sin[x], -2 Pi, 2 Pi]
fplot2[{Sin[x], square[x]}, -2 Pi, 2 Pi]
Example 3:
fplot3[f_, x1_, x2_] :=
Module [ (* This type of function passing works in Module with x declared as local variable. Only one function name can be passed. *)
{x},
Plot[f[x], {x, x1, x2}]
];
fplot3[Sin, -2 Pi, 2 Pi]
fplot3[square, -2 Pi, 2 Pi]
I aim to calculate and preserve the results from the maximization of a function with two arguments and one exogenous parameter, when the maximum can not be derived (in closed form) by maximize. For instance, let
f[x_,y_,a_]=Max[0,Min[a-y,1-x-y]
be the objective function where a is positive. The maximization shall take place over [0,1]^2, therefore I set
m[a_]=Maximize[{f[x, y, a], 0 <= x <= 1 && 0 <= y <= 1 && 0 <= a}, {x,y}]
Obviously m can be evaluated at any point a and it is therefore possible to plot the maximizing x by employing
Plot[x /. m[a][[2]], {a, 0.01, 1}]
As I need to do several plots and further derivations containing the optimal solutions x and y (which of course are functions of a), i would like to preserve/save the results from the optimization for further use. Is there an elegant way to do this, or do I have to write some kind of loop to extract the values myself?
Now that I've seen the full text of your comment on my original comment, I suspect that you do understand the differences between Set and SetDelayed well enough. I think what you may be looking for is memoisation, sometimes implemented a bit like this;
f[x_,y_] := f[x,y] = Max[0,Min[a-y,1-x-y]]
When you evaluate, for example f[3,4] for the first time it will evaluate to the entire expression to the right of the :=. The rhs is the assignment f[3,4] = Max[0,Min[a-y,1-x-y]]. Next time you evaluate f[3,4] Mathematica already has a value for it so doesn't need to recompute it, it just recalls it. In this example the stored value would be Max[0,Min[a-4,-6]] of course.
I remain a little uncertain of what you are trying to do so this answer may not be any use to you at all.
Simple approach
results = Table[{x, y, a} /. m[a][[2]], {a, 0.01, 1, .01}]
ListPlot[{#[[3]], #[[1]]} & /# results, Joined -> True]
(The Set = is ok here so long as 'a' is not previosly defined )
If you want to utilise Plot[]s automatic evaluation take a look at Reap[]/Sow[]
{p, data} = Reap[Plot[x /. Sow[m[a]][[2]], {a, 0.01, 1}]];
Show[p]
(this takes a few minutes as the function output is a mess..).
hmm try this again: assuming you want x,y,a and the minimum value:
{p, data} = Reap[Plot[x /. Sow[{a, m[a]}][[2, 2]], {a, 0.01, .1}]];
Show[p]
results = {#[[1]], x /. #[[2, 2]], y /. #[[2, 2]], #[[2, 1]]} & /# data[[1]]
BTW Your function appears to be independent of x over some ranges which is why the plot is a mess..
As it is problematic to google strings which contain $ (dollar sign) I couldn't find any explanation to the following output:
{Cos[tmp$132923 + \[Phi]],
Sin[tmp$132926 + \[Phi]],
\[Phi]
}
The question:
What does tmp$xxxx means?
Some background
In `book2.nb' I defined the following function:
g[i_, j_] := {
f1[i, t, f2[b, j], p][[1]],
f1[i, t, f2[b, j], p][[2]],
f3[i, t, p]
}
Where f1,f2,f3 are all defined in another notebook book1.nb, which was initialized and working fine. Furthermore, f1 returns a list and b is a list defined and active.
Now, when I invoke g[1,1] I get an output similar to the one cited above - with this tmp$. Nevertheless, if I try to plot g it works perfectly (using ParametricPlot3D[g[1, 1], {t, 0, 1}, {p, 0, 2 Pi}]). However, if I try to define a variable
V= {
f1[1, t, f2[b, 1], p][[1]],
f1[1, t, f2[b, 1], p][[2]],
f3[1, t, p]
}
where I replace i,j with fixed values. Then V is once again with a tmp$ element, but this time it DOESN'T plot...
You are most likely seeing localized symbols that result through scoping such as Module.
Here is one example. Since the localized symbol x is used to define the global symbol y the temporary symbol x$152 escapes Module.
In[1]:= Module[{x}, y = x]; y
Out[2]= x$152
There are other variations of this process. Suppose you set a unique context for the cell (Evaluation > Notebook's Default Context > Unique to Each Cell Group) and then make an assignment to an explicitly Global symbol:
Global`b = a
Now in another notebook:
In[1]:= b
Out[1]= Notebook$$33`a
Your code probably has a variation of this problem:
f[x_] := Module[{t}, Cos[t]+Cos[x] ]
at which point evaluating this:
f[y]
gives this:
Cos[t$685] + Cos[y]
Often, this means there is a problem with the code.
Either 't' was meant to be passed in as a parameter of 'f':
f[x_,t_] := Module[{}, Cos[t]+Cos[x] ]
or 't' needed to be initialized in some fashion:
f[x_] := Module[{t}, t=2x; Cos[t]+Cos[x] ]
It's perfectly ok to use these unique variables in your code, if you intend to do so. For example, this is one way to write an expression with with many unique variables:
Plus ## Table[Unique[x]^i, {i, 100}]
What is the simplest way to map an arbitrarily funky nested list expr to a function unflatten so that expr==unflatten##Flatten#expr?
Motivation:
Compile can only handle full arrays (something I just learned -- but not from the error message), so the idea is to use unflatten together with a compiled version of the flattened expression:
fPrivate=Compile[{x,y},Evaluate#Flatten#expr];
f[x_?NumericQ,y_?NumericQ]:=unflatten##fPrivate[x,y]
Example of a solution to a less general problem:
What I actually need to do is to calculate all the derivatives for a given multivariate function up to some order. For this case, I hack my way along like so:
expr=Table[D[x^2 y+y^3,{{x,y},k}],{k,0,2}];
unflatten=Module[{f,x,y,a,b,sslot,tt},
tt=Table[D[f[x,y],{{x,y},k}],{k,0,2}] /.
{Derivative[a_,b_][_][__]-> x[a,b], f[__]-> x[0,0]};
(Evaluate[tt/.MapIndexed[#1->sslot[#2[[1]]]&,
Flatten[tt]]/. sslot-> Slot]&) ]
Out[1]= {x^2 y + y^3, {2 x y, x^2 + 3 y^2}, {{2 y, 2 x}, {2 x, 6 y}}}
Out[2]= {#1, {#2, #3}, {{#4, #5}, {#5, #7}}} &
This works, but it is neither elegant nor general.
Edit: Here is the "job security" version of the solution provided by aaz:
makeUnflatten[expr_List]:=Module[{i=1},
Function#Evaluate#ReplaceAll[
If[ListQ[#1],Map[#0,#1],i++]&#expr,
i_Integer-> Slot[i]]]
It works a charm:
In[2]= makeUnflatten[expr]
Out[2]= {#1,{#2,#3},{{#4,#5},{#6,#7}}}&
You obviously need to save some information about list structure, because Flatten[{a,{b,c}}]==Flatten[{{a,b},c}].
If ArrayQ[expr], then the list structure is given by Dimensions[expr] and you can reconstruct it with Partition. E.g.
expr = {{a, b, c}, {d, e, f}};
dimensions = Dimensions[expr]
{2,3}
unflatten = Fold[Partition, #1, Reverse[Drop[dimensions, 1]]]&;
expr == unflatten # Flatten[expr]
(The Partition man page actually has a similar example called unflatten.)
If expr is not an array, you can try this:
expr = {a, {b, c}};
indexes = Module[{i=0}, If[ListQ[#1], Map[#0, #1], ++i]& #expr]
{1, {2, 3}}
slots = indexes /. {i_Integer -> Slot[i]}
{#1, {#2, #3}}
unflatten = Function[Release[slots]]
{#1, {#2, #3}} &
expr == unflatten ## Flatten[expr]
I am not sure what you are trying to do with Compile. It is used when you want to evaluate procedural or functional expressions very quickly on numerical values, so I don't think it is going to help here. If repeated calculations of D[f,...] are impeding your performance, you can precompute and store them with something like
Table[d[k]=D[f,{{x,y},k}],{k,0,kk}];
Then just call d[k] to get the kth derivative.
I just wanted to update the excellent solutions by aaz and Janus. It seems that, at least in Mathematica 9.0.1.0 on Mac OSX, the assignment (see aaz's solution)
{i_Integer -> Slot[i]}
fails. If, however, we use
{i_Integer :> Slot[i]}
instead, we succeed. The same holds, of course, for the ReplaceAll call in Janus's "job security" version.
For good measure, I include my own function.
unflatten[ex_List, exOriginal_List] :=
Module[
{indexes, slots, unflat},
indexes =
Module[
{i = 0},
If[ListQ[#1], Map[#0, #1], ++i] &#exOriginal
];
slots = indexes /. {i_Integer :> Slot[i]};
unflat = Function[Release[slots]];
unflat ## ex
];
(* example *)
expr = {a, {b, c}};
expr // Flatten // unflatten[#, expr] &
It might seem a little like a cheat to use the original expression in the function, but as aaz points out, we need some information from the original expression. While you don't need it all, in order to have a single function that can unflatten, all is necessary.
My application is similar to Janus's: I am parallelizing calls to Simplify for a tensor. Using ParallelTable I can significantly improve performance, but I wreck the tensor structure in the process. This gives me a quick way to reconstruct my original tensor, simplified.