Simple - Plotting a function - wolfram-mathematica

Why does this not plot?
Clear[x, b]
b = 2
f[x_] := b^x
Plot[f[x], {x, 1, 5}]
The Plot simply generates and empty graph.

This plots just fine for me in Mathematica 8.
Something to note though, you don't really want to do := in the function declaration here.
:= Postpones mathematica evaluating the function until it is actually called, and then it evaluates with the arguments given.
Basically, the rule I use is if I don't have a reason to use :=, I don't use it.
Good luck.
Edit
I just noticed you didn't clear f, that could be your problem.

Try this:
ClearAll[f, b];
b = 2;
f[x_] := b^x
Plot[f[x], {x, 1, 5}]

Related

Mathematica, nested optimization

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} *)

Using NIntegrate inside NDSolve

I am trying to numerically solve a partial differential equation, where the inhomogeneous term is an integral of another function. Something like this:
NDSolve[{D[f[x, y], x] == NIntegrate[h[x,y+y2],{y2, x, y}],f[0,y] == 0}, f, {x, 0, 1}, {y,0,1}]
where h[x,y] is a well known function previously defined.
But it seems that Mathematica does not know how to evaluate the integral.
I do not use Mathematica too often, so I am sure there is a simple solution to this.
Could someone tell me what I am doing wrong?
Thanks.
It is not really clear from the question, but I had a similar problem and the solution in my case was to follow the advice from the wolfram forums to put the integral in an extra function and force real input.
So in your case this would be
integral[x_Real,y_Real] := NIntegrate[h[x,y+y2],{y2, x, y}];
NDSolve[{D[f[x, y], x] == integral[x,y], f[0,y] == 0}, f, {x, 0, 1}, {y,0,1}]

function iteration in mathematica

I'm a beginner in Mathematica programming. My code is not running as expected. I wonder if anyone could examine what goes wrong? Here is part of the code.
F[{k_, n_, x_}] =
Which[k == 0, f[a, b, x],
k == 1, g[a, b, n, x],
k == 2, h[c, d, n, x]]
G[x_] = F[{0, 0, x}]
While[Extract[G[x], 1] != 3, G[x_] = F[G[x]]]
The functions f, g and h are defined by Which as is F, and they are all vector-valued so that it makes sense to iterate F. What I want to achieve is: given initial value {0,0,x}, keep iterating F until the first component of F becomes 3. Is there anything, e.g. syntax, wrong in the above code?
Thanks!
You need to use SetDelayed (:=) for function definitions like: F[x_]:=x. When you use Set (=) like F[x_]=x, the it is essentially the same as F[_]=x since the definition isn't delayed until evaluation, so there is no way to transfer the matched pattern on the left hand side into the evaluation of the right hand side.
As jVincent mentioned, I would use := instead of = while defining F.
I would also use the built in NestWhile instead of manually iterating.
NestWhile[F, {0, 0, x}, Function[e, Extract[e, 1] != 3]]
I can't quite comment on how to correct the code as written because I'm not entirely sure how reassigning G in the While works.

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