Prof. R. S. Sorbello
Dept of Physics, UWM
Last update: Nov. 5, 2010
LIST OF MATHEMATICA COMMANDS AND EXAMPLES

INDEX OF TOPICS
Aliases, Animations, Assumptions, Caution on integrals, Clear, Complex variables, Conditionals, Derivatives, Displaying output, Do Loop, Errors and error messages, Evaluating expressions, Exporting/Importing data and graphics, Field plots, Functions, Graphics, Graphics incompatibility, Help, Integrals, Keyboard shortcuts, Limits, Lists, Lists and arrays, Matrices, Modules, Page-breaks, Plots, Plot options, Printout, Programming, Series expansions, Simplify, Solving equations, Special constants, Sums, Tables, TeX, Vector analysis, Wolfram databases

About this document

FUNCTIONS
Examples of built-in Mathematica functions: Sin[x], Cos[x], Tan[x], Exp[x], Log[x], Sinh[x], Cosh[x], Tanh[x], ArcSin[x], ArcCos[x], ArcTan[x], Abs[x], Sign[x], Sqrt[x], LegendreP[n, x], BesselJ[n, x], BesselY[n, x], SphericalHarmonicY[l, m, theta, phi].

Defining a function:
To define a function F[x] use the so-called "set-delayed" symbol  ":=",   as for example,  F[x_]:= Tan[x]/x.   This construction creates functions that act just as Mathematica's built-in functions, i.e., you can call F[x] repeatedly with different numerical or symbolic values of x, and F[x] is evaluated afresh each time. Note the required underscore after the argument x on the left-hand side of the definition (but not on the right hand side). Multi-variable functions are defined in a similar way, as for example, F[x_, y_, z_]:= x*Sin[y]/z.

Defining an expression vs. defining a function:
It is often more convenient to work with an expression that depends on a variable rather than with a function that explicitly depends on that variable. For example, instead of defining the function F[x] by entering F[x_]:= Tan[x]/x, you can define an expression f by entering f=Tan[x]/x, which defines f to be Tan[x]/x provided that x has not been previously assigned a value. As a precaution against the latter possibility, clear the value of x by entering the Clear[x] command before entering f=Tan[x]/x. This can be written in a single command-line as   Clear[x];f=Tan[x]/x   (A semicolon separator allows a string of commands to be entered in a single input line.)   The reason to clear the symbol x is that if x has a value, say x=2, when the definition f=Tan[x]/x is entered, the undesired effect is that f is set equal to Tan[2]/2, and f keeps that value in all subsequent commands (unless f is redefined or cleared). This follows the general rule that whenever the equal-sign is used in a Mathematica command, the quantity on the left-hand side of the equal sign is set to the immediate value of the expression on the right-hand of the equal sign.

If a properly defined expression f has been evaluated for different values of the variable x, one can always retrieve the original expression by entering the Clear[x] command. For example, starting with the definition of f by entering Clear[x];f=Tan[x]/x, entering x=3;f  returns Tan[3]/3, and subsequently entering  x=4;f  returns Tan[4]/4, and if this is followed by  Clear[x];f  the result is the original expression Tan[x]/x. To get these results from the function F[x] defined by F[x_]:= Tan[x]/x, simply enter F[3], then F[4], and then F[x].

The preferred way to evaluate an expression f for a specific value of x, say x=b, is with the substitution command  f/.x->b .   This returns the value that f would have if x were replaced by b in the current expression for f, but no changes are actually made in the current expression for f or in the current value of x. On the other hand, if one evaluates f using the command   x=b;f, the immediate effect is that x takes the value b and and x is replaced by b in the expression for f. The potential danger here is that one might not remember that these changes are in effect when executing subsequent commands. Note, however, one can undo these changes by entering Clear[x] as the next command after x=b;f.

Comment on ":=" and "=" constructions for functions and expressions:
We have described the ":=" construction for functions and the "=" construction for expressions, but one can also use the "=" construction for functions and the ":=" construction for expressions. For example, one can enter  Clear[x];G[x_]= Tan[x]/x, in which case the function G[x] is immediately set to the expression on the right-hand side of the equal sign. If a parameter is present in the function, as for example, G[x_]= k*Tan[x]/x, the parameter k on the right hand side is set to its value at the time of the definition and retains that value in all subsequent evaluations of G[x]. If different values of k are to be used in later calculations, one should be sure that no specific value of k is in effect at the time the definition G[x_]= k*Tan[x]/x was entered. As a precaution, enter the Clear[x, k] command immediately before entering the definition of G[x].   (This precaution is not needed for the ":=" construction G[x_]:= k*Tan[x]/x because in that case G[x] is not evaluated until the function is needed.) If you use the ":=" construction for an expression, as for example, g:=k*Tan[x]/x, the values of k and x at the time of the definition are irrelevant; when g is subsequently calculated, only the values of k and x in effect at that time will be used.

Caution on evaluating or plotting functions containing derivatives or integrals:
The usual commands for evaluating and plotting functions may require the use of the Evaluate command to force an immediate evaluation when a derivative or integral is present. For example, if you have defined F[x_]:= D[Sin[x], x], and the value of this derivative at x=2 is desired, do not enter F[2], as this will cause Mathematica to try to evaluate D[Sin[2], 2] and return an error message "2 is not a valid variable". Instead, enter   x=2;Evaluate[F[x]]   or enter  F[x]/.x->2. Also, in Plot and Table commands, use Evaluate[F[x]] in place of F[x], as for example, Plot[Evaluate[F[x]], {x, 0, 10}] and Table[Evaluate[F[x]], {x, 0, 10, 0.1}]. The same syntax is required if the function contains an integral, as for example, F[x_]:=Integrate[Sin[x], x].

Note that if you use the equal-sign "=" construction to define expressions or functions, there is no need to use the Evaluate command to force an immediate evaluation because "=" forces Mathematica to make an immediate evaluation. For example, if you define f= D[Sin[x], x], Mathematica immediately evaluates the derivative and sets f equal to Cos[x], so there is no need to use the Evaluate command. Similarly, if you use the "=" construction to define F[x_]=D[Sin[x], x], Mathematica sets F[x] equal to Cos[x].

Piecewise functions:
These can be created by the commands "Piecewise" or "Which" (for description of "Which" see section on Conditionals).   For example:
   F[x_]:= Piecewise[{{f1, x < x1}, {f2, x2≥x ≥x1}, {f3, x > x2}}]
   F[x_]:= Which[x < x1, f1,   x2≥x ≥x1, f2,   x > x2, f3]
both define a function equal to f1, f2, or f3, for x<x1, x2≥x ≥x1, or x>x2, respectively, where f1, f2, and f3 may depend on x and other symbolic variables.

SPECIAL CONSTANTS
Pi, E, I, Infinity.
Note: Mathematica protects these names; they cannot be used as names for other quantities. In Mathematica notebooks, these can be entered in their stylized forms from the keyboard by using the escape-key constructions esc-p-esc, esc-ee-esc, esc-ii-esc, and esc-inf-esc, respectively.

DERIVATIVES
Let f be an expression containing x and constant parameters. ( For example: f = x Sin[b x] )
First derivative of f with respect to x:   D[f, x]
n-th derivative of f with respect to x:   D[f, {x, n}]

Let f be some expression containing x and other variables and constants. ( For example: f = x y + y^2 + x Sin[b x] )
First partial derivative of f with respect to x:   D[f, x]
n-th partial derivative of f with respect to x:   D[f, {x, n}]
Mixed first partial-derivative:   D[f, x, y] or D[D[f, x], y]

INTEGRALS
Indefinite integral:   Integrate[f, x] (Here f is an expression depending on x)
Definite integral from x=x1 to x=x2:   Integrate[f, {x, x1, x2}] (Here x1 and x2 may be symbolic variables)
Indefinite double Integral:   Integrate[f, x, y] (Here f is an expression depending on x and y)
Definite double Integral:   Integrate[f, {x, x1, x2}, {y, y1, y2}]
Assumptions on parameters in an integral (See also Assumptions section):
If we know that a parameter, n, is in a certain domain, say n > 1, add-on the option: "Assumptions -> n > 1".
   Example:   Integrate[1/x^n, {x, 1, Infinity}, Assumptions -> n>1]
   Example for multiple assumptions:   Integrate[1/x^(n+m), {x, 1, Infinity}, Assumptions -> {n>1, m>0}]
Numerical Integration (necessary if no analytic solution exists):   NIntegrate[f, {x, x1, x2}], where now x1, x2 must be numerical quantities, and similarly for double integrals:   NIntegrate[f, {x, x1, x2}, {y, y1, y2}]
Principal-value integral (Mathematica 5.2 and later):  Integrate[1/x, {x, -1, 2}, PrincipalValue -> True]
Caution on definite integrals having symbolic parameters: see Caution section.

SUMS
Sum[f, {n, nmin, nmax}] , where for example f = 1/n^2 and nmin = 1 and nmax = Infinity.
Sum [f, {n, nmin, nmax, nstep}] , where n goes from "nmin" to "nmax" in steps of "nstep".
Double sum: Sum[f, {m, mmin, mmax},{n, nmin, nmax}]

SERIES EXPANSIONS
Series[f, {x, x0, n}] gives a power series expansion for f as a function of x about the point x=x0 up to terms of order (x - x0)^n.
Series[f, {x, x0, n}, {y, y0, n}] gives a successive power series expansion for f first with respect to x then with respect to y.
Series[f, {x, x0, n}, Assumptions-> {a>0, b<0}] gives a power series expansion for f subject to assumptions on the parameters a,b that appear in f. (See also Assumptions section).

Note: To extract the series expansion without the order-symbol O[...] in the output line, enter Normal[%] after the Series command or just copy and paste desired terms from the output line.

Math comment: The power series returned by Mathematica is a Taylor series if f is an analytic function at x=x0.  Mathematica's power series also exist for functions that are not analytic at x=x0 if the result can be given as a power series containing a finite number of negative powers, or as a power series times a non-expandable function such as Log[x-x0].   Examples: f=1/Sin[x] with x0=0 generates a series with terms 1/x, x, x^3, ..., which is known as a Laurent series;   f=BesselY[0, x] with x0=0 generates a power series and Log[x] times a power series.

PLOTS  (See also Plot Options immediately following.)
Simple plot
   Plot[f, {x, x1, x2}]  plots the expression f from x=x1 to x=x2.   For plotting a function F[x], replace f by F[x].
   Plot[f, {x, x1, x2}, PlotRange-> {f1, f2}]  plots f from x=x1 to x=x2 for values of f in range from f=f1 to f=f2.

Plots with labels
   Plot[f, {x, x1, x2}, AxesLabel -> {"x", "f"}]  plots f from x=x1 to x=x2 and labels x-axis and y-axis with text-strings x and f, respectively.
   Plot[f, {x, x1, x2}, PlotRange-> {f1, f2}, AxesLabel -> {"x", "f"}]  plots f from x=x1 to x=x2, in range from f=f1 to f=f2 and displays axes labels.
   Plot[f, {x, x1, x2}, PlotRange-> {f1, f2}, AxesLabel -> {"x", "f"}, PlotLabel-> "MY PLOT"]  adds plot title MY PLOT to previous plot.

   Note: In the above commands, x and f within quotation marks are text strings and can be replaced by any other text string, for example "x" and "f" can be replaced by "x-axis" and "f= sin x", respectively. To change the font of axes labels or plot label, select the text string between quotes and choose the Format menu to make changes. You can also use keyboard shortcuts to choose italics or larger font size. (For Macintosh computers these shortcuts are Command-I and Command-=, respectively.)
   Caution: If the quotes in "x" and "f" are omitted, they are no longer text strings but rather the actual variables. The result is that the x-axis and y-axis would be labeled with the current definitions of x and f.   If x or f have specific numerical values when the Plot commands are entered, the undesired effect is that these values appear as axes labels.

Plots with color and dashing (for all versions of Mathematica)
   Color plot using RGB components:
      Plot[f, {x, x1, x2}, PlotStyle -> RGBColor[0, 0, 1]]  (* This gives blue curve. Use RGB[1, 0, 0] for red, and RGB[0, 1, 0] for green. *)
   Black or gray plot:
      Plot[f, {x, x1, x2}, PlotStyle -> GrayLevel[0]]  (* Gives black curve. Use this if the plot without GrayLevel[0] option is not dark enough. *)
      Plot[f, {x, x1, x2}, PlotStyle -> GrayLevel[0.3]]   (* Gives medium gray curve. For light gray, use GrayLevel[0.7] *)
   Dashed plot using customized thickness and dashing:
      Plot[f, {x, x1, x2}, PlotStyle -> {Thickness[0.002], Dashing[{0.02, 0.01}]}]
      Plot[f, {x, x1, x2}, PlotStyle -> {Thickness[0.002], Dashing[{0.02, 0.01}], GrayLevel[0]}]
         Numbers in Thickness and Dashing give fraction of total plot width. Dashing numbers are lengths of on/off segments.
         The last plot command gives a black dashed curve. Use this if the plot without GrayLevel[0] option is not dark enough.

Plots with color and dashing (alternative for Mathematica 6 and later versions)
   Color plot using color names:
      Plot[f, {x, x1, x2}, PlotStyle -> Blue]  (* Can replace Blue by Red, Green, Yellow, Orange, Purple, Black, or Gray. *)
      Plot[f, {x, x1, x2}, PlotStyle -> Black]  (* Gives black curve. Use this if the plot without Black PlotStyle option is not dark enough.*)
   Dashed plot using plot-style names :
      Plot[f, {x, x1, x2}, PlotStyle -> Dashed]
   Dashed color plot using plot-style names:
      Plot[f, {x, x1, x2}, PlotStyle -> {Blue, Dashed}]
      Plot[f, {x, x1, x2}, PlotStyle -> {Black, Dashed}]  (*Gives dashed black curve. Use this if the plot without Black PlotStyle option is not dark enough. *)
   Dashed color thick/thin curve using plot-style names:
      Plot[f, {x, x1, x2}, PlotStyle -> {Blue, Thick, Dashed}]
      Plot[f, {x, x1, x2}, PlotStyle -> {Blue, Thin, Dashed}]

Plots of several expressions
   Plot of several expressions on one graph:
      Plot[{f, g, h, ...}, {x, x1, x2}] plots f, g, h, ... from x=x1 to x=x2.
   2-color plot (blue and red) using RGB components:
      Plot[{f, g}, {x, x1, x2}, PlotStyle -> {RGBColor[0, 0, 1], RGBColor[1, 0, 0]}]  
   3-color plot (blue, red, green) using RGB components:
      Plot[{f, g, h}, {x, x1, x2}, PlotStyle -> {RGBColor[0, 0, 1], RGBColor[1, 0, 0], RGBColor[0, 1, 0]}]  
   2-color plot (blue and red) using color names (alternative in Mathematica 6 and later):
       Plot[{f, g}, {x, x1, x2}, PlotStyle -> {Blue, Red}]  
   2-style plot (full black and dashed black) using style names (alternative in Mathematica 6 and later):
       Plot[{f, g}, {x, x1, x2}, PlotStyle -> {Black, {Black, Dashed}}]   
   3-color plot (blue, red, green) using color names (alternative in Mathematica 6 and later):
       Plot[{f, g, h}, {x, x1, x2}, PlotStyle -> {Blue, Red, Green}]  

Plots of functions of 2 variables
   Plot3D[f, {x, xmin, xmax}, {y, ymin, ymax}]  (* gives a 3-d plot of expression f as a function of x and y. *)
   SphericalPlot3D[r, {theta, theta1, theta2}, {phi, phi1, phi2}]   (* gives 3D polar plot with radius r= r(theta, phi) in spherical coords. Requires Mathematica 6 or later.*)
   ContourPlot[f, {x, xmin, xmax}, {y, ymin, ymax}, ContourShading -> False]  (* gives contour plot of f in the xy-plane (equi-value curves) *).
   DensityPlot[f, {x, xmin, xmax}, {y, ymin, ymax}]  (* is similar to ContourPlot with ContourShading->True but has only shading and no contour lines *)
   Contour plot of solutions of f(x, y)= 0 in xy-plane in Mathematica 6 and later:
      ContourPlot[f == 0, {x, x1, x2}, {y, y1, y2}]  (* Here f is an expression depending on x and y. If have a function F[x, y], replace f by F[x, y]. *)
   Contour plot of solutions of f(x, y)= 0 in xy-plane in Mathematica 5 and earlier:
       << Graphics`ImplicitPlot`
      ImplicitPlot[f == 0, {x, x1, x2}, {y, y1, y2}]

Parametric plots (in Mathematica 6 and later versions)
   Parametric plot of y(x) from defined x[t] and y[t]:
      ParametricPlot[{x[t], y[t]}, {t, 0, tmax}, AspectRatio -> Automatic]

Polar plots
   PolarPlot[r, {theta, theta1, theta2}]  (* gives 2-d polar plot of radius r=r(theta) from theta1 to theta2. *)

Showing selected plot features and combining plots
   To show an existing plot in a restricted domain:
      myplot=Plot[Sin[x], {x, 0, 10}]
      Show[myplot, PlotRange->{{x1, x2}, {y1, y2}}] (* For all pts: PlotRange->All *)
   To show several plots superimposed:
      Show[{myplot1, myplot2, myplot3}, PlotRange->{{x1, x2}, {y1, y2}}]

   To create single multicolor plot of a family of functions:
      Plot[Evaluate[Table[Sin[n x], {n, 1, 3}]], {x, 0, Pi}, PlotStyle -> {RGBColor[1, 0, 0], RGBColor[0, 1, 0], RGBColor[0, 0, 1]}]
      Alternative in Mathematica 6 and later:  Plot[Evaluate[Table[Sin[n x], {n, 1, 3}]], {x, 0, Pi}, PlotStyle -> {Red, Green, Blue}]

   To create separate plots of a function as some parameter is varied:
      Mathematica 5 and earlier:   Do[Plot[Sin[n x], {x, 0, Pi}], {n, 1, 4}]
      Mathematica all versions:   Do[Print[Plot[Sin[n x], {x, 0, Pi}]], {n, 1, 4}]
         For more on Plot command inside a Do loop, see the section Graphics incompatibility.

Miscellaeous plot information
To plot lists: see Lists section.

To annotate plots with text, arrows, shapes, etc., in Mathematica 6 and later:   Choose menu item Graphics/Drawing Tools or type control-T.

Comment on use of the Evaluate command inside a Plot command:
Plot commands may run significantly faster if the function or expression to be plotted is enclosed by the Evaluate command, e.g., F[x] is replaced by Evaluate[F[x]] and f is replaced by Evaluate[f].   In certain cases the use of Evaluate is required, as is the case when F[x] has been defined by the ":=" construction and a derivative or integral is contained in F[x], as for example,  F[x_]:= D[Sin[x], x].  (See Caution in Functions section.)

PLOT OPTIONS
Plot[f, {x, x1, x2}, option1, option2, ...]

List of Plot options
To restrict plotted values between f = f1 and f = f2:   PlotRange -> {f1, f2}
To plot all of values of f in the interval (if Mathematica fails to):   PlotRange -> All
To increase the number of sampled plot points used to 200:   PlotPoints -> 200
For labels on the x-axis and y-axis:   AxesLabel -> {"xtext", "ytext"}
     where xtext and ytext are text-strings, and their font style can be changed using Format menu.
For dashed curves:   PlotStyle -> Dashed   or   PlotStyle -> Dashing[{0.02, 0.01}]
     where numbers refer to length of each repeating on/off segment expressed as the fraction of the total width of the graphic.
For colored curves using RGB components:   PlotStyle -> RGBColor[n1, n2, n3]
     where n1, n2, n3 are relative amount of red, green, blue components, resp., e.g., RGB[1, 0, 0] is red.
For colored curves using names (Mathematica 6 and later):
     PlotStyle -> Blue (or PlotStyle -> Red, Green, Yellow, Orange, Purple, Black, Gray).
For dashed colored thick or thin curves using names (in Mathematica 6 and later):
     PlotStyle -> {Blue, Thick, Dashed}  or  PlotStyle -> {Blue, Thin, Dashed}
For gray curves:   PlotStyle -> GrayLevel[n], where n from 0 to 1 with black being n=0.
For specifying colors with opacity:  RGBColor[n1, n2, n3, a] or GrayLevel[n, a].
For 2 curves of different color using names (Mathematica 6 and later):  PlotStyle -> {Blue, Red}
For 2 curves of different color using RGB components:  PlotStyle -> {RGB[0, 0, 1], RGB[1, 0, 0]}
For 2 curves full and dashed using names (Mathematica 6 and later):     PlotStyle -> {{Black}, {Black, Dashed}}
For 2 curves full and thinner dashed curve :   PlotStyle -> {{Thickness[0.004]}, {Thickness[0.002], Dashing[{0.02, 0.01}]}
      where numbers refer to fraction of total graphic width and can be set as desired.
For 2 curves black and gray using names (in Mathematica 6 and later):   PlotStyle -> {Black, Gray}
For 2 curves black and gray:   PlotStyle -> {GrayLevel[0], GrayLevel[0.3]}  
For 2 curves of different color and dashing using names (in Mathematica 6 and later):
     PlotStyle -> {{Blue}, {Red, Dashed}}
     PlotStyle -> {{Thickness[0.004], Blue}, {Thickness[0.002], Dashing[{0.02, 0.01}], Red}}
For tick marks at x1, x2,... and default ticks on y-axis:  Ticks-> {{x1, x2, ...}, Automatic}
For tick marks at x1, x2,... and y1, y2,... :  Ticks-> {{x1, x2, ...}, {y1, y2, ...}}
For tick-mark labels, replace x1 by {x1, "label1"}, etc., in lists of two previous tick-mark examples.
For plot label:   PlotLabel -> FontForm["My Graph", {"Helvetica-Bold", 12}]
For grid-lines on plot:  GridLines -> Automatic
For border around plot:  Frame -> True
For no ticks on frame:  FrameTicks -> None
To set origin:  AxesOrigin-> {x0, y0}
To set y-scale unit to the same display size as x-scale unit:  AspectRatio->Automatic
To set aspect ratio (height/width) of plot = R:    AspectRatio-> R
To set font for all future graphics text:  $TextStyle = {FontFamily -> "Times", FontSize -> 12}
To eliminate shading in the ContourPlot:  ContourShading -> False
Plot3D: To change viewpoint to coordinates x1, x2, x3:  ViewPoint-> {x1, x2, x3}
Plot3D:  To change viewpoint in Mathematica 6 and later:  Click, drag and rotate plot as desired.
Plot3D:   To remove box-lines containing plot: Boxed-> False
Plot3D:   To set ratios of sides of box containing plot:   BoxRatios -> {a, b, c} gives the ratios for the x, y, z sides, resp.
Plot3D example: Plot3D[Sin[x y], {x, -Pi, Pi}, {y, -Pi/2, Pi/2}, AxesLabel -> {"x", "y", " sin(x y)"}, BoxRatios -> {1, .5, .3}]
   where the BoxRatios in the x and y directions make the x and y scale-lengths identical.

Finding current options and setting global options for Plot (and other commands)
To find current options for Plot command:  Options[Plot]
To find current specific option, like PlotRange in Plot command:  Options[Plot, PlotRange]
To change default options for session:  SetOptions[Plot, PlotRange->All]
To determine if a specific option was implimented:  AbsoluteOptions[myplot, PlotRange]
To find all commands or options whose name begins with "Plot", use wildcard inquiry:  ?Plot*
To find all commands or options whose name contains "Axes" anywhere, use wildcard inquiry:  ?*Axes*

Additional plot options in Mathematica 6 and later
To exclude displaying plot at specified points use Exclusions as in:
      Plot[Tan[x], {x, 0, 2 Pi}, Exclusions-> {x= Pi/2, 3Pi/2}]
To annotate plots or graphics with text, arrows, shapes, etc., use menu item Graphics/Drawing Tools or type control-T.
To add slider-control for displaying effect of varying parameters:
     Manipulate[Plot[Sin[a x + b], {x, 0, 6}], {a, 1, 4}, {b, 0, 10}]
     Manipulate[Plot[Sin[a x + b], {x, 0, 6}], {{a, 2, "freq"}, 1, 4}, {{b, 0, "phase"}, 0, 10}]    
where {a, 2, "freq"} means the first slider controls a, has a default value of 2, and has the label "freq".

SIMPLIFY
To simplify algebraic expression for f: Simplify[f]
To really simplify, try: FullSimplify[f].
To simplify, making assumptions on domain of variables in expression, see Assumptions section.
To test if expr1 is identical to expr2:    FullSimplify[expr1-expr2]

Other useful manipulations:
Collect[expr, x]   (* Collects terms of the same power of x in expr. *)
TrigReduce[expr]   (* Rewrites products and powers of trig functions in terms of trig functions of combined arguments. *)
TrigToExp[expr]   (* Converts all trig functions to complex exponentials in expr. *)
TrigExpand[expr]   (* expands out trig functions in expr. *)

ASSUMPTIONS
By default, Mathematica takes symbolic variables to be complex. To make assumptions on variables in the commands Simplify, FullSimplify, Integrate, Series, and Refine use the option Assumptions-> assum, where assum can be, for example,   x>a, or 1>y>0, or Re[x]>0, or Element[p, Integers], or Element[x, Reals], or Element[{x, y}, Reals].    (For keyboard-shortcut symbolic entry of Element[x, Reals], enter x escape-key el escape-key Reals.)
Examples:
    Simplify[Sqrt[x^2]/x, Assumptions-> x>0]  (* The result is 1 *)
    Simplify[Sqrt[x^2]/x + Sqrt[y^2]/y, Assumptions-> {x>0, y>0}]    (* The result is 2 *)
    Integrate[Exp[-n x], {x, 0, Infinity}, Assumptions-> Re[n]>0]  (* The result is 1/n *)

To set assumptions globally on variables in commands Simplify, FullSimplify, Integrate, Series, Refine:
    $Assumptions = assum    (* for one assumption *)
    $Assumptions = {assum1, assum2, assum3}    (* for several assumptions *)
To remove these globally set assumptions, enter $Assumptions= True.

Note: In Mathematica 6 and later, for the special cases of Simplify, FullSimplify and Refine, can drop "Assumptions-> " and just write the assumption, as in Simplify[f, assum] or Simplify[f, {assum1, assum2}].

Comment on Refine command: Refine[expr, assum] gives the form of expr that would be obtained if symbols in it were replaced by explicit numerical expressions satisfying the assumption assum.   Example:  Refine[Log[x], Assumptions-> x<0]   gives   I*Pi + Log[-x].

EVALUATING EXPRESSIONS
To evaluate an expression f numerically:   N[f]
To evaluate f to a precision of M digits:   N[f, M]
Note: The N[f, M] command will fail to give an output of precision greater than machine precision (typically 6 digits) if f contains machine precision numbers or if f contains numbers entered with a decimal point. For example, N[10.*Pi, 12] returns 31.4159 whereas N[10*Pi, 12] returns 31.4159265359

To evaluate f where f depends on x (and other variables) for a particular value x=b, use   f /. x -> b   which returns f evaluated for the case that x = b but does not change anything in the current expression for f or x. This is equivalent to entering x = b, then entering f, then entering Clear[x]. If one just enters x=b and then f, the variable x is replaced by b everywhere in f and this becomes the new expression for f until a new value of x is entered or until the Clear[x] command is used.

To perform several replacements for variables in f enter    f /. {x -> a, y -> b, z -> c}
Alternatively, if define function f[x_, y_, z_], enter f[a, b, c] to return the desired value of f and leave the original f[x, y, z] unchanged.

For distinctions between expressions or functions that are defined by the ":= " and "="constructions, and for possible pitfalls when trying to evaluate them, see the section on Functions.

For correcting errors in evaluating, plotting or tabulating expressions involving derivatives and integrals, see Caution on evaluating or plotting in Functions section.

To clear functions and variables:
Clear assigned value for variable x:   Clear[x]
Clear assigned values for variables x, a,... :   Clear[x, a,...]
Clear definition for f or f[x] and for assigned values for x, a,... :   Clear[f, x, a,...]
Clear definitions for all functions, expressions and variables (except Mathematica's built-in definitions):   Clear["Global`*"]
   Ex1:  Clear[f, x]; f= x; x= 3; f   (* Result is f=3 *)
   Ex2:  Clear[f, x]; f= x; x= 3; x=1; f   (* Result is f=1 *)
   Ex3:  Clear[f, x]; f= x; x= 3; x=1; Clear[x]; f   (* Result is f=x *).

Limit of an expression:
To find limit of f as x->x0:   Limit[f, x->x0]   (* Use this if limit of f is independent of approach direction *)
To find limit of f as x->x0 from smaller values of x:   Limit[f, x->x0, Direction -> +1]]
To find limit of f as x->x0 from larger values of x:   Limit[f, x->x0, Direction -> -1]]   (* This is the default direction for Limit[f, x->x0] *)

TABLES
To create a table of values of x and the function F[x] for x values from x1 to x2 in increments of xstep:
    Table[{x, F[x]}, {x, x1, x2, xstep}]
To create a table of x and the expression f for x values from x1 to x2 in increments of xstep:
    Table[{x, f}, {x, x1, x2, xstep}]

The Table command automatically creates a "list". (See also Lists section) For example:
    mylist= Table[{x, Sin[x]}, {x, 0, 10, 0.1}]  creates a list called "mylist" given by
    {{0, Sin[0]}, {0.1, Sin[0.1]}, {0.2, Sin[0.2]}, ... {10, Sin[10]}}

To display a table or list in columns:
    Table[{x, Sin[x]}, {x, 0, 10, 0.1}]//TableForm  or  mylist//TableForm  or  TableForm[mylist]
To put labels at top of columns in displayed table or list:
    TableForm[mylist, TableHeadings -> {None, {"x", "sin(x)"}}]   adds labels x, sin(x) at top of table display
To put labels on left-hand side of rows displayed table or list:
    TableForm[mylist, TableHeadings -> {{"x1", "x2", "x3", ...}, None}]   adds labels x1, x2, x3, ... at side of table display
To put labels on top and on left-hand side of displayed table or list:
    TableForm[mylist, TableHeadings -> {{"x1", "x2", "x3", ...}, {"x", "sin(x)"}}]

To improve visual display of output see Printout section.

To create and display an array of graphics (for example, 3D polar plots of spherical harmonics for l= 0, 1, and 2 in Mathematica 6 and later):
    mylist=Table[SphericalPlot3D[ Evaluate[Abs[SphericalHarmonicY[l, m, theta, phi]]], {theta, 0, Pi}, {phi, 0, 2 Pi}, ImageSize -> 100, Boxed -> False, Axes -> None], {l, 0, 3}, {m, 0, l}]; mylist//TableForm

Comment on use of the Evaluate command inside a Table or Plot command:
When tabulating or plotting a function or expression, the Table or Plot commands may run significantly faster if a function or expression is enclosed by the Evaluate command, e.g., F[x] is replaced by Evaluate[F[x]] and f is replaced by Evaluate[f].   (This is true in the graphics array example of the previous paragraph.)  In certain cases the use of Evaluate is required, as is the case when F[x] has been defined by the ":=" construction and a derivative or integral is contained in F[x], as for example,  F[x_]:= D[Sin[x], x].  (See Caution in Functions section.)

DISPLAYING OUTPUT
If output from a certain command "expr" is not wanted, follow with ";" as in expr;
To show a one-line outline form of the output:   expr //Short
To show an n-line outline form of the output:   Short[expr, n]
For displaying numerical output, see Printout section.

COMPLEX VARIABLES
Mathematica considers symbolic variables to be complex unless specific real values are assigned to them.
ComplexExpand[expr] displays real and imaginary parts of expr assuming all variables (if any) are real.
    Example: ComplexExpand[E^(I x)] gives Cos[x] + I Sin[x]
ComplexExpand[expr, {x1, x2,...}] displays expr assuming all variables are real except x1, x2,... which are complex.
    Example: ComplexExpand[E^(I x), x] gives E^(-Im[x]) Cos[Re[x]]+ I E^(-Im[x]) Sin[Re[x]]
To declare variables to be real:  This should be done with commands using the Assumptions option.
Useful commands: Re[z], Im[z], Abs[z], Conjugate[z], Arg[z], Residue[f, {z, z0}]

SOLVING EQUATIONS
Algebraic eqs.:
    Solve[eq, x]  (* Here eq has form f(x)==0 *)
    Solve[{eq1, eq2}, {x, y}]   (* Here eq1 and eq2 have form f(x,y)==0. *)
To evaluate an expression using solutions:   expr /. sol   (* For example,  sol= Solve[{eq1, eq2}, {x, y}] *)
To obtain numerical solutions:   Use NSolve instead of Solve.
To eliminate variables between a set of equations:
    Eliminate[{eq1, eq2}, var]   or  Eliminate[{eq1, eq2, eq3}, {var1, var2}]
To test whether two expressions are identical:   f==g   or    FullSimplify[f-g]   (*These return True or 0, respectively, if f and g are identical*)
To reduce an expression using equations or inequalities for variables:
    Reduce[expr, vars] or Reduce[expr, vars, dom] if variables defined over domain dom= Reals, Integers, etc.

Transcendental eqs (without symbolic parameters, e.g., solve f=0, where f= Tan[x]-x):
Numerical soln: FindRoot[f==0, {x, x0}]   (* Searches for a numerical solution to f(x)=0, starting from point x=x0 *)
Graphical soln:  Plot[f, {x, x1, x2}]  (* Observe crossings of x-axis, use smaller x1, x2 range, and repeat. *)
Finding local minimum of function f(x) starting hunt at x0:   FindMinimum[f, {x, x0}]
Finding local minimum of function f(x, y) starting hunt at x0, y0:   FindMinimum[f,{{x, x0]}, {y, y0}}]
Finding local maximum: use FindMaximum in place of FindMinimum.

Differential eqs:
DSolve[{eq1, eq2,...}, y[x], x]   (* for analytical solutions *)
NDSolve[{eq1, eq2,...}, y[x], {x, xmin, xmax}]   (* for numerical solutions *)
    Example:  sol = NDSolve[{y''[x]+y[x]==0, y[0]==1., y'[0]==0}, y[x], {x, 0, Pi}]
This command gives sol= {{y[x] -> InterpolatingFunction}}.  Let f be the y[x] solution as given by this interpolating function. Then f= sol[[1,1,2]], which follows from list extraction rules given below. To plot y[x], use Plot[f, {x, 0, Pi}]. Alternatively, take the solution to be y[x]/.sol, which returns {f}. Since f and {f} give the same Plot and TableForm output, it may be unnecessary to distinguish between them. (If necessary, brackets can be removed by methods in Lists section.)

Extraction rules for output lists of solutions (see also Lists section):
    Ex 1:  sol= {{x -> a, y -> b}, {x -> c, y -> d}}.   Here a= sol[[1, 1, 2]], b= sol[[1, 2, 2]], c=sol[[2, 1, 2]], d=sol[[2, 2, 2]].
    Ex 2:  sol= {{x -> g}}.   Here g= sol[[1, 1, 2]].

PRINTOUT
Given a table or list:   zlist=Table[{x, Sin[x], Cos[x]}, {x, 0, Pi, 0.1}]
To get printout in table form:   zlist//TableForm
To get printout with larger separation between columns:   Table[{x, " ", Sin[x], " ", Cos[x]}, {x, 0, Pi, 0.1}]//TableForm
To get printout via print statements as values are created:   Do[Print[x, " ", Sin[x], " ", Cos[x]], {x, 0, Pi, 0.1}];
To get pretty printout without jags in column alignment:
   PaddedForm[expr, {nt, nr}] gives nt total digit spaces with nr digits to right of decimal point:
       pf[w_]:=PaddedForm[w, {10, 6}];
       Do[ Print[pf[x], pf[Sin[x]], pf[Cos[x]]], {x, 0, Pi, 0.1}]

DO LOOP
Do[expr, {i, imin, imax}]   (* Index i from imin to imax in steps= 1. For non-integers, i ends at largest value ≤ imax. *)
Do[expr, {i, imin, imax, istep}]   (* Index i from imin to imax in steps= istep. For non-integers, i ends at largest value ≤ imax. *)
Do[expr1; expr2; expr3, {i, imin, imax, istep}]   (* Caution: In this form, the final expr is followed by "," not by ";" *)
    Alternate forms of the previous command:
        Do[{expr1, expr2, expr3}, {i, imin, imax, istep}]
        Do[{expr1; expr2; expr3}, {i, imin, imax, istep}]
Do[{expr1; expr2; expr3}, {i, imin, imax}, {j, jmin, jmax}]
   Caution: In above double iteration, the loop over j is done for each i, then i is summed-over last.
Using Do-loop to create separate plots of a function as some parameter is varied:
    Mathematica 5.2 and earlier:   Do[Plot[Sin[n x], {x, 0, Pi}], {n, 1, 4}]
    Mathematica all versions:    Do[Print[Plot[Sin[n x], {x, 0, Pi}]], {n, 1, 4}]
For discussion of the correct syntax when a Plot command is inside a Do loop, see the section Graphics incompatibility.

CONDITIONALS
If[z>a, x=x1]   (* If z>a then x=x1, otherwise do nothing. *)
If[z>a, x=x1, x=x2]   (* If z>a then x=x1, else x=x2 *)
If[z == 0 , x=x1, x=x2]   (* If z=0 then x=x1, else x=x2 *)
If[z>a && z<b , x=x1, x=x2]   (* If z>a AND z<b, x=x1, else x=x2 *)
If[z>a || z<b , x=x1, x=x2]   (* If z>a OR z<b, x=x1, else x=x2 *)
Which[test1, value1, test2, value2...] (* Returns value corresponding to first true test *)
    Example:   F[x_]:=Which[x<x1, f1,  x ≥x1 && x≤x2, f2,  x>x2, f3] creates a piecewise function that is equal to f1, f2, or f3, for x<x1, x2≥x ≥x1, or x>x2, respectively.

GRAPHICS:
For making plots of functions and lists see the sections on Plots and Lists, respectively.  To annotate graphics with text, arrows, shapes, etc., in Mathematica 6 and later:   Choose menu item Graphics/Drawing Tools or type control-T.

Graphics containing points, lines, and geometric figures, etc., can be created and displayed as follows:
       Without options:   Show[Graphics[p]]   (In Mathematica 6 and later, can also use  Graphics[p] )
       With options:        Show[Graphics[p], options]
       Multiple objects:   Show[Graphics[{p1, p2, ...}, options]   or   Show[{Graphics[p1], Graphics[p2], ...}, options]
where p is a graphics primitive such as Point, Line, Circle, etc, with appropriate arguments, and the options are those available for plots and described in the section on Plot Options.  In Mathematica 6 and later, braces surrounding the argument of the Show command can be omitted, as in Show[Graphics[p1], Graphics[p2], ..., options].  For other differences in graphics commands between Mathematica 5 and later versions, see the section on Graphics incompatibility

Useful primitives:
    Point[{x, y}],   Line[{{x1, y1}, {x2, y2},...}],   Circle[{x, y}, r],   Disk[{x, y}, r],
    Rectangle[{xmin, ymin}, {xmax, ymax}],    Text[expr, {x, y}].
The argument of Line is a list of at least two points, and in Mathematica 6 and later, the argument of Point may be a list of points, as in the Line primitive, in which case all those points will appear in the graphic.   The {x,y} coordinates specify the center of Circle, Disk or Text, and r is the radius of Circle or Disk.

Options:
Options associated with the display of the entire set of primitives are placed at the end of the Show command. An option associated with a single primitive is known as a "graphics directive" and is combined with the primitive inside braces as in the following examples:
    {PointSize[d], Point[{x, y}]},     {Thickness[d], Line[{{x1, y1}, {x2, y2}}]},
    {Thickness[d], RGBColor[1, 0, 0], Circle[{x, y}, r]},
where d is the fraction of the total width of the graphic. (In Mathematica 6 and later, RGBColor[1, 0, 0] can be replaced by Red.)

Combining plots and graphics primitives in Mathematica 6 and later:
    Show[myplot, Graphics[p], options], where for example myplot= Plot[Cos[x], {x, 0, 10}, AspectRatio -> Automatic]
    Show[myplot, Graphics[{{p1, option1}, {p2, option2}, {p3, option3}}], options]
where option1, option2, option3 are options ("graphics directives") associated with primitives p1, p2, p3, resp.

Combining plots and graphics primitives in Mathematica 5:
Express the plot data in a list (or Table) form and plot it as a Graphic using Line primitive:
    Show[Graphics[{Line[T], p2, p3}, options]
    Show[Graphics[{{Line[T]], optionT}, {p2, option2}, {p3, option3}}, options}],
where for example, T= Table[{x, Exp[-0.2x]Sin[2x]}, {x, 0, 10, .1}] and optionT is RGBColor[1,0,0].

Examples in Mathematica 6 and later:
    T = Table[{x, Exp[-0.2x]Sin[2x]}, {x, 0, 10, .1}];   (* Creates list for later examples *)
    myplot = Plot[Exp[-0.2 x] Sin[2 x], {x, 0, 10}, AspectRatio -> Automatic] (* Creates plot for next example *)
    Show[myplot, Graphics[{Point[{0, 0}], Circle[{0, 0}, 1]}], PlotRange -> {{-2, 10}, {-2, 2}}]
    Show[Graphics[{Point[{0, 0}], Line[T], Circle[{0, 0}, 1] } ]]
    Show[Graphics[{{PointSize[.05], Point[{0, 0}]}, {Blue, Line[T]}, {Thickness[0.005], Red, Circle[{0, 0}, 1]}}], PlotRange -> {{-2, 10}, {-2, 2}}, Axes -> True]
Note that Show[Graphics[Line[T]]] gives the same result as ListPlot[T, Joined->True], which appears in the section on Lists. (In earlier versions of Mathematica, Joined is replaced by PlotJoined).

Examples in Mathematica 5:
To get correct aspect ratio and plot range, need to include options for AspectRatio and PlotRange in Show command. (Also, color option must be RGBColor.) :
    Show[Graphics[{Point[{0, 0}], Line[T], Circle[{0, 0}, 1]}], AspectRatio -> Automatic, PlotRange -> {{-1, 10}, {-1, 1}}]
    Show[Graphics[{{RGBColor[0, 0, 1], Line[T]}, {PointSize[.05], Point[{0, 0}]}, {Thickness[0.005], RGBColor[1, 0, 0], Circle[{0, 0}, 1]}}], AspectRatio -> Automatic, PlotRange -> {{-2, 10}, {-2, 2}}]

LISTS
Specifying elements in a list:
A list is a collection of items contained within curly-brackets, such as {a, b, c}. Other examples:
   u= {{a, b}, {c, d}, {e, f}};   v= {{j, k, p}, {q, r, s}};   x= {{c1}, {c2}, {c3}};   w= {t};
To pick-out elements of lists, u[[n]], v[[n]], x[[n]], w[[n]] refer to n-th element of lists, and u[[n, m]], v[[n, m]], x[[n, m]] refer to n-th element, m-th sub-element:
   u[[1]]= {a, b};  u[[1, 2]]= b;  u[[3, 1]]=e;  v[[1]]= {j, k, p};  v[[1, 2]]= k;  v[[2, 1]]=q;  x[[1, 1]]=c1;   x[[2, 1]]=c2;   w[[1]]=t;
To remove all internal brackets from a list:   unew= Flatten[u]   (* Result is unew= {a, b, c, d, e, f} *)
To remove external brackets from a one-number list:   wnew=w[[1]] or {wnew}= w   (* Result is wnew= t *)
To string-together lists:  If y= {{a, b}, {c, d}},  and z= {{e, f}, {g, h}}, then:
   Flatten[{y, z}, 1]  gives {{a, b} , {c, d}, {e, f}, {g, h}}
which is said to flatten the list {y, z} to level 1. Similarly,  Flatten[{y, z}, 2]  gives {a, b, c, d, e, f, g, h} which flattens to level 2.

To create a list:
data=Table[{x, Sin[x]}, {x, 0, 10, .2}]   (* Creates data= {{0, Sin[0]}, {.2, Sin[.2]}, ... , {10, Sin[10]}}. *)
To display a list in neat table form:  data//TableForm

To combine two 1-d lists to create a paired list:
   xdata=Table[x, {x, 0, 10, .2}]   (* Creates xdata= {0, .2, ..., 10}. *)
   ydata=Table[Sin[x], {x, 0, 10, .2}]   (* Creates ydata= {Sin[0], Sin[.2], ..., Sin[10]}. *)
   data=Transpose[{xdata,ydata}]  (* Creates data= {{x1, y1}, {x2, y2}, ...} as before *)
Alternate method:
   data=Table[{xdata[[i]], ydata[[i]]}, {i, 1, imax}]   (* Here must supply imax = dimension of array = (10/0.2)+1 = 51. *)

To plot a list or multiple lists:
ListPlot[data] (* This puts data points on plot, where data is a paired list as previously defined *)
ListPlot[data, Joined->True] (* To connect data points on plot. In earlier versions of Mathematica, Joined is replaced by PlotJoined. *)
ListPlot[{data1, data2}]   (* This replaces obsolete "MultipleListPlot" command*)

To obtain an interpolating function for f[x] from lists for f and x :
flist= {0, 1, 4.2, 9.3, 12.0};   xlist= {0, 1, 2, 3, 5.5};
f= ListInterpolation[flist, {xlist}];   Plot[f[x], {x, 0, 4}]
Note that the function is called f[x] although it was created from "f= ListInterpolation..." without the x-variable mentioned. The x-variable in f[x] is associated with {xlist}. (One would obtain the same plot from Plot[f[u], {u, 0, 4}].) For a simple linear interpolation (if the previous interpolation fails):   f= ListInterpolation[flist, {xlist}, InterpolationOrder -> 1].

To obtain the best fit of data by a linear combination of a given set of independent functions:
Fit[data, funcs, vars], as for example, f= Fit[data, {x, x^2, x^3, Log[x]}, x], where data is a list having the structure described earlier, and the set of functions are here x, x^2, x^3, Log[x].

To obtain the best fit of data by finding the best values of parameters in a given expression:
FindFit[data, expr, pars, vars], as for example, FindFit[data, a*x + b*Log[x], {a, b}, x], which finds the best values of a and b to fit the data using the expression a*x + b*Log[x].

List Extraction-Rules (for output lists created by commands such as Solve):
When the list contains an arrow "->" between items, it acts like a "," element-separator:

Ex. 1:  sol= {{x -> a, y -> b}, {x -> c, y -> d}}.  Then a= sol[[1, 1, 2]], b= sol[[1, 2, 2]], c=sol[[2, 1, 2]], d=sol[[2, 2, 2]].

Ex. 2:  sol= {{x[t] -> Cos[t]}}.  Then Cos[t]=sol[[1, 1, 2]].
Here the first (and only) element within the external brackets is {x[t] -> Cos[t]}, and inside this first element, the first (and only) sub-element inside its surrounding brackets is x[t] -> Cos[t], which contains two sub-sub elements separated by "->".

Ex. 3:  sol= {{x -> a}, {x -> b}, {x -> c}, {x -> d}}.  Then a=sol[[1, 1, 2]], b=sol[[2, 1, 2]], c=sol[[3, 1, 2]], d=sol[[4, 1, 2]]

Ex. 4:  sol=Solve[{eq1, eq2, eq3, eq4}, {w, x, y, z}]. The solution for these 4 simultaneous eqs in 4 unknowns w, x, y, z is returned in the form {{w -> a}, {x -> b}, {y -> c}, {z -> d}}, so the solution for x is sol[[2, 1, 2]].   (As usual, eq1, eq2, etc., are written with "==" signs, as in the form f(w, x, y, z)== 0)

LISTS AND ARRAYS
In the following, farray and xarray are 1-d arrays, meaning that farray[i] and xarray[i] are each a number (or an expression) that depends on i for each integer i in range i=1 to imax.   The representations of farray and xarray as lists are flist and xlist, respectively.

To make a 1d-list from a 1d-array:   flist=Table[farray[i], {i, 1, imax}]
To make a 1d-array from a 1d-list:   Do[farray[i]=flist[[i]], {i, 1, imax}];
To make a paired-list from two 1-d arrays:    xflist=Table[{xarray[i], farray[i]}, {i, 1, imax}]
To make a paired-list from two 1-d lists:    xflist=Table[{xlist[[i]], flist[[i]]}, {i, 1, imax}]
To plot a list of paired elements:   ListPlot[xflist, Joined->True] (*In earlier versions of Mathematica, Joined is replaced by PlotJoined *)
To make 2 arrays from a 2d-list:   Do[{xarray[i]=xflist[[i, 1]]; farray[i]=xfist[[i, 2]], {i, 1, imax}]
To make an array from a function:   Do[ x=x1+(i-1)*(x2-x1)/(imax-1); farray[i]=f[x], {i, 1, imax}]

To make an array from a list whose elements are enclosed in brackets:
If U = {{U1}, {U2}, {U3}, ...}, then to make a 1-d array, called Uarray, whose i-th entry is Ui:   Do[Uarray[i]= U[[i, 1]], {i, 1, imax}].

To create a 2d array from a 2d function:
Let the 2d array be Farray[i, j] to be created from a specified function F[x,y] defined for the variables x and y having values in the ranges x1, x2, and y1, y2, resp. Let the number of i,j points = imax, jmax, resp.   (The function in the following example happens to have the form of the Langevin magnetization function.):

    F[x_,y_]:=Tanh[x/y]; x1 = -4; x2 = 4; y1 = 1; y2 = 3; imax = 100; jmax = 100;
    dx = (x2 - x1)/(imax - 1);  dy = (y2 - y1)/(jmax - 1);  (* Creates the intervals between grid points for which Farray[i, j] will be calculated *)
    Do[x = x1 + (i - 1)*dx; y = y1 + (j - 1)*dy;  Farray[i, j] = F[x, y], {i, 1, imax}, {j, 1, jmax}];  (* This fills-in Farray[i, j] values at the appropriate x and y grid points *)

To create a 2d function from a 2d array:
    Let the function G[x, y] be created from the 2-d array Farray[i, j] having structure as above:
    G[x_, y_] := Farray[IntegerPart[1 + (x - x1)/dx], IntegerPart[1 + (y - y1)/dy]];  (* This sets G[x, y] to be the value of array at nearest i,j grid-point lying just below the x,y values *)
    Plot3D[G[x, y], {x, x1, x2}, {y, y1, y2}] (* The result closely agrees with Plot3D[F[x, y], {x, x1, x2}, {y, y1, y2}] *)

    Alternatively, create and plot a function G[x, y] starting from a list containing above data and use more accurate interpolation:
    data = Table[Tanh[x/y], {x, x1, x2, dx}, {y, y1, y2, dy}]; (* Note the structure of this starting list *)
    G= ListInterpolation[data, {{x1, x2}, {y1, y2}}];
    Plot3D[G[x, y], {x, x1, x2}, {y, y1, y2}] (* The result is indistinguishable from Plot3D[F[x, y], {x, x1, x2}, {y, y1, y2}] *)

MATRICES and MATRIX EQUATIONS
Enter Matrices and N-dimensional vectors from the input palette using the 2-by-2 small-box array surrounded by parentheses for a matrix, and the vertical array of 2 small boxes surrounded by parentheses for a vector. To add additional rows, press the return key while holding the control key down (control-return). To add additional columns press the comma key while holding the control key down (control-,).

For matrix multiplication use a period. For example, M1.M2 where M1 and M2 are matrices.
Useful commands: Inverse[M], Det[M], Tr[M], Transpose[M], ConjugateTranspose[M], MatrixPower[M, n], Eigensystem[M], Eigenvalues[M]

To display matrix M as columns and rows, use M//MatrixForm or M//TraditionalForm. Otherwise, Mathematica will display matrix as a list of lists.
To display vector X as a column, use X//MatrixForm or X//TraditionalForm.
To display matrices and vectors as columns and rows throughout session, choose Cell/Default Output Type/TraditionalForm.

To use matrices to solve a set of linear, inhomogeneous eqs: Express eqs as Y=M.X, where Y is a known N-dimensional vector and M is a known N-by-N matrix. Solve for unknown N-dimensional vector X, using the command X=Inverse[M].Y

ANIMATIONS (In Mathematica 6 and later)
In Mathematica 6 and later, the built-in command Animate[expr, {t, t1, t2}] generates an animation of expr in which t varies continuously from t1 to t2. In a typical case, expr is a 2-d or 3-d plot evaluated for a specific value of the time variable t.   If the animation is jittery, the number of still-frames can be increased by choosing the time interval between successive still-frames to be smaller than Mathematica's default value. To do this, use Animate[expr, {t, t1, t2, dt}], where dt is the time-variable interval between successive frames, which can be taken as small as desired. An alternative method that may give better results is described in the NOTE below.  For Mathematica versions before 6.0, see the section Animations in Mathematica 5.2 or earlier.

Examples:
Animate[Plot[Cos[t]Sin[x], {x, 0, 2Pi}, PlotRange -> {-1, 1}], {t, 0, 2Pi}]
    Plot-command options can be used inside the Plot[...] command as shown here for the PlotRange option.
    To enlarge screen display, click on plot and stretch it by sliding the tiny black rectangle in the lower right-hand corner downward and outward.
Animate[Plot3D[Sin[2x]Sin[3y]Cos[t], {x, 0, Pi}, {y, 0, Pi}, PlotRange -> {-1, 1}], {t, 0, 2Pi}]
    For a mesh in animated 3-d plots, use following option in Plot3D:   Mesh -> 20

Options for Animate:   AnimationRepetitions->n,   AnimationRunning->False,   DefaultDuration -> m,   where n= no. of animation cycles before stopping,   m= no. of seconds animation takes to run, and False means that the animation will not run until start button is pressed.

CAUTION:   The animation will fail if the expression to be animated does not contain explicit variables when it appears in the argument of the Plot command. Therefore, the following fails:   Animate[Plot[f, {x, 0, 2Pi}, PlotRange -> {-1,1}], {t, 0, 2Pi}], where previously f has been defined by a command such as f=Cos[t]Sin[x].   This can be fixed by introducing a function of x and t in the Plot command, for example,   Animate[Plot[f[x,t], {x, 0, 2Pi}, PlotRange -> {-1,1}], {t, 0, 2Pi}], where previously we have defined  f[x_,t_]:=Cos[t]Sin[x].   (Comment: We could also have defined f[x_,t_] by using the "=" symbol instead of the ":=" symbol provided that x and t did not have specific values when the definition was entered. [See section on Functions].)
An elegant alternative which works for all expressions (whether or not they are explicit functions of x and t) is to define a function as follows:
    anim[f_] := Animate[Plot[f, {x, 0, 2 Pi}, PlotRange -> {-1, 1}], {t, 0, 2 Pi}]
Then, for example, enter   anim[Cos[t]Sin[x]]   or enter   anim[f], where f has been previously defined by f=Cos[t]Sin[x].

To animate a function f[t] as t evolves from t1 to t2 (specify f, t1, t2, and function range fmin, fmax):
    Animate[Plot[f[tp], {tp, t1, t}, PlotRange -> {{t1, t2}, {fmin, fmax}}], {t, t1+.00001(t2-t1), t2}]
where for example we could have previously defined f[t_]:= Sin[t]; t1= 0; t2= 2 Pi; fmin=-1; fmax=1;
       (* Note: The t1+.00001(t2-t1) start for t avoids the error-message that the plot of f[tp] has a zero range of tp in the first frame when tp=t=t1. *)

To follow the single point evolving as above without a trajectory trail:
    Animate[Graphics[{PointSize[0.01], Point[{t, f[t]}]}, PlotRange -> {{t1, t2}, {fmin, fmax}}], {t, t1, t2}]

NOTE:  The following alternative eliminates the viewing box and slider display of the previous animations and may sometimes give better results than using the Animate command:   Create a sequence of plots using "Do[Print[Plot[...],...]".   The animation is then activated by selecting the output graphics cells (by clicking on the enclosing blue bracket) and choosing the menu item Graphics/Rendering/Animate Selected Graphics. For example, the command lines to create the graphics cells for the previous animations are:
    Do[Print[Plot[Cos[t] Sin[x], {x, 0, 2 Pi}, PlotRange -> {-1, 1}]], {t, 0, 2 Pi, Pi/20}]
    Do[Print[Plot3D[Sin[2 x] Sin[3 y] Cos[t], {x, 0, Pi}, {y, 0, Pi}, PlotRange -> {-1, 1}]], {t, 0, 2 Pi, Pi/20}]
    Do[Print[Plot[f[tp], {tp, t1, t}, PlotRange -> {{t1, t2}, {fmin, fmax}}]], {t, t1+.00001(t2-t1), t2, (t2-t1)/40}]
    Do[Print[Graphics[{PointSize[0.01], Point[{t, f[t]}]}, PlotRange -> {{t1, t2}, {fmin, fmax}}]], {t, t1, t2,(t2-t1)/40}]
The animation is then activated by selecting the output graphics cells (by clicking on the enclosing blue bracket) and choosing the menu item Graphics/Rendering/Animate Selected Graphics. (Control the animation with tiny icons at bottom of notebook page. If animation runs too fast or slow change size of step in t in the last entry in the t do-loop, e.g., change 20 to 40 in {t, 0, 2 Pi, Pi/20}.)

Animations of functions defined by lists:
To animate a function f(x,t) defined by a paired list of x-values and f values depending on the symbolic time variable t:
Example:
    mylist=Table[{x, Cos[10x-t]*Exp[-x]}, {x, 0, 5, 0.05}]; (* creates a paired list list of x and f(x,t) for a propagating, decaying wave *)
    Do[Print[ListPlot[mylist, PlotRange -> {-1, 1}, Joined -> True]], {t, 0, 2 Pi, Pi/20}]
The animation is then activated by selecting the output graphics cells (by clicking on the enclosing blue bracket) and choosing the menu item Graphics/Rendering/Animate Selected Graphics. (Control the animation with tiny icons at bottom of notebook page. If animation runs too fast or slow you can change size of step in t in the last entry in the t do-loop, e.g., change 20 to 40 in {t, 0, 2 Pi, Pi/20} to slow down the animation.)

Trajectory animations:
To create a trajectory animation from time t=t1 to t=t2 for a given set of Cartesian coordinate functions x[t] and y[t]:
    Animate[ParametricPlot[{x[tp], y[tp]}, {tp, t1, t}, AspectRatio -> Automatic, Axes -> False, PlotRange -> {{xmin, xmax}, {ymin, ymax}}], {t, t1+.00001(t2-t1), t2}]
where must specify numerical values for t1, t2, and the plot ranges xmin,xmax, ymin,ymax. (To include axes, use option Axes->True.)
CYCLOID EXAMPLE:
    x[t_]:= t-Sin[t]; y[t_]:= 1-Cos[t]; t1 = 0; t2 = 20; xmin = 0; xmax = 20; ymin = -.1; ymax =2.1;
    Animate[ParametricPlot[{x[tp], y[tp]}, {tp, t1, t}, AspectRatio -> Automatic, Axes -> False, PlotRange -> {{xmin, xmax}, {ymin, ymax}}], {t, .00001(t2-t1), t2}]
To see the previous animation as a moving dot without a trajectory trail:
    Animate[Graphics[{PointSize[0.01], Point[{x[t], y[t]}]}, PlotRange -> {{xmin, xmax}, {ymin, ymax}}], {t, t1, t2}]
More elaborate cycloid animation:
   Animate[Show[ParametricPlot[{x[tp], y[tp]}, {tp, t1, t}], Graphics[{{Red, Circle[{t, 1}, 1]}, {PointSize[0.005], Point[{t, 1}]}, {PointSize[0.015], Point[{x[t], y[t]}]}, {Blue, Line[{{x[t],y[t]}, {t, 1}}]}, {Thin, Line[{{0, 0}, {t2, 0}}]}}], Axes -> False, AspectRatio -> Automatic, PlotRange -> {{xmin, xmax}, {ymin, ymax}}], {t, t1 + .00001 (t2-t1), t2, dt}]

Trajectory animations using lists:
In these examples, we calculate x[t],y[t] trajectory points at a large number of points (npts), for t values equally spaced from t1 to t2, and store the result in lists. As shown below, these list entries are then retrieved and used in the animations.
    npts = 200; (* npts= number of (x,y) data points= no. of frames *)
    dt = (t2 - t1)/(npts - 1);
    mylist = Table[{x[t], y[t]}, {t, t1, t2, dt}];   (* This list is the full set of x[t], y[t] points *)
    mylist2[n_] := Table[{mylist[[m, 1]], mylist[[m, 2]]}, {m, 1, n}]   (* This list is the partial set of x[t], y[t] points up to the n-th step *)
   Animate[ListPlot[mylist2[n], Joined -> True, PlotRange -> {{xmin, xmax}, {ymin, ymax}}], {n, 1, npts}] (* In earlier versions of Mathematica, Joined is replaced by PlotJoined *).
To see the previous animation as a moving dot without trajectory trail:
    Animate[ListPlot[{mylist[[n]]}, PlotStyle -> PointSize[0.01], PlotRange -> {{xmin, xmax}, {ymin, ymax}}], {n, 1, npts, 1}] (* Note the explicit step increment of 1 in the iterator not required previously. *)
Alternate commands for the previous two animations:
    Animate[Graphics[Line[mylist2[n]], PlotRange -> {{xmin, xmax}, {ymin, ymax}}], {n, 1, npts}]
       (* For thicker line, replace Line[mylist2[n]] by {Thickness[0.015], Line[mylist2[n]]} in previous command *)
To see the previous animation as a moving dot without trajectory trail:
    Animate[Graphics[{PointSize[0.01], Point[{mylist[[n]]}]}, PlotRange -> {{xmin, xmax}, {ymin, ymax}}], {n, 1, npts, 1}]

Creating GIF Animations:
To make a gif animation to insert into Powerpoint or into a webpage or to make a movie of the animation, construct a Table of plots and use Export command as described in the section Exporting/Importing data and graphics. An example of an animated webpage made by this method is shown at http://pantherfile.uwm.edu/sorbello/www/classes/cycloid.html.

ANIMATIONS (In Mathematica 5.2 or earlier)
Load animation package with <<Graphics`Animation` and create a sequence of plots using the commands listed below. Double-click on the bracket containing all the output graphics cells (but not the input cell) to collapse the output cells to a single pane. Then choose menu item Cell/Animate Selected Graphics.  

Note on compatibility with Mathematica 6 and later :  All the Mathematica 5 animations listed below will work in Mathematica 6 and later if the Do command is replaced by the Animate command. (See previous section Animations in Mathematica 6 and later.)   However, the modified animations will not work in Mathematica 5. If compatibility is desired, then each graphics command, such as Plot, ListPlot, Graphics, etc., inside a Do loop must be enclosed by a Print command, following the rule given in the Graphics incompatibility section.  In such cases, the animation procedures and display for both versions of Mathematica revert to those of Mathematica 5, except that the menu-item for animating cells is Graphics/Rendering/Animate Selected Graphics.

Examples
Do[Plot[Cos[t]Sin[x], {x, 0, 2Pi}, PlotRange -> {-1, 1}], {t, 0, 2Pi}]
Do[Plot3D[Sin[2x]Sin[3y]Cos[t], {x, 0, Pi}, {y, 0, Pi}, PlotRange -> {-1.1, 1.1}], {t, 0, 2Pi}]
    For a mesh in animated 3-d plots, use following option in Plot3D:   Mesh -> 20
To animate a function f[t] as t evolves from t1 to t, specify t1, t2, function range fmin, fmax:
    Do[Plot[{tp, f[tp]}, {tp, t1, t}, Axes -> True, PlotRange -> {{t1, t2}, {fmin, fmax}}], {t, t1+.00001(t2-t1), t2}] 
       (* Note: The t1+.00001(t2-t1) start for t avoids the error-message that the plot of f[tp] has a zero range of tp in the first frame when tp=t=t1. *)
To animate a function f[t] as above, but with specified time interval between frames = dt (nominally dt=(t2-t1)/100 for 101 frames):
    Do[Plot[{tp, f[tp]}, {tp, t1, t}, Axes -> True, PlotRange -> {{t1, t2}, {fmin, fmax}}], {t, t1+.00001(t2-t1), t2, dt}]  
To follow the single point evolving as above without a trajectory trail:
    Do[Show[Graphics[{PointSize[0.01], Point[{t, f[t]}]}, PlotRange -> {{t1, t2}, {fmin, fmax}}, Axes -> False]], {t, t1, t2, dt}]

Trajectory animations:
To create a trajectory animation from time t=t1 to t=t2 given x[t] and y[t]:
    Do[ParametricPlot[{x[tp], y[tp]}, {tp, t1, t}, AspectRatio -> Automatic, Axes->False,PlotRange -> {{xmin, xmax}, {ymin, ymax}}], {t, t1+.00001dt, t2, dt}]
where must specify numerical values for t1, t2, the plot ranges xmin, xmax, ymin, ymax, and nominally take dt=(t2-t1)/100 for 101 animation frames.
CYCLOID EXAMPLE:
    x[t_]:= t-Sin[t]; y[t_]:= 1-Cos[t]; t1 = 0; t2 = 20; xmin = 0; xmax = 20; ymin = -.1; ymax =2.1; dt = 0.2;
    Do[ParametricPlot[{x[tp], y[tp]}, {tp, t1, t}, AspectRatio -> Automatic, Axes->False,PlotRange -> {{xmin, xmax}, {ymin, ymax}}], {t, t1+.00001dt, t2, dt}]
To see the previous animation as a moving dot without a trajectory trail:
    Do[Show[Graphics[{PointSize[0.015], Point[{x[t], y[t]}]}, PlotRange -> {{xmin, xmax}, {ymin, ymax}}, Axes -> False]], {t, t1, t2, dt}]
More elaborate cycloid animation:
    Do[Show[Graphics[{Line[Table[{x[tp], y[tp]}, {tp, t1, t, dt}]], {PointSize[0.015], Point[{x[t], y[t]}]}, {RGBColor[1, 0, 0], Circle[{t, 1}, 1]}, {PointSize[0.01], Point[{t, 1}]}}, AspectRatio -> Automatic, PlotRange -> {{xmin, xmax}, {ymin, ymax}}]], {t, t1+.0001(t2 - t1), t2, dt}]

Trajectory animations using lists:
In these examples, we calculate x[t],y[t] trajectory points at a large number of points (npts), for t values equally spaced from t1 to t2, and store the result in lists. As shown below, these list entries are then retrieved and used in a do-loop command to create still-frames, which are subsequently animated as previously described.
    npts = 100; (* npts= number of (x,y) data points= no. of frames *)
    dt = (t2 - t1)/(npts - 1);
    mylist = Table[{x[t], y[t]}, {t, t1, t2, dt}];   (* This list is the full set of x[t], y[t] points *)
    mylist2[n_] := Table[{mylist[[m, 1]], mylist[[m, 2]]}, {m, 1, n}]   (* This list is the partial set of x[t], y[t] points up to the n-th step *)
    Do[ListPlot[mylist2[n], Joined -> True, PlotRange -> {{xmin, xmax}, {ymin, ymax}}], {n, 1, npts}] (* In earlier versions of Mathematica, Joined is replaced by PlotJoined. *)
To see the previous animation as a moving dot without trajectory trail:
    Do[ListPlot[{mylist[[n]]}, PlotStyle -> PointSize[0.01], PlotRange -> {{xmin, xmax}, {ymin, ymax}}], {n, 1, npts}]

EXPORTING AND IMPORTING DATAFILES AND GRAPHICS
Exported files are sent to a default directory (usually user's home directory).
To find this directory: Directory[]
To change this directory: SetDirectory["pathname"], where, e.g., pathname= /Users/home/mathwork.

DATAFILES
To create and Export datafiles (such files must have the ".dat" suffix):
    Begin with a datalist or Table, e.g., mylist=Table[{x, Sin[x], Cos[x]},{x, 0, 7, 0.1}]
    Export["myfile.dat", mylist]
This creates the datafile myfile.dat which consists of 71 lines, each line having values of x, Sin[x], Cos[x] separated by spaces.
To append an expression to an existing file:   expr >>>myfile (same as PutAppend[expr, "myfile"])
To make an Excel file from a created datafile:   Change the filename suffix ".dat" to ".xls" and open the new file in Excel.

To Import a datafile as a list:
    zlist= Import["myfile.dat"], where myfile.dat contains lines of data with numbers on each line separated by space(s).
To create 1-d arrays from above list:
    Do[A[i] = zlist[[i,1]]; B[i]=zlist[[i, 2]], C[i]=zlist[[i, 3]], {i, 1, imax}]
where for our previous myfile.dat, A, B, C, refer to x, Sin[x], and Cos[x], respectively, and there are imax=71 entries for each of the arrays A[i], B[i], C[i].

GRAPHICS, ANIMATIONS AND MOVIES
To Export a single graphic (for subsequent use by Word, Powerpoint, Web Browsers, etc.):
   Method 1: Select Graphic, then use menu item File/Save Selection As...GIF (or choose PDF, JPG, or other file type in menu)
   Method 2: Export["myfile.gif", myplot] to create a gif file from myplot.  Similarly, "myfile.jpg" creates jpg file, etc.

To insert the exported graphic file in Word, etc.:
   Conventional method:  Use Word menu item  Insert/Picture ...from file (and browse to the saved file)
   Better method:   Create a PDF file of the selection, as in Method 1 above, then open it in Adobe Acrobat, use the "snapshot tool" (camera icon) to capture (and automatically copy) the desired portion of the pdf file. Then paste into Word, and resize as desired. (For a Mac computer, the screen image and printout by this method were better than obtained by the conventional method. The screen image and the hardcopy printout from an HP inkjet printer were excellent, but the printout from an HP laserjet printer was not as sharp.)

To create a gif animation from a Table of plots (or other graphics):
    Export["myfile.gif", myplots], where myplots is a Table of plots or other graphics and myfile.gif is the created gif animation file to be inserted into Powerpoint as a movie or to be be used as an image source in an html file.   Example of a Table of plots:
  myplots=Table[Plot[Cos[t]Sin[x], {x, 0, 2Pi}, PlotRange-> {-1, 1}], {t, 0, 2Pi}]
An example of an animated webpage made by this method is shown at http://pantherfile.uwm.edu/sorbello/www/classes/cycloid.html.

To create a movie (in .avi format) from a Table of plots (or other graphics):
    Export["myfile.avi", myplots], where myplots is a Table of plots or graphics (as in previous paragraph) and myfile.avi is the created movie.  (The movie can be opened in QuickTime, for example.)

To create a QuickTime movie (in .mov format) from a sequence of plots (or other graphics):
    Create the desired sequence, e.g.,   myplots = Do[Print[Plot[Cos[t] Sin[x], {x, 0, 2 Pi}, PlotRange -> {-1, 1}]], {t, 0, 2 Pi}] then select the set and use menu item File/Save Selection As.../QuickTime.

FIELD PLOTS
Mathematica's vector field plots display the field at fixed grid points by drawing an arrow emanating from each grid point. The magnitude of the field at a grid point is proportional to the length of the arrow, and the direction of the field at a grid point is in the direction of the arrow.   This is not the conventional field-line plot, where the magnitude of the field is proportional to the density of field lines. In Mathematica 7, StreamPlot gives a streamline plot which is similar to the conventional field-line plot, but with possible discrepancies as described below.

In Mathematica 7 :

VECTOR-FIELD PLOTS
To create a vector-field plot of A(x,y) having Cartesian components (Ax, Ay):
      VectorPlot[{Ax, Ay}, {x, x1, x2}, {y, y1, y2}]
To specify number of grid pts and size of arrows use VectorPoints and VectorScale, resp.

Example (magnetic field of a TE10 mode in a square waveguide):
      VectorPlot[{Cos[2 x] Cos[Pi y], 2 Sin[2 x] Sin[Pi y]}, {x, 0, Pi}, {y, 0, 1}, VectorScale -> 0.035, VectorPoints -> {31, 10}, AspectRatio -> 1/Pi, PlotLabel->"TE10 propagation direction ->"] (* Aspect ratio choice makes magnitude of unit vectors along x and y directions of plot identical, so angles of vectors in plot are physical angles in space *)

To create a 3d vector-field plot of A(x,y,z) having Cartesian components (Ax, Ay, Az):
      VectorPlot3D[{Ax, Ay, Az}, {x, x1, x2}, {y, y1, y2}, {z, z1, z2}]

Example (electric field in region exterior to a uniformly charged sphere):
      r = (x^2 + y^2 + z^2)^(1/2); w = Which[r > 0.25, 1, r <= 0.25, 0]; VectorPlot3D[{w*x/r^3, w*y/r^3, w*z/r^3}, {x, -1, 1}, {y, -1, 1}, {z, -1, 1}, VectorPoints -> {8, 8, 8}, VectorScale -> 0.1]

STREAMLINE PLOTS
To create a plot of the streamlines of A(x,y):    StreamPlot[{Ax, Ay}, {x, x1, x2}, {y, y1, y2}]

Note: Mathematica's streamline plots, as opposed to the conventional field-line plots, are not required to be continuous where there are no sources and are not required to have a local field-line density proportional to the field magnitude. One can try to obtain a conventional field-line plot by specifying an appropriate list of points through which streamlines pass, as shown in examples 1b, 2b and 3b below. Some experimentation with plot options may be required in the general case.

Example 1a (2d point source at the origin):
      StreamPlot[{x/(x^2 + y^2), y/(x^2 + y^2)}, {x, -1, 1}, {y, -1, 1}]

Example 1b (2d point source at the origin- corrected for continuity and line density):
      pts = Table[{0.2 Cos[t], 0.2 Sin[t]}, {t, Pi/30, 2 Pi, Pi/30}];
      StreamPlot[{x/(x^2 + y^2), y/(x^2 + y^2)}, {x, -1, 1}, {y, -1, 1}, StreamPoints -> {pts, Automatic, 1}, StreamScale -> Full, Epilog -> {Red, Point[pts]}]
  where in option arguments {pts, Automatic, 1} gives continuous lines cut-off at length 1, Full gives full lines with single arrow, and Epilogue shows the points in the list "pts" in red.

Example 2a (Dipole arrangement of two 2d point sources):
StreamPlot[{x/(x^2 + y^2) - (x + 1)/((x + 1)^2 + (y + 1)^2), y/(x^2 + y^2) - (y + 1)/((x + 1)^2 + (y + 1)^2)}, {x, -2, 1}, {y, -2, 1}]

Example 2b (Dipole arrangement of two 2d point sources- corrected for continuity and line density):
pts1 = Table[0.1 {Cos[t], Sin[t]}, {t, Pi/20, 2 Pi, Pi/20}]; pts2 = Table[{-1 + 0.1 Cos[t], -1 + 0.1 Sin[t]}, {t, Pi/20, 2 Pi, Pi/20}]; pts = Flatten[{pts1, pts2}, 1]; StreamPlot[{x/(x^2 + y^2) - (x + 1)/((x + 1)^2 + (y + 1)^2), y/(x^2 + y^2) - (y + 1)/((x + 1)^2 + (y + 1)^2)}, {x, -2, 1}, {y, -2, 1}, StreamPoints -> {pts, Automatic, 5}, Epilog -> {Red, Point[pts]}, StreamScale -> Tiny]

Example 3a (Grounded infinite cylinder in a uniform external electric field):
r = (x^2 + y^2)^(1/2); v = x/r^2 - x; ex = -D[v, x]; ey = -D[v, y]; exout = Which[r > 1, ex, r <= 1, 0]; eyout = Which[r > 1, ey, r <= 1, 0]; plot = StreamPlot[{exout, eyout}, {x, -5, 5}, {y, -5, 5}]; Show[{plot, Graphics[Circle[{0, 0}, 1]]}]

Example 3b (Grounded infinite cylinder in a uniform external electric field- corrected for continuity and line density):
pts1 = Table[{-5, y}, {y, -5, 5, 0.25}]; pts2 = Table[{5, y}, {y, -5, 5, 0.25}]; pts = Flatten[{pts1, pts2}, 1]; r = (x^2 + y^2)^(1/2); v = x/r^2 - x; ex = -D[v, x]; ey = -D[v, y]; exout = Which[r > 1, ex, r <= 1, 0]; eyout = Which[r > 1, ey, r <= 1, 0]; plot = StreamPlot[{exout, eyout}, {x, -5, 5}, {y, -5, 5}, StreamPoints -> {pts, Automatic, 10}, Epilog -> {Red, Point[pts]}, StreamScale -> Tiny]; Show[{plot, Graphics[Circle[{0, 0}, 1]]}]

Note: In examples 1b, 2b and 3b, we specified a set of points for streamlines to pass through where we knew the field field lines are uniformly spaced (exactly in 1b, and to an excellent approximation in 2b and 3b). The uniform spacing is due to symmetry in 1b, due to our choice of points very close to the point sources in 2b, and due to our choice of points far away from the cylinder in 3b. (The manipulation of lists of points using Flatten is described in the section on Lists.)

In Mathematica 6 :
To create a vector-field plot of the vector-field A(x,y) having Cartesian components (Ax, Ay):
    Load the plot package using <<VectorFieldPlots`;
    VectorFieldPlot[{Ax, Ay}, {x, x1, x2}, {y, y1, y2}]

In Mathematica 5.2 and earlier:
  To create a vector-field plot of grad f(x,y) from x1 to x2 and y1 to y2:
    Load the plot package using <<Graphics`PlotField`;
      then enter:   PlotGradientField[f, {x, x1, x2}, {y, y1, y2}]
       or enter:     PlotGradientField[f, {x, x1, x2}, {y, y1, y2}, HeadWidth->0.01, HeadLength->0.01, HeadCenter->0]

PROGRAMMING
Example of simple numerical integration program:
F[x_]:=x^2
mysum=0.0; x1=0.0; x2=10.0; npts=1001;
dx= (x2-x1)/(npts-1);
Do[
x=x1 + (n-1)*dx;
mysum=mysum + F[x], {n, 1, npts}];
integralval = mysum*dx;
Print["Integral= ", integralval]

Modules:
A module is a set of instructions that can be called repeatedly with different input variables, and thus functions as a subroutine. The syntax is as follows:   Module[{x, y, ...}, expr1; expr2;...; exprlast]. When the module is entered as a command it evaluates expr1, expr2, ... exprlast and returns the value of exprlast as its output.   {x, y, ...} specifies that occurrences of the symbols x, y, ...in expr1, expr2, etc., should be treated as local. The following is a "module" (subroutine) of the previous program. One can specify x1, x2, and npts in a sub-routine call (assuming F[x] already has been defined). To integrate a pre-existing F[x] function using this module, enter, for example: myintegrate[0, 10, 1001], where the module myintegrate is defined as follows:

myintegrate[x1_, x2_, npts_]:=Module[{n, mysum, x, dx, integralval},
mysum=0.0;
dx= (x2-x1)/(npts-1);
Do[{
x=x1 + (n-1)*dx,
mysum = mysum + F[x]},
{n,1,npts}];
integralval=mysum*dx
];

Modules can also be used as shortcuts for commands. For example,
   myplot[f_]:= Module[{}, Plot[f, {x, 0, 2 Pi}, PlotRange -> {-1, 1}]]
Then to plot a previously defined expression g over the range indicated, enter myplot[g].   For example, g=Sin[x]; myplot[g]. Of course, in this particularly simple case of a single command, one might as well have directly defined the function   myplot[f_]:= Plot[f, {x, 0, 2 Pi}, PlotRange -> {-1, 1}]

VECTOR ANALYSIS
Load this package in Mathematica 5 and earlier by typing:   <<Calculus`VectorAnalysis`
Load this package in Mathematica 6 and later by typing:   <<VectorAnalysis`
Choose spherical coordinate system by typing:  SetCoordinates[Spherical[r, theta, phi]]
Choose cartesian coordinate system by typing:  SetCoordinates[Cartesian[x, y, z]]
Choose cylindrical coordinate system by typing:  SetCoordinates[Cylindrical[r, phi, z]]
Vector operations:   Div[f], Curl[f], CrossProduct[v1,v2], v1.v2, where vector fields f, v1, v2 are specified as { , , } and v1.v2 is the dot product.
Gradient and Laplacian of a function g:   Grad[g],  Laplacian[g]
Over-riding the set-coordinates:   Div[F[x, y, z], Cartesian[x, y, z]] if previously SetCoordinates[Spherical[r, theta, phi]]

MISCELLANEOUS

GRAPHICS INCOMPATIBILITY (Mathematica 6 and later vs. Mathematica 5)
Graphics are treated somewhat differently in later versions of Mathematica than they are in Mathematica 5 and earlier versions. A program containing graphics may run in earlier versions of Mathematica but fail in Mathematica 6 and later. For a list of incompatibilities between Mathematica 5 and 6 (or later versions), see the Mathematica Tutorial on the Wolfram site.  If commands in an old program are incompatible with Mathematica 6 and later, one solution is to use the command <<Version5`Graphics` which replaces Mathematica 6 and later graphics with Mathematica 5 graphics. Mathematica 6 and later graphics are restored with <<Version6`Graphics`. If the result is unsatisfactory, or if features of Mathematica 6 and later are desired, the graphics commands in the old program have to be modified. For a list of new graphics features in Mathematica 6 and later, see New in 6.0 on the Wolfram website.

If you want programs to run in both versions of Mathematica, this can often be accomplished by minor modification of incompatible graphics commands. In some cases, the incompatibility is caused by Plot commands inside Do loops, and this can be fixed easily by enclosing each Plot command by a Print-command. Similarly, commands such as Graphics[Point...] inside Do loops need to be enclosed by a Print statement. This syntax is needed because Mathematica 6 and later treats graphics output like other output and therefore suppresses it in the execution of a Do loop unless a Print-command is used. The same syntax is valid in Mathematica 5.2 and earlier, but there the Print-command was optional.

HELP
In addition to Mathematica's "HELP" menu, you can get help on a specific command by typing ?Command. For example: ?Plot.  You can also use the "wildcard" character "*", as in ?Plot*, which returns the names of all commands or options whose name begins with "Plot" and provides links to help for each item. Similarly, to find help on all commands or options containing the word "Point" anywhere, use ?*Point*. There is also free on-line help at Wolfram's Documentation Center, which is also linked from the "HELP" menu.

WOLFRAM DATABASES
In Mathematica 6 and later, you can access data from physics, chemistry, mathematics, etc., that are in the database on the Wolfram site. To see the database categories use the help inquiry:    ?*Data
For example, to see a specific molecular structure that you can dynamically rotate:     ChemicalData["Caffeine", "MoleculePlot"]
More generally ChemicalData["name","property"] gives the value of the specified property for the chemical "name".   ChemicalData["name"] gives a structure diagram for the chemical with the specified name.   ChemicalData["class"] gives a list of available chemicals in the specified class.

KEYBOARD SHORTCUTS AND ALIASES
Keyboard shortcuts using escape-key "esc" before and after textstrings:
   Greek symbols: esc-g-esc for gamma, esc-G-esc for capital gamma, etc.
   Other esc-X-esc shortcuts:
      X= inf, hb, el, deg, vec,   for infinity, h-bar, element, degree, vector-sign, resp.
      X= int, dd, ii, ee,   for integral sign, differential, I, E, resp. (These are stylized, active forms).
      X= TeX language string for single symbols, for example:
      X= \gamma, \Gamma, \hbar, \infty, \partial, \times, \sum, \int, \propto, \rightarrow, \sim, \equiv, \cdot, \perp, \parallel

Creating aliases (custom keyboard shortcuts) for Mathematica Notebooks:
   To create a new notebook where if you type esc-name1-esc or esc-name2-esc you get text1 and text2, resp.:
      nb = CreateDocument[{}, InputAliases -> {"name1" -> "text1", "name2" -> "text2"}]
      Example:   nb = CreateDocument[{}, InputAliases -> {"aa" -> "Assumptions->", "tt" -> "//TableForm", "pp" -> "Plot[f, {x, x1, x2}, PlotRange->All]"}]

Keyboard shortcuts for math input:
   Exponent: Control-6.   Example:   x Control-6 n  gives x to the n-th power.
   Square Root symbol: Control-2
   Division symbol: Control-/
   Escape to the next input character after completing above inputs: Control-space
   Over-symbol: Control-7.   Examples:  For x-hat: x Control-7 ^ Control-space.   For x-vector: x Control-7 esc-vec-esc Control-space.

Shortcut for entering text-mode style in notebooks:
   Put cursor on new line and click (or click on existing cell-bracket) and type shortcut key (Command-7 for Macintosh operating systems).

Shortcut for entering a complicated command or a set of commands:
   Modules and functions can simplify entering a complicated command or a set of commands. See section on Modules.

TeX
Mathematica to TeX conversion: TeXForm[expr]
TeX to Mathematica conversion: ToExpression["input",TeXForm], where, for example, input = \sqrt{b^2-4ac}

NOTEBOOK PAGE-BREAKS
To show page-breaks in Mathematica 5 or earlier: Format/Show PageBreaks
To show page-breaks in Mathematica 6 and later: File/Printing Settings/Show Page Breaks
To return to notebook view: Use same menu items as above (acts as toggle switch).
To create a page-break between cells in Mathematica 6 and later, use menu item Insert/Page Break.
To remove a page-break between cells in Mathematica 6 and later, delete the appropriate pagebreak-bar (heavy horizontal line across screen) displayed by File/Printing Settings/Show Page Breaks. To do this, position the cursor over the bar to get cursor to change from ">--<" to "|<--", then click mouse to select bar, and finally press delete key. (You can also click on the tiny icon at the end of the pagebreak bar to select the bar.)

FIXING COMMON MATHEMATICA ERRORS
Use curly brackets "{" and "}" to enclose a list or group of similar objects in commands, and use square brackets "[" and "]" to enclose arguments of functions or the entire set of objects or arguments appearing in a command.

When defining an explicit function such as F[x_]:= Tan[x]/x or G[x_,y_]:= y*Sin[x], etc., be sure to use an underscore after each argument on the left hand side (but never on the right hand side).

Be careful about multiple uses of expressions containing variables whose values are changed.   Fewer problems are likely to occur if use delayed assignment ":=" in defining functions or if evaluate an expression with the substitution command as in "f/. x->b".   Use the appropriate Clear command to ensure that variables and functions do not have spurious pre-existing values when they are used.

Be careful about missing "}" or ";" or "]" in Do Loops, missing "," and "]" in Print statements, and "}", "{" and "," in lists.

If Mathematica's instruction alignment in a block of commands looks bad, one of the above rules is probably being violated.

If Mathematica gives error message about Tags and Protected quantities, check for violations of above rules.

Empty plots or plot error messages such as "f is not a machine-size real number at x=..." are often due to undefined variables, or a missing "," or ";" separator. Examples include typographical errors, functions that have not been defined, variables that have not been specified in the expression to be plotted, an expression to be plotted that has an imaginary part, or a set of commands inside a Do Loop in which a Print statement is immediately followed by a Plot command without the appropriate "," or ";" separator between them.

An error message that some numerical string "is not a valid variable" occurs when a function cannot be evaluated for the chosen value of the variable. This may occur if a function or expression contains operations like derivatives or integrals and/or the ":=" construction is used in defining such functions or expressions. For example, if   F[x_]:= D[Sin[x], x] and the value at x=2 is desired, entering F[2] returns a meaningless result, and Plot[F[x], {x, 0, 10}] and Table[F[x], {x, 0, 10, 0.1}] also fail. To find F[2], enter F[x]/.x->2 or enter x=2 followed by the command Evaluate[F[x]]. To make plots or tables of F[x], replace F[x] by Evaluate[F[x]] in the argument of the Plot or Table commands. (See Caution on evaluating or plotting in Functions section.)

Mathematica error messages containing "shadowing" or "symbol used in multiple contexts" occur if a symbol or name "X" is used before loading a package that contains "X" as the name of a defined function.   Example: "X" ="Grad", where "Grad" is defined in a command line, and afterwards the vector analysis package is loaded. In this case, the vector-analysis package definition of "Grad" will over-write the previous one.   If resulting complications are severe, a brute-force fix is to quit Mathematica, re-launch it, and load package correctly at start of new session. Once package is loaded, "X" will be protected from subsequent conflicting uses.  Be careful loading packages:  The correct syntax is   <<PackageName`  or  Needs["PackageName`"].

CAUTION ON MATHEMATICA'S EVALUATION OF INTEGRALS CONTAINING SYMBOLIC PARAMETERS
Sometimes (hopefully only rarely) a definite integral that has a symbolic parameter in its upper or lower limits of integration or that contains a symbolic parameter in its integrand may be evaluated incorrectly by Mathematica in the following sense: The integral evaluates to an inverse trig function or other multi-branch function and Mathematica fails to take (or to specify) the correct branch of the function. This can be regarded either as a "bug" or a failure of the Assumptions-option to pick out the correct solution.

An example of this is the integral of 1/(2 + Cos[y]) from y=0 to y=x, where x is a real symbolic parameter in the upper limit and x>Pi. Mathematica's result for the integral involves the ArcTan function, but by taking the wrong branch of the ArcTan function, Mathematica obtains a discontinuous function of x, whereas the integral must be continuous in x. Further details are at https://pantherfile.uwm.edu/sorbello/www/classes/mathematica_badintegral.pdf.

In general, one should be careful to take the correct branch of any multi-branch function that appears in the output of Mathematica's Integrate command (or of any other command for that matter). As a precaution, it is advisable to plot Mathematica's result as a function of the symbolic parameter, and see if the result is consistent with the analytic properties of the integral. In the previous example, Mathematica's error can be corrected by simply adding appropriate constants in piecewise regions of parameter space to get the appropriate branch of the ArcTan function.

____________________________

ABOUT THIS DOCUMENT:
This webpage is a continually updated list of Mathematica commands, examples, tricks and Mathematica frustration-avoidance measures that I have found useful over the years in my work as a physicist and teacher. It is intended to be a quick-reference help-file that one might consult instead of, or prior to, accessing Mathematica's extensive Help menu or Wolfram's on-line Documentation Center.   I am posting this so that my students and I, and anyone else who may find it useful, can access it from the web, do browser word-searches on subjects within this document, and copy/paste examples directly into an ongoing Mathematica session. The order of subjects listed is intended to roughly reflect the order of commonly referenced Mathematica subjects for students in science and engineering.

This document can be located by Googling "sorbello mathematica" or, apparently, "mathematica frustration".   For Mathematica beginners, I have also posted a bare-bones guide to Mathematica at https://pantherfile.uwm.edu/sorbello/www/classes/mathematica_primer.pdf.

Prof. Richard S. Sorbello
Department of Physics
University of Wisconsin-Milwaukee
Milwaukee, WI 53211
Email: sorbello@uwm.edu