Passing parameters stored in a list to expression - wolfram-mathematica

How can I pass values to a given expression with several variables? The values for these variables are placed in a list that needs to be passed into the expression.

Your revised question is straightforward, simply
f ## {a,b,c,...} == f[a,b,c,...]
where ## is shorthand for Apply. Internally, {a,b,c} is List[a,b,c] (which you can see by using FullForm on any expression), and Apply just replaces the Head, List, with a new Head, f, changing the function. The operation of Apply is not limited to lists, in general
f ## g[a,b] == f[a,b]
Also, look at Sequence which does
f[Sequence[a,b]] == f[a,b]
So, we could do this instead
f[ Sequence ## {a,b}] == f[a,b]
which while pedantic seeming can be very useful.
Edit: Apply has an optional 2nd argument that specifies a level, i.e.
Apply[f, {{a,b},{c,d}}, {1}] == {f[a,b], f[c,d]}
Note: the shorthand for Apply[fcn, expr,{1}] is ###, as discussed here, but to specify any other level description you need to use the full function form.

A couple other ways...
Use rule replacement
f /. Thread[{a,b} -> l]
(where Thread[{a,b} -> l] will evaluate into {a->1, b->2})
Use a pure function
Function[{a,b}, Evaluate[f]] ## l
(where ## is a form of Apply[] and Evaluate[f] is used to turn the function into Function[{a,b}, a^2+b^2])

For example, for two elements
f[l_List]:=l[[1]]^2+l[[2]]^2
for any number of elements
g[l_List] := l.l
or
h[l_List]:= Norm[l]^2
So:
Print[{f[{a, b}], g[{a, b}], h[{a, b}]}]
{a^2 + b^2, a^2 + b^2, Abs[a]^2 + Abs[b]^2}
Two more, just for fun:
i[l_List] := Total#Table[j^2, {j, l}]
j[l_List] := SquaredEuclideanDistance[l, ConstantArray[0, Length[l]]
Edit
Regarding your definition
f[{__}] = a ^ 2 + b ^ 2;
It has a few problems:
1) You are defining a constant, because the a,b are not parameters.
2) You are defining a function with Set, Instead of SetDelayed, so the evaluation is done immediately. Just try for example
s[l_List] = Total[l]
vs. the right way:
s[l_List] := Total[l]
which remains unevaluated until you use it.
3) You are using a pattern without a name {__} so you can't use it in the right side of the expression. The right way could be:
f[{a_,b_}]:= a^2+b^2;

Related

Evaluation functions and expressions in Boolean expressions

I am aware how we can evaluate an expression after converting into Polish Notations. However I would like to know how I can evaluate something like this:
If a < b Then a + b Else a - b
a + b happens in case condition a < b is True, otherwise, if False a - b is computed.
The grammar is not an issue here. Since I only need the algorithm to solve this problem. I am able evaluate boolean and algebraic expressions. But how can I go about solving the above problem?
Do you need to assign a+b or a-b to something?
You can do this:
int c = a < b ? a+b : a-b;
Or
int sign = a < b ? 1 : -1;
int c = a + (sign * b);
Refer to LISP language for S-express:
e.g
(if (> a b) ; if-part
(+ a b) ; then-part
(- a b)) ; else-part
Actually if you want evaluate just this simple if statement, toknize it and evaluate it, but if you want to evaluate somehow more complicated things, like nested if then else, if with experssions, multiple else, variable assignments, types, ... you need to use some parser, like LR parsers. You can use e.g Lex&Yacc to write a good parser for your own language. They support somehow complicated grammars. But if you want to know how does LR parser (or so) works, you should read into them, and see how they use their table to read tokens and parse them. e.g take a look at wiki page and see how does LR parser table works (it's something more than simple stack and is not easy to describe it here).
If your problem is just really parsing if statement, you can cheat from parser techniques, you can add empty thing after a < b, which means some action, and empty thing after else, which also means an action. When you parsed the condition, depending on correctness or wrongness you will run one of actions. By the way if you want to parse expressions inside if statement you need conditional stack, means something like SLR table.
Basically, you need to build in support for a ternary operator. IE, where currently you pop an operator, and then wait for 2 sequential values before resolving it, you need to wait for 3 if your current operation is IF, and 2 for the other operations.
To handle the if statement, you can consider the if statement in terms of C++'s ternary operator. Which formats you want your grammar to support is up to you.
a < b ? a + b : a - b
You should be able to evaluate boolean operators on your stack the way you currently evaluate arithmetic operations, so a < b should be pushed as
< a b
The if can be represented by its own symbol on the stack, we can stick with '?'.
? < a b
and the 2 possible conditions to evaluate need to separated by another operator, might as well use ':'
? < a b : + a b - a b
So now when you pop '?', you see it is the operator that needs 3 values, so put it aside as you normally would, and continue to evaluate the stack until you have 3 values. The ':' operator should be a binary operator, that simply pushes both of its values back onto the stack.
Once you have 3 values on the stack, you evaluate ? as:
If the first value is 1, push the 2nd value, throw away the third.
If the first value is 0, throw away the 2nd and push the 3rd.

Using Evaluate with a Pure Function and SetDelayed

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 do I find the maximum positive value in an array in Mathematica?

I have an array of expressions, each depends on a.
I want to find the minimal positive value, as it depends on a, without having to substitute for a.
For example, if the array is [a^2, 1-2a, 1], then the function, call it MinPositive would return:
(MinPositive[a^2, 1-2a, 1]) /. a-> 0
0
(MinPositive[a^2, 1-2a, 1]) /. a-> 0.7
0.7^2
and so on.
Any ideas?
I would appreciate help to write the MinPositive function so that it can be used, for example, instead of the regular Min function.
Thanks.
Did you have something like this in mind? Return the expression that retsults in the min value..
minp[lst_, a_, v_] := (
pos = Select[lst, ((# /. a -> v) > 0) &];
Last#Sort[pos , ( (#1 /. a -> v ) > (#2 /. a -> v )) &])
minp[{a^2, 1 - 2 a, 1}, a, .2] -> a^2
minp[{a^2, 1 - 2 a, 1}, a, .48] -> 1-2 a
minp[{a^2, 1 - 2 a, 1}, a, 2] -> 1
The expression
[a^2, 1-2a, 1]
is not a well-formed Mathematica expression, perhaps you mean
{a^2, 1-2a, 1}
which is a valid expression for a list of 3 elements. Mathematica doesn't really do arrays as such, though lists can generally be used to model arrays.
On the other hand the expression
MinPositive[a^2, 1-2a, 1]
is a valid call to a function called MinPositive with 3 arguments.
All that to one side, I think you might be looking for a function call such as
MinPositive[{a^2, 1-2a, 1}/.a->0]
in which the value of 0 will be substituted for a inside the call to MinPositive but will not be applied outside that call.
It's not clear from your question whether you want help to write the MinPositive function; if you do, edit your question and make it clear. Further, your question title asks for the maximum positive value, while the body of your question refers to minima. You might want to sort that out too.
EDIT
I don't have Mathematica on this machine so I haven't checked this, but it should be close enough for you to finish off:
minPositive[lst_List] := Min[Select[lst,#>0&]]
which you would then call like this
minPositive[{a^2, 1-2a, 1}]
(NB: I avoid creating functions with a name with an initial capital letter.)
Or, considering your comment, perhaps you want something like
minPositive[lst_List, rl_Rule] := Min[Select[lst/.rl,#>0&]]
which you would call like this:
minPositive[{a^2, 1-2a, 1},a->2]
EDIT 2
The trouble, for you, with an expression such as
(MinPositive[a^2, 1-2a, 1]) /. a-> 0
is that the normal evaluation loop in Mathematica will cause the evaluation of the MinPositive function before the replacement rule is applied. How then can Mathematica figure out the minimum positive value in the list when a is set to a particular value ?
To prevent evaluation of the arguments before calling the body of the function is achieved by setting the attributes of the function to HoldAll (prevents evaluations of all arguments), HoldFirst (prevents the evaluation of the first argument only) or HoldRest (prevents the evaluation of all but the first argument).
In addition, since "a" by itself is not an argument, you need to use Block to isolate it from (potential) definitions for "a"
so
SetAttributes[minPositive, HoldAll]
minPositive[lst_List] := Block[{a},Min[Select[lst /. a -> 0, # > 0 &]]]
and even if you explicitly set a to some other value, say
a=3
than
minPositive[{a^2, 1 - 2 a, 100}]
returns 9 as expected
HTH
yehuda

Noncommutative Multiplication and Negative coeffcients at the Beginning of an Expression in Mathematica

With the help of some very gracious stackoverflow contributors in this post, I have the following new definition for NonCommutativeMultiply (**) in Mathematica:
Unprotect[NonCommutativeMultiply];
ClearAll[NonCommutativeMultiply]
NonCommutativeMultiply[] := 1
NonCommutativeMultiply[___, 0, ___] := 0
NonCommutativeMultiply[a___, 1, b___] := a ** b
NonCommutativeMultiply[a___, i_Integer, b___] := i*a ** b
NonCommutativeMultiply[a_] := a
c___ ** Subscript[a_, i_] ** Subscript[b_, j_] ** d___ /; i > j :=
c ** Subscript[b, j] ** Subscript[a, i] ** d
SetAttributes[NonCommutativeMultiply, {OneIdentity, Flat}]
Protect[NonCommutativeMultiply];
This multiplication is great, however, it does not deal with negative values at the beginning of an expression, i.e.,
a**b**c + (-q)**c**a
should simplify to
a**b**c - q**c**a
and it will not.
In my multiplication, the variable q (and any integer scaler) is commutative; I am still trying to write a SetCommutative function, without success. I am not in desperate need of SetCommutative, it would just be nice.
It would also be helpful if I were able to pull all of the q's to the beginning of each expression, i.e.,:
a**b**c + a**b**q**c**a
should simplify to:
a**b**c + q**a**b**c**a
and similarly, combining these two issues:
a**b**c + a**c**(-q)**b
should simplify to:
a**b**c - q**a**c**b
At the current time, I would like to figure out how to deal with these negative variables at the beginning of an expression and how to pull the q's and (-q)'s to the front as above. I have tried to deal with the two issues mentioned here using ReplaceRepeated (\\.), but so far I have had no success.
All ideas are welcome, thanks...
The key to doing this is to realize that Mathematica represents a-b as a+((-1)*b), as you can see from
In[1]= FullForm[a-b]
Out[2]= Plus[a,Times[-1,b]]
For the first part of your question, all you have to do is add this rule:
NonCommutativeMultiply[Times[-1, a_], b__] := - a ** b
or you can even catch the sign from any position:
NonCommutativeMultiply[a___, Times[-1, b_], c___] := - a ** b ** c
Update -- part 2. The general problem with getting scalars to front is that the pattern _Integer in your current rule will only spot things that are manifestly integers. It wont even spot that q is an integer in a construction like Assuming[{Element[q, Integers]}, a**q**b].
To achieve this, you need to examine assumptions, a process that is probably to expensive to be put in the global transformation table. Instead I would write a transformation function that I could apply manually (and maybe remove the current rule form the global table). Something like this might work:
NCMScalarReduce[e_] := e //. {
NonCommutativeMultiply[a___, i_ /; Simplify#Element[i, Reals],b___]
:> i a ** b
}
The rule used above uses Simplify to explicitly query assumptions, which you can set globally by assigning to $Assumptions or locally by using Assuming:
Assuming[{q \[Element] Reals},
NCMScalarReduce[c ** (-q) ** c]]
returns -q c**c.
HTH
Just a quick answer that repeats some of the comments from the previous question.
You can remove a couple of the definitions and solve all of the parts of this question using the rule that acts on Times[i,c] where i is commutative and c has the default of Sequence[]
Unprotect[NonCommutativeMultiply];
ClearAll[NonCommutativeMultiply]
NonCommutativeMultiply[] := 1
NonCommutativeMultiply[a___, (i:(_Integer|q))(c_:Sequence[]), b___] := i a**Switch[c, 1, Unevaluated[Sequence[]], _, c]**b
NonCommutativeMultiply[a_] := a
c___**Subscript[a_, i_]**Subscript[b_, j_] ** d___ /; i > j := c**Subscript[b, j]**Subscript[a, i]**d
SetAttributes[NonCommutativeMultiply, {OneIdentity, Flat}]
Protect[NonCommutativeMultiply];
This then works as expected
In[]:= a**b**q**(-c)**3**(2 a)**q
Out[]= -6 q^2 a**b**c**a
Note that you can generalize (_Integer|q) to work on more general commutative objects.

Targeted Simplify in Mathematica

I generate very long and complex analytic expressions of the general form:
(...something not so complex...)(...ditto...)(...ditto...)...lots...
When I try to use Simplify, Mathematica grinds to a halt, I am assuming due to the fact that it tries to expand the brackets and or simplify across different brackets. The brackets, while containing long expressions, are easily simplified by Mathematica on their own. Is there some way I can limit the scope of Simplify to a single bracket at a time?
Edit: Some additional info and progress.
So using the advice from you guys I have now started using something in the vein of
In[1]:= trouble = Log[(x + I y) (x - I y) + Sqrt[(a + I b) (a - I b)]];
In[2]:= Replace[trouble, form_ /; (Head[form] == Times) :> Simplify[form],{3}]
Out[2]= Log[Sqrt[a^2 + b^2] + (x - I y) (x + I y)]
Changing Times to an appropriate head like Plus or Power makes it possible to target the simplification quite accurately. The problem / question that remains, though, is the following: Simplify will still descend deeper than the level specified to Replace, e.g.
In[3]:= Replace[trouble, form_ /; (Head[form] == Plus) :> Simplify[form], {1}]
Out[3]= Log[Sqrt[a^2 + b^2] + x^2 + y^2]
simplifies the square root as well.
My plan was to iteratively use Replace from the bottom up one level at a time, but this clearly will result in vast amount of repeated work by Simplify and ultimately result in the exact same bogging down of Mathematica I experienced in the outset. Is there a way to restrict Simplify to a certain level(s)?
I realize that this sort of restriction may not produce optimal results, but the idea here is getting something that is "good enough".
There are a number of ways you can do this, but it can be a little tricky and depends on the structure of your actual expression. However, usually a product of a number of terms in brackets will have the head Times, and you can use FullForm to verify this:
In[1]:= FullForm[(a+b)(c+d)]
Out[1]= Times[Plus[a, b], Plus[c, d]]
You can use the higher-order function Map with expressions with head Times the same way you use it with expressions with head List, and that may allow you to Simplify the expression one term at a time, like so:
Map[Simplify, yourGinormousExpression]
You can use Expand on the result if you need to subsequently expand out the brackets.
EDIT to add: If you want to specify the forms that you do want to simplify, you can use Replace or ReplaceAll instead of one of the relatives of Map. Replace is particularly useful because it takes a level specification, allowing you to only affect the factors in the topmost product. As a simple example, consider the following:
In[1]:= expr = Sqrt[(a + 1)/a] Sqrt[(b + 1)/b];
In[2]:= Simplify[expr]
Out[2]= Sqrt[1 + 1/a] Sqrt[1 + 1/b]
If you don't want to simplify factors that depend on a. you can do this instead:
In[3]:= Replace[expr, form_ /; FreeQ[form, a] :> Simplify[form], {1}]
Out[3]= Sqrt[(1 + a)/a] Sqrt[1 + 1/b]
Only the second term, which depends on b, has been changed. One thing to bear in mind though is that some transformations are done automatically by Times or Plus; for instance a + a will be turned into 2 a even without use of Simplify.
I beg to differ with my colleagues, in that using Map to apply Simplify to each subexpression may not save any time as it will still be applied to each one. Instead try, MapAt, as follows:
In[1]:= MapAt[f, SomeHead[a,b,c,d], {4}]
Out[1]:= SomeHead[a, b, c, f[d]]
The tricky part is determining the position specification. Although, if the expression you want to simplify is at the first level, it shouldn't be any more difficult then what I've written above.
Now if you would still like to simplify everything, but you wish to preserve some structure, try using the option ExcludedForms. In the past, I've used to prevent this simplification:
In[2]:= Simplify[d Exp[I (a + b)] Cos[c/2]]
Out[2]:= Exp[I(a + b + c)](d + d Exp[c])
which Mathematica seems to like, so I do
In[3]:= Simplify[d Exp[I (a + b)] Cos[c/2], ExcludedForms -> {_Cos,_Sin}]
Out[3]:= d Exp[I (a + b)] Cos[c/2]
Also, don't forget that the second parameter for Simplify is for assumptions, and can greatly ease your struggles in getting your expressions into a useful form.
You should try Map.
In general, Map[foo, G[a, b, c, ...]] gives G[foo[a], foo[b], foo[c], ...] for any head G and any expression foo, so for
Map[Simplify, a b c d e]
it gives
Simplify[a] Simplify[b] Simplify[c] Simplify[d] Simplify[e]
Note you can denote Map[foo, expr] als foo /# expr if you find that more convenient.

Resources