Mathematica, nested optimization - wolfram-mathematica

I want to use the solution of Maximization, defined as a function, in another function. Here's an example:
f1[y_] := x /. Last[Maximize[{Sin[x y], Abs[x] <= y}, x]] (* or any other function *)
This definition is fine, for example if I give f1[4], I get answer -((3 \[Pi])/8).
The problem is that when I want to use it in another function I get error. For example:
FindRoot[f1[y] == Pi/4, {y, 1}]
Gives me the following error:
ReplaceAll::reps: {x} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>
FindRoot::nlnum: The function value {-0.785398+(x/.x)} is not a list of numbers with dimensions {1} at {y} = {1.}. >>
I've been struggling with this for several days now! Any comment, idea, help, ... is deeply appreciated! Thank you very much!

When y is not a number, your Maximize cannot be resolved, in which case the Last element of it is x, which is why you get that odd error message. You can resolve this by clearing the bad definition of f1 and making a new one that ensures only numeric arguments are evaluated:
ClearAll[f1]
f1[y_?NumericQ] := x /. Last[Maximize[{Sin[x y], Abs[x] <= y}, x]]
FindRoot[f1[y] == \[Pi]/4, {y, 1}]
(* {y -> 0.785398} *)

Related

How can I extract all monomials (without coefficients!) from a polynomial in mathematica?

Mathematica provides MonomialList[f] to get all monomials in f:
MonomialList[(x+y)^2]={x^2,2xy,y^2}
But what I need is {x^2,xy,y^2}, how can I make it?
Inner[#2^#1 &, First/#CoefficientRules[#1, #2], #2, Times] &[(x + y)^2, {x, y}]
(*
{x^2, x y, y^2}
*)

Evaluating derivatives of functions of three variables in Mathematica

I am trying to evaluate the derivative of a function at a point (3,5,1) in Mathematica. So, thats my input:
In[120]:= D[Sqrt[(z + x)/(y - 1)] - z^2, x]
Out[121]= 1/(2 (-1 + y) Sqrt[(x + z)/(-1 + y)])
In[122]:= f[x_, y_, z_] := %
In[123]:= x = 3
y = 5
z = 1
f[x, y, z]
Out[124]= (1/8)[3, 5, 1]
As you can see I am getting some weird output. Any hints on evaluating that derivative at (3,5,1) please?
The result you get for Out[124] leads me to believe that f was not cleared of a previous definition. In particular, it appears to have what is known as an OwnValue which is set by an expression of the form
f = 1/8
(Note the lack of a colon.) You can verify this by executing
g = 5;
OwnValues[g]
which returns
{HoldPattern[g] :> 5}
Unfortunately, OwnValues supersede any other definition, like a function definition (known as a DownValue or, its variant, an UpValue). So, defining
g[x_] := x^2
would cause g[5] to evaluate to 5[5]; clearly not what you want. So, Clear any symbols you intend to use as functions prior to their definition. That said, your definition of f will still run into problems.
At issue, is your use of SetDelayed (:=) when defining f. This prevents the right hand side of the assignment from taking on a value until f is executed later. For example,
D[x^2 + x y, x]
f[x_, y_] := %
x = 5
y = 6
f[x, y]
returns 6, instead. This occurs because 6 was last result generated, and f is effectively a synonym of %. There are two ways around this, either use Set (=)
Clear[f, x, y]
D[x^2 + x y, x];
f[x_, y_] = %
f[5, 6]
which returns 16, as expected, or ensure that % is replaced by its value before SetDelayed gets its hands on it,
Clear[f, x, y]
D[x^2 + x y, x];
f[x_, y_] := Evaluate[%]

Evaluate[] seems to not work inside Button[]

Any idea how to get this to work?
y = {}; Table[Button[x, AppendTo[y, Evaluate[x]]], {x, 5}]
Result: Click [1] , click [2], get {6,6}
I'm trivializing the actual task, but the goal is to set what a button does inside a Map or a Table or ParallelTable.
Please Help!
EDIT
Figured it out... Evaluate works at first level only. Here, it's too deep. So I used ReplaceRule:
Remove[sub]; y = {}; Table[Button[x, AppendTo[y, sub]] /. sub -> x, {x, 5}]
This is a job for With. With is used to insert an evaluated expression into another expression at any depth -- even into parts of the expression that are not evaluated right away like the second argument to Button:
y = {}; Table[With[{x = i}, Button[x, AppendTo[y, x]]], {i, 5}]
In simple cases like this, some people (myself included) prefer to use the same symbol (x in this case) for both the With and Table variables, thus:
y = {}; Table[With[{x = x}, Button[x, AppendTo[y, x]]], {x, 5}]
Replacement rules and pure functions offer concise alternatives to With. For example:
y={}; Range[5] /. x_Integer :> Button[x, AppendTo[y, x]]
or
y = {}; Replace[Range[5], x_ :> Button[x, AppendTo[y, x]], {1}]
or
y = {}; Array[Button[#, AppendTo[y, #]] &, {5}]
or
y = {}; Button[#, AppendTo[y, #]] & /# Range[5]
For another example comparing these techniques, see my post here, where they are applied to a problem of creating a list of pure functions with parameter embedded in their body (closures).
Evaluate works at first level only. Here, it's too deep. So I used ReplaceRule:
Remove[sub]; y = {}; Table[ Button[x, AppendTo[y, sub]] /. sub -> x, {x, 5}]

How to fix syntax to nest functions in mathematica?

I wanted to try to make a rule to do norm squared integrals. For example, instead of the following:
Integrate[ Conjugate[Exp[-\[Beta] Abs[x]]] Exp[-\[Beta] Abs[x]],
{x, -Infinity, Infinity}]
I tried creating a function to do so, but require the function to take a function:
Clear[complexNorm, g, x]
complexNorm[ g_[ x_ ] ] := Integrate[ Conjugate[g[x]] * g[x],
{x, -Infinity, Infinity}]
v = complexNorm[ Exp[ - \[Beta] Abs[x]]] // Trace
Mathematica doesn't have any trouble doing the first integral, but the final result of the trace when my helper function is used, shows just:
complexNorm[E^(-\[Beta] Abs[x])]
with no evaluation of the desired integral?
The syntax closely follows an example I found in http://www.mathprogramming-intro.org/download/MathProgrammingIntro.pdf [page 155], but it doesn't work for me.
The reason why your expression doesn't evaluate to what you expect is because complexNorm is expecting a pattern of the form f_[x_]. It returned what you put in because it couldn't pattern match what you gave it. If you still want to use your function, you can modify it to the following:
complexNorm[g_] := Integrate[ Conjugate[g] * g, {x, -Infinity, Infinity}]
Notice that you're just matching with anything now. Then, you just call it as complexNorm[expr]. This requires expr to have x in it somewhere though, or you'll get all kinds of funny business.
Also, can't you just use Abs[x]^2 for the norm squared? Abs[x] usually gives you a result of the form Sqrt[Conjugate[x] x].
That way you can just write:
complexNorm[g_] := Integrate[Abs[g]^2, {x, -Infinity, Infinity}]
Since you're doing quantum mechanics, you may find the following some nice syntatic sugar to use:
\[LeftAngleBracket] f_ \[RightAngleBracket] :=
Integrate[Abs[f]^2, {x, -\[Infinity], \[Infinity]}]
That way you can write your expectation values exactly as you would expect them.

Getting Indices from Mathematica's Select

How can I get the indices of a selection rather than the values. I.e.
list={3->4, 5->2, 1->1, 5->8, 3->2};
Select[list, #[[1]]==5&]; (* returns {5->2, 5->8} *)
I would like something like
SelectIndices[list, #[[1]]==5&]; (* returns {2, 4} *)
EDIT: I found an answer to the immediate question above (see below), but what about sorting. Say I want to sort a list but rather than returning the sorted list, I want to return the indices in the order of the sorted list?
Ok, well, I figured out a way to do this. Mathematica uses such a different vocabulary that searching the documentation still is generally unfruitful for me (I had been searching for things like, "Element index from Mathematica Select", to no avail.)
Anyway, this seems to be the way to do this:
Position[list, 5->_];
I guess its time to read up on patterns in Mathematica.
WRT to the question remaining after your edit: How about Ordering?
In[26]:= Ordering[{c, x, b, z, h}]
Out[26]= {3, 1, 5, 2, 4}
In[28]:= {c, x, b, z, h}[[Ordering[{c, x, b, z, h}]]]
Out[28]= {b, c, h, x, z}
In[27]:= Sort[{c, x, b, z, h}]
Out[27]= {b, c, h, x, z}
I think you want Ordering:
Sort[list, #[[1]] == 5 &]
Ordering[list, All, #[[1]] == 5 &]
(*
{5->2,5->8,3->2,1->1,3->4}
{2,4,5,3,1}
*)
Sorry, I had read your question to fast.
I think your second question is about how to sort the list according to the values of the rules. The simplest way that come to mind is by using a compare function. then simply use your solution to retrieve the indices:
comp[_ -> x_, a_ -> y_] := x < y;
Position[Sort[list, comp], 5 -> _]
Hope this helps!
Without sorting or otherwise altering the list, do this:
SelectIndex[list_, fn_] := Module[{x},
x = Reap[For[i = 1, i < Length[list], i++, If[fn[list[[i]]], Sow[i], Null];]];
If[x[[1]] == {}, {}, x[[2, 1]]]]
list={ {"foo",1}, {"bar",2}};
SelectIndex[list, StringMatchQ[ #[[1]], "foo*"] &]
You can use that to extract records from a database
Lookup[list_, query_, column_: 1, resultColumns_: All] := list[[SelectIndex[list, StringMatchQ[query, #[[column]]] &], resultColumns]]
Lookup(list,"foo")

Resources